Load shedding at the service edge: why unbounded queues cause collapse, Little's law sizing, ASP.NET Core rate limiting and concurrency limiters, 503 versus 429 with Retry-After, priority shedding, and client behaviour that keeps the system recoverable.
An overloaded service with unbounded queues collapses: requests wait so long that many time out after the server has done the work, so goodput (successful responses that arrive in time) falls towards zero while CPU stays at 100%. Load shedding means rejecting excess work early and cheaply so the work you accept finishes in time.
In ASP.NET Core I use the rate limiting middleware (AddRateLimiter / UseRateLimiter) with a concurrency limiter sized by Little's law (concurrency = throughput × latency, measured at the healthy limit) and a small queue. Rejected requests get 503 with Retry-After, or 429 when a single client is over its quota. I shed by priority: checkout before batch exports, health probes never. Clients must honour Retry-After and back off with jitter.
The trade-off: you deliberately fail some users to keep the system serving most of them.
"The thing to understand about overload is that it's non-linear. While you're under capacity, queues stay short. Once arrivals exceed what you can process, the queue grows without limit. Every request waits longer, then times out at the client, and you keep doing work that nobody's waiting for. CPU is at 100% and goodput, the successful responses that arrived in time, drops towards zero. So the goal of load shedding is to refuse work early and cheaply, before you've spent anything on it, so the requests you do accept finish within their deadline.
In ASP.NET Core, the rate limiting middleware gives me the tools. A concurrency limiter caps in-flight requests. I size it with Little's law: if one instance does 400 requests a second at 250 ms, about 100 are in flight, so I set the permit limit near that with a small queue. Anything over it is rejected in microseconds with 503 and a
Retry-Afterheader. I use 429 instead when one client is over its own quota, through a partitioned limiter keyed by API key or tenant. For example, at [company] we [had a month-end batch client that saturated the API]. A partitioned token bucket for batch keys and a reserved share for interactive traffic [kept interactive p95 under 300 ms during the next month-end].The parts people forget are priority and clients. Not all traffic is equal: health probes must never be shed, or the orchestrator kills a busy but healthy instance, and checkout matters more than an export. And shedding only works if clients cooperate: they honour
Retry-After, back off with jitter and cap their retries. Otherwise your 503s just come straight back as a retry storm."
Arrivals 600 rps ──► [ queue grows: 0 → 5,000 → 20,000 ] ──► workers (capacity 400 rps)
│
wait time > client timeout (10 s)
▼
server finishes work → client already gone → goodput ≈ 0
| Tool | Where | What it limits | Rejection |
|---|---|---|---|
| Concurrency limiter | AddRateLimiter (global or per endpoint) |
In-flight requests | 503 (default RejectionStatusCode) |
| Token bucket / fixed / sliding window | Partitioned by client, key or tenant | Requests per time window | 429 with Retry-After from lease metadata |
| Kestrel limits | KestrelServerOptions.Limits |
Connections, body size, header size | Connection refused or 4xx |
Bounded Channel<T> |
In-process background queues | Queued work items | TryWrite false → reject or 503 |
| Gateway limits (APIM, Front Door WAF) | Before the service | Per subscription or IP | 429 |
| Status | Meaning | Client should |
|---|---|---|
| 429 Too Many Requests | You are over your quota | Slow down; wait for Retry-After |
| 503 Service Unavailable | The server is overloaded or down | Back off with jitter; try another region if available |
| Priority | Traffic | Policy |
|---|---|---|
| Never shed | Liveness and readiness probes | Excluded from limiters (DisableRateLimiting) |
| Highest | Checkout, payments, authenticated interactive | Larger permit share |
| Medium | Browse and search | Normal share |
| Lowest | Exports, batch partners, anonymous | Shed first; small token bucket |
A quoting API ran at about 400 rps per instance with a 250 ms p50. A partner's batch job sent 1,500 rps for 20 minutes each night. Before shedding, all traffic timed out and the incident lasted 40 minutes. With a concurrency limiter of 120 per instance (queue 20) and a partitioned token bucket giving batch keys 100 rps, the partner got 429s with Retry-After. Interactive p95 stayed at 280 ms and error rates for other clients stayed under 0.1%.
Checks whether the candidate understands overload as a non-linear failure and can protect a service with sized limits, correct status codes, priorities and client cooperation.
Green flags
Retry-AfterRed flags
Queueing theory says that as utilisation approaches 100%, the expected wait time grows without bound. For a simple single-server model, wait time is proportional to ρ / (1 − ρ), where ρ is utilisation. At 50% utilisation the multiplier is 1; at 90% it is 9; at 99% it is 99. Real systems are not that simple, but the shape holds: the last 10% of capacity costs most of your latency.
L = λ × W: average items in the system = arrival rate × average time in the system.
UseRateLimiter runs early in the pipeline. For each request it acquires a lease from a RateLimiter (from System.Threading.RateLimiting):
request ──► RateLimitingMiddleware
├─ GlobalLimiter (PartitionedRateLimiter<HttpContext>) ── acquire lease
├─ endpoint policy ([EnableRateLimiting("name")] / RequireRateLimiting)
├─ lease acquired? ── yes ──► next middleware ... (lease disposed at the end)
└─ no ──► OnRejected callback ──► RejectionStatusCode (503 default)
ConcurrencyLimiter holds the permit for the whole request, so it limits in-flight work.TokenBucketRateLimiter, FixedWindowRateLimiter and SlidingWindowRateLimiter limit rate. Their failed leases carry MetadataName.RetryAfter, which you copy into the Retry-After header.PartitionedRateLimiter.Create keys limiters by anything in the HttpContext: API key, user, tenant or IP.UseRateLimiter after routing when you use endpoint-specific policies.Shedding must be cheap. A rejection in the middleware costs microseconds and no database work. Shedding after authentication, model binding and a database read gives you little back. So the order is: gateway limits → Kestrel limits → rate limiter early in the pipeline → application work.
Client ──► 503 Retry-After: 5 ──► wait 5 s + jitter ──► retry (budget: max 10% extra calls)
│
budget spent? ──► fail to the user, do not retry
Microsoft.Extensions.Http.Resilience retries honour Retry-After by default (ShouldRetryAfterHeader on HttpRetryStrategyOptions). Clients without that behaviour turn your shedding into an amplifier.
Static limits go stale when the code or hardware changes. Adaptive concurrency limiters (in the style of TCP congestion control, which raises the limit while latency is fine and cuts it when latency rises) exist in service meshes and some libraries. They are worth it at large scale. For most .NET services, a load-tested static limit reviewed each quarter is enough.
k6 or bombardier up to twice its capacity, with no limiter. Plot goodput against offered load.AddConcurrencyLimiter sized by Little's law and repeat. Compare p95 and goodput.X-Api-Key header and check that the Retry-After header is set on 429s./healthz with DisableRateLimiting() and confirm probes still pass at full overload.dotnet-counters monitor Microsoft.AspNetCore.RateLimiting (metrics such as active and queued leases) during the test.A global concurrency limiter with a reserved pool for checkout, a partitioned quota per API key with Retry-After, escalation for clients that ignore it, and health checks exempt.
// Program.cs (.NET 10)
using System.Collections.Concurrent;
using System.Globalization;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks();
// Counts recent rejections per key so clients that ignore Retry-After get a longer wait.
var recentRejections = new ConcurrentDictionary<string, int>();
builder.Services.AddRateLimiter(options =>
{
// Global cap on in-flight work, sized by Little's law: 400 rps × 0.25 s ≈ 100, plus headroom = 120.
// Split into two pools so browse traffic can never use checkout's share (a bulkhead).
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(ctx =>
{
var isCheckout = ctx.Request.Path.StartsWithSegments("/checkout");
return isCheckout
? RateLimitPartition.GetConcurrencyLimiter("checkout", _ => new ConcurrencyLimiterOptions
{
PermitLimit = 40,
QueueLimit = 10, // revenue traffic may wait briefly (~25 ms)
QueueProcessingOrder = QueueProcessingOrder.OldestFirst
})
: RateLimitPartition.GetConcurrencyLimiter("general", _ => new ConcurrencyLimiterOptions
{
PermitLimit = 80,
QueueLimit = 0 // everything else: reject, never wait
});
});
// Per-client quota: batch partners are shed first, with a clear 429.
options.AddPolicy("per-api-key", ctx =>
RateLimitPartition.GetTokenBucketLimiter(
ctx.Request.Headers["X-Api-Key"].ToString() is { Length: > 0 } key ? key : "anonymous",
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 100,
TokensPerPeriod = 100,
ReplenishmentPeriod = TimeSpan.FromSeconds(1),
QueueLimit = 0
}));
options.RejectionStatusCode = StatusCodes.Status503ServiceUnavailable; // the default, stated explicitly
options.OnRejected = (context, _) =>
{
var http = context.HttpContext;
var key = http.Request.Headers["X-Api-Key"].ToString() is { Length: > 0 } k ? k : "anonymous";
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
// A quota limiter rejected this client: 429 and when to come back.
// Clients that keep hammering despite Retry-After get an escalating wait (capped at 60 s);
// persistent offenders are blocked at the gateway (APIM / Front Door WAF), not here.
var strikes = recentRejections.AddOrUpdate(key, 1, (_, n) => n + 1);
var seconds = Math.Min(60, Math.Ceiling(retryAfter.TotalSeconds) * Math.Max(1, strikes / 10));
http.Response.StatusCode = StatusCodes.Status429TooManyRequests;
http.Response.Headers.RetryAfter = seconds.ToString(CultureInfo.InvariantCulture);
}
else
{
// Concurrency limiter: the server is busy. Short Retry-After; clients add jitter.
http.Response.Headers.RetryAfter = "2";
}
return ValueTask.CompletedTask;
};
});
var app = builder.Build();
app.UseRateLimiter();
// Never shed health probes: shedding them gets busy but healthy instances killed.
app.MapHealthChecks("/healthz/live").DisableRateLimiting();
app.MapPost("/checkout", (Order order) => Results.Accepted());
app.MapGet("/quotes/{id:int}", (int id) => Results.Ok(new { id }))
.RequireRateLimiting("per-api-key");
// Reset strike counts every minute so well-behaved clients recover (a hosted service in real code).
_ = Task.Run(async () =>
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
while (await timer.WaitForNextTickAsync()) recentRejections.Clear();
});
app.Run();
public sealed record Order(Guid Id, decimal Total);
// Client side: honour Retry-After and keep retries small.
builder.Services.AddHttpClient("quotes")
.AddStandardResilienceHandler(o =>
{
o.Retry.MaxRetryAttempts = 2;
o.Retry.ShouldRetryAfterHeader = true; // the default: wait as long as the server asked
o.Retry.UseJitter = true;
});
QueueLimit, unbounded channels, a huge Kestrel backlog). Why it is wrong: Requests wait past their timeout, so the server does work nobody receives. Instead: Keep queues short enough to drain within the client's patience; reject the rest.UseRateLimiter early, and use gateway limits before the service.DisableRateLimiting() on probe endpoints.Retry-After.Retry-After, add jitter and cap retries with a budget.Load shedding is admitting that capacity is finite and choosing who fails, instead of letting everyone fail at random. The senior work is mostly decisions and numbers: which traffic is critical, what the limits are and where they came from (a load test, not a guess), and what each client is told. The priority order has reasons. Probes are never shed, because a failed probe makes the orchestrator remove or restart a healthy instance, which cuts capacity further. Revenue and interactive traffic come next, because a person is waiting and the business loses money. Batch and anonymous traffic can retry later at no real cost. Little's law gives the starting point, but only with throughput and latency measured at the healthy limit. Latency measured during overload includes queueing time and gives a limit that is far too high.
I also want the limiter visible. I watch the ASP.NET Core rate limiting metrics (aspnetcore.rate_limiting.active_request_leases, aspnetcore.rate_limiting.queued_requests, aspnetcore.rate_limiting.requests tagged by result), rejections per partition, goodput and p95. A rising rejection rate is an early capacity signal, long before latency alerts fire.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Concurrency limiter in the app | Protecting one instance's CPU, memory, connections | Needs load-tested sizing | Limiting per-customer fairness (use a partitioned rate limiter) |
| Partitioned token bucket per client | Quotas, fairness, noisy neighbours | Partition state per key; per instance unless shared | Global quotas across many instances without a shared store |
| Gateway limits (Azure API Management, Front Door WAF) | Per-subscription quotas, abuse protection, blocking clients that ignore Retry-After | Cost, a separate config surface | Fine-grained, app-aware priority |
| Autoscaling | Sustained growth | Minutes to react; costs money | Spikes shorter than scale-out time; shedding still needed |
Backpressure is a way for a slow consumer to make producers slow down, instead of letting work pile up until something breaks. The four strategies are block (producer waits), bounded buffer, drop (shed lower-value work) and reject (tell the caller to retry later). In .NET: bounded Channel<T> with WriteAsync (block), BoundedChannelFullMode.DropOldest (drop), TryWrite plus HTTP 429/503 with Retry-After (reject), pull-based IAsyncEnumerable<T>, and broker settings such as prefetch count and max concurrent calls so consumers only take what they can process. Every boundary needs a chosen strategy and metrics for queue depth and age.
Unbounded concurrency means starting as much concurrent work as the input demands, with no cap: Task.WhenAll over every item, Task.Run per request, unbounded queues, unlimited outgoing connections. Under load it exhausts something: memory, database connection pools (100 by default in SqlClient), sockets, downstream rate limits or CPU, and latency collapses for everyone. Little's law (concurrency = throughput × latency) shows that when a dependency slows down, in-flight work grows without bound. Put limits at each layer: SemaphoreSlim or Parallel.ForEachAsync for fan-out, bounded channels for queues, ASP.NET Core rate limiting (concurrency or token bucket) for inbound requests, MaxConnectionsPerServer for outbound HTTP, and bulkheads per dependency.
A bulkhead partitions shared resources so one failing dependency can only exhaust its own share, like the watertight compartments in a ship. In .NET the shared resources are thread-pool threads, sockets, database connection-pool slots, memory and request slots.
AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.AddRateLimiter concurrency policies per endpoint group.MaxConcurrentCalls.A bulkhead limits concurrent work. Rate limiting limits requests per time window. Size limits with Little's Law (concurrency = rate x latency) plus headroom, and pair them with timeouts. The trade-off is containment against rejecting work when a compartment is full.
How to tell it (STAR)
**S:** At [company], a partner's nightly batch job pushed our quoting API past capacity, and every client timed out for [about 40 minutes]. **T:** I was asked to make sure one client could never take down everyone else. **A:** I load tested to find our real limit, sized a concurrency limiter with Little's law, and added a token bucket per API key that returned 429 with Retry-After. I excluded health probes so busy instances would not be restarted, and agreed with the partner that they would honour Retry-After. **R:** The next batch run got throttled cleanly. Interactive p95 stayed at [about 280 ms], and the nightly incident stopped completely.
Last updated 23 Nov 2026.