📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your API is overloaded: latency climbs, requests queue and eventually everything times out. How do you shed load at the edge of the service instead of falling over? Explain bounded queues and concurrency limits, the ASP.NET Core rate limiting middleware, 503 versus 429 with Retry-After, priority-based shedding, and how well-behaved clients should respond.

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.

Senior Theory Advanced aspnet-core backpressure distributed-systems load-shedding rate-limiting resilience

🎯 Key points

  • Overload collapse: queues grow, requests wait past their timeout, and goodput falls towards zero even at 100% CPU
  • Little's law: concurrency = throughput × latency, using throughput and latency measured at the healthy limit, not during overload
  • Bounded concurrency plus a small or zero queue: reject fast instead of waiting slowly
  • AddRateLimiter + UseRateLimiter; RejectionStatusCode defaults to 503; OnRejected sets Retry-After
  • 429 = this client is over its quota; 503 = the server is overloaded
  • Shed by priority: probes never (or healthy instances get killed), revenue and interactive traffic last, batch and anonymous first
  • Clients honour Retry-After, back off with jitter, and stop retrying when the budget is spent
  • Watch rejections per partition, in-flight and queued leases, goodput and p95 as early capacity signals

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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-After header. 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."


What overload does without shedding

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

The tools

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

503 or 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 shedding

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

Production example

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%.

🔍 What the interviewer is checking

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

  • Explains goodput collapse and why unbounded queues cause it
  • Sizes limits with Little's law from measured numbers
  • Distinguishes 503 from 429 and sets Retry-After
  • Exempts health probes and reserves capacity for critical flows

Red flags

  • "Just autoscale" as the whole answer
  • Larger queues to "avoid dropping requests"
  • No idea how clients should react to 503

📚 Learn in depth

1. Why queues explode

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.

2. Little's law for sizing

L = λ × W: average items in the system = arrival rate × average time in the system.

  • Measure throughput at the healthy limit with a load test (for example, 400 rps per instance).
  • Measure latency at that point (0.25 s).
  • In-flight requests ≈ 400 × 0.25 = 100. Set the concurrency limit near that, with headroom (say 120).
  • Queue length: only as long as can be drained within the client's patience. At 400 rps, a queue of 20 adds about 50 ms. A queue of 4,000 adds 10 s, which is useless.

3. How the ASP.NET Core middleware works

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.
  • Place UseRateLimiter after routing when you use endpoint-specific policies.

4. Cost of rejection

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.

5. Client side: making 503 useful

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.

6. Adaptive limits

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.

Try it yourself

  1. Load test a minimal API with k6 or bombardier up to twice its capacity, with no limiter. Plot goodput against offered load.
  2. Add AddConcurrencyLimiter sized by Little's law and repeat. Compare p95 and goodput.
  3. Add a partitioned token bucket keyed by an X-Api-Key header and check that the Retry-After header is set on 429s.
  4. Exclude /healthz with DisableRateLimiting() and confirm probes still pass at full overload.
  5. Watch dotnet-counters monitor Microsoft.AspNetCore.RateLimiting (metrics such as active and queued leases) during the test.

💻 Code

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;
    });

⚠ Common mistakes

  • Mistake: Unbounded queues (large 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.
  • Mistake: Shedding after expensive work (auth, database reads, model binding). Why it is wrong: Rejection costs nearly as much as serving, so it relieves nothing. Instead: Put UseRateLimiter early, and use gateway limits before the service.
  • Mistake: Rate-limiting health probes. Why it is wrong: The orchestrator sees failed probes and restarts busy but healthy instances, which removes capacity during overload. Instead: DisableRateLimiting() on probe endpoints.
  • Mistake: Returning 500 for shed requests. Why it is wrong: Clients and gateways treat it as a bug, and alerts fire for the wrong reason. Instead: 503 for server overload, 429 for client quota, both with Retry-After.
  • Mistake: Guessing limits. Why it is wrong: Too low wastes capacity; too high does not protect anything. Instead: Load test, then size with Little's law and review after major changes.
  • Mistake: One limiter for all traffic. Why it is wrong: A batch client can use every permit and starve checkout. Instead: Partition by client or priority and reserve capacity for critical flows.
  • Mistake: Clients that retry 503s immediately. Why it is wrong: Shedding turns into a retry storm. Instead: Honour Retry-After, add jitter and cap retries with a budget.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions backpressure across queues and brokers, not only HTTP Why: Checks the system-wide view of backpressure from in-process channels to message brokers
    How to answer

    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.

  2. When: Candidate mentions limiting fan-out or outbound concurrency Why: Checks how the candidate limits concurrency inside the service, not only at the edge
    How to answer

    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.

  3. When: Candidate mentions reserving capacity for checkout or partitioning limits Why: Checks how a bulkhead differs from rate limiting and how to size it
    How to answer

    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.

    • Outbound: a concurrency limiter per dependency. Use Polly's AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.
    • Inbound: ASP.NET Core AddRateLimiter concurrency policies per endpoint group.
    • Messaging: separate queues and consumers with their own 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.

🛠 Real-world problems: how you handle them

Partner batch job taking down interactive traffic every night
Situation
A B2B quoting API on [Azure App Service, 6 instances in Australia East] serving about 400 rps per instance. A partner's nightly batch job sent [1,500 rps for 20 minutes].
Signals
Nightly alerts on p95 above 10 s, HTTP 504s from the gateway, ThreadPool queue length and SQL DTU at 100%, and interactive users reporting time-outs at [02:00 AEST].
Investigation
Application Insights requests split by API key showed one key making up 70% of traffic. A load test in staging found the healthy limit at about 400 rps per instance with a 250 ms p50. dotnet-counters confirmed ThreadPool queue growth once that limit was passed.
Resolution
Immediate: an Azure API Management quota on the partner's subscription. Real fix: a global concurrency limiter (Little's law sizing), a partitioned token bucket per API key with 429 and Retry-After, and health probes excluded from limiting. The partner was told to honour Retry-After.
Prevention
A dashboard of rejections per partition, a quarterly load test to resize limits, an ADR describing priority classes, and a client integration guide that requires Retry-After support.

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.

↩ Usually asked after

More in Reliability Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me