Your LLM Concurrency Limit Is a Guess: 6 Questions to Answer Before You Set One in .NET
Here's a question I couldn't answer a few weeks ago: how many LLM calls is my .NET API allowed to have in flight right now? The honest answer was "whatever the HTTP stack lets through", and the standard resilience handl
Here's a question I couldn't answer a few weeks ago: how many LLM calls is my .NET API allowed to have in flight right now?
The honest answer was "whatever the HTTP stack lets through", and the standard resilience handler's rate limiter defaults to 1,000 permits. My (simulated) provider could serve 16 calls at once on a good day and 5 during a brownout. Nothing in between complained until callers started timing out.
This post isn't the full build. It's the six questions I now ask before I let anyone type a concurrency number into appsettings.json for model calls, with the C# shape of each answer.
Tech Skill Builder is $5/month for a very limited time only (normally $10). Grab it now before it goes back to $10. Join Tech Skill Builder. The complete, tested adaptive-limiter project behind this post is in there.
Building an AI product that pays per model call? My AI SaaS Starter Kit gives you multi-tenancy, Stripe billing and metered AI credits in .NET.
Q1: Is your limit a measurement or a guess?
Picture a nightly job that summarises support tickets and a chat endpoint that share one provider key. Someone sets MaxConcurrency = 64 because it "felt safe". Here's what a fixed number did in my drill (simulated provider, 100 req/s, capacity drops from 16 to 5 for five seconds, then recovers):
| Limit | Good answers / s when healthy | p95 during brownout |
|---|---|---|
| none | 100.0 | 2,431 ms |
| fixed 64 | 100.0 | 2,233 ms |
| fixed 8 | 65.5 | 307 ms |
| adaptive (hybrid, latency-based) | 99.5 | 692 ms |
High fixed limits never trigger when it matters. Low ones throw away a third of your traffic on a normal day. The provider's real capacity moves during the day, so the limit has to move too.
Q2: Where does the gate sit, and can anything skip it?
If the limit lives in one controller, the background job walks right past it. I put it in the IChatClient pipeline (Microsoft.Extensions.AI), because every model call already goes through that interface:
services.AddChatClient(sp => sp.GetRequiredKeyedService<IChatClient>("provider"))
.UseLogging()
.Use((inner, sp) => new AdaptiveConcurrencyChatClient(
new AttemptTimeoutChatClient(inner, attemptTimeout), // timeout INSIDE the gate
sp.GetRequiredService<AdaptiveConcurrencyLimiter>()
/* signal, Retry-After, TimeProvider, logger ... */));
// full registration + options binding in the complete project
Two details matter more than they look. The per-attempt timeout sits inside the limiter, because a timeout is the loudest overload signal you'll get and the limiter must see it. And SDK-level retries are off, so every attempt is its own sample instead of three hidden ones.
Q3: What happens to the slot when a call goes wrong?
A slot that leaks once is a limit that shrinks forever. So each call holds a lease that can only be completed once, and disposing it without an outcome means "ignore this one":
using var lease = await AcquireOrThrowAsync(options, ct); // throws CapacityExceededException if full
var start = _time.GetTimestamp();
try
{
var response = await base.GetResponseAsync(messages, options, ct);
lease.Success(/* normalized latency, see Q5 */);
return response;
}
catch (Exception ex)
{
lease.Complete(/* outcome from Q4 */, _time.GetElapsedTime(start).TotalMilliseconds);
throw;
}
// lease internals (complete-once, dispose = ignored) in the complete project
The Api maps CapacityExceededException to 503 with Retry-After. A shed caller learns that in microseconds instead of waiting 2.5 seconds to time out.
Q4: Which failures mean "the provider is full"?
This is the question people skip. If a malformed prompt or a user closing the tab shrinks the limit, one buggy client throttles everyone.
public static CallOutcome Classify(FailureKind kind) => kind switch
{
FailureKind.None => CallOutcome.Success,
FailureKind.RateLimited or FailureKind.Overloaded or FailureKind.Timeout
=> CallOutcome.Dropped, // 429, 502/503/529, 408/504
_ => CallOutcome.Ignored, // 400s, caller cancellation, open breaker ...
};
// status/exception -> FailureKind mapping lives in FailureClassifier (complete project)
My rule: when in doubt, ignore. Missing a signal is cheaper than inventing one.
Q5: Are you measuring load, or just answer length?
This one surprised me. On an idle provider, a 300-token answer took about 4.5x as long as a 40-token one. A latency-based limiter reads that as congestion and starts shedding healthy traffic.
The fix is to measure "milliseconds per 100 output tokens" instead of total time:
double rtt = outputTokens is > 0
? elapsedMs / outputTokens.Value * referenceTokens // e.g. referenceTokens = 100
: elapsedMs; // no usage returned: fall back, and count it
In a drill where answers jumped from 20β60 tokens to 250β300 with no real overload, total latency shed 140 calls for nothing. Per-token latency shed 9.
Q6: Does the limit react before errors arrive?
AIMD (add 1 when busy, multiply by 0.9 on a drop) is easy and it waits for errors. In my brownout the provider just got slower and never returned one, so AIMD never cut: its limit averaged 56 and p95 sat at 2,192 ms.
Latency-based algorithms like Netflix's Gradient2 compare each sample to a long-running average and shrink when things get slower. I use a hybrid: Gradient2 for latency, plus a multiplicative cut on a real drop (at most once per few samples, so one burst of 429s counts once). The skeleton of the update looks like this:
public int Update(LimitSample sample)
{
var shortRtt = sample.Rtt.TotalMilliseconds;
var longRtt = _longRtt.Add(shortRtt);
if (sample.InFlight < _estimated / 2) return Limit; // not enough traffic to learn from
var gradient = Math.Clamp(_s.RttTolerance * longRtt / shortRtt, 0.5, 1.0);
// smoothing, queue-size headroom, min/max clamps, drop handling ...
// full Gradient2 + hybrid implementation in the complete project
return Limit;
}
One thing a concurrency limit won't fix
With a 60 requests-per-second quota on the provider, every strategy I tried got the same 195 429s. Eleven slots of ~117 ms calls still allow ~94 calls a second. Concurrency limits and rate limits solve different problems. If your provider has a quota, you need both.
Checklist
- [ ] The limit adapts; no hand-picked number in config
- [ ] One gate in the
IChatClientpipeline that nothing can skip - [ ] Attempt timeout inside the gate, SDK retries off
- [ ] Complete-once leases; abandoned calls release without a sample
- [ ] Only 429 / 503-class / timeouts count as drops
- [ ] Latency normalised per output token, fallback counted
- [ ] Shed calls get
503+Retry-Afterimmediately - [ ] A separate rate limiter if the provider has a quota
All numbers are local measurements on a simulated provider, not a real model. Treat them as how the mechanics behave, not a promise about your provider.
Get the complete project
The snippets above are the skeleton. The full, tested .NET 10 project, with Clean Architecture layers, the limiter middleware and leases, AIMD, Gradient2 and the hybrid limit, the outcome policy, per-token latency, the provider simulator and the load-drill tool, plus a long PDF walkthrough with architecture and request-flow diagrams, is in Tech Skill Builder. It's $5/month for a very limited time only (normally $10). Grab it now before it goes back to $10.
Shipping an AI product of your own? The AI SaaS Starter Kit gives you multi-tenancy, Stripe subscriptions, metered AI credits, RAG and streaming chat in .NET.
Do you know your app's concurrency limit for model calls, or did you guess it too?
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.