Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson5 / 9

    Module 3 · API Resilience, Backpressure, and Observability · Lesson 5 of 9

    Rate Limiting, Backpressure, and Overload Protection

    Diagnose before reading

    Your report channel holds 200 items. Another 1,000 request handlers call WriteAsync while the worker is slow. Does capacity 200 bound all memory and concurrent requests? Mark buffered items, waiting producers and in-flight work as different quantities before reading the implementation.

    Write your answer first. Then use this trace to check the boundary you chose.

    QuantityControlled byStill needs its own policy
    Buffered work itemsBounded channel capacityItem size and durable acceptance
    Producers waiting to writeTheir admission and waiting budgetA buffer limit alone does not bound their count
    Concurrent database operationsConsumer concurrency / admission limiterA request-rate quota does not cap slow in-flight work
    Fleet-wide tenant quotaShared coordination or partitioned authorityPer-process limiter state does not aggregate replicas

    Rate limiting constrains admission over time or concurrent execution, depending on the limiter. Backpressure answers what producers should do when consumers cannot keep up.

    Choose the limiter that matches the constraint

    • Concurrency limiter: caps simultaneous in-flight operations. Use it when memory, database connections, or another scarce concurrent resource is the bottleneck.
    • Fixed window: simple request quota per interval. It can allow a burst at a window boundary.
    • Sliding window: smooths the boundary effect by dividing time into segments.
    • Token bucket: permits controlled bursts while enforcing an average refill rate.
    • Partitioned limiter: selects separate limiter instances by tenant, API key, user, route or workload class; it is a partitioning mechanism, not a separate rate algorithm. Use trustworthy normalized keys and control key cardinality so arbitrary caller input cannot create unbounded partitions.

    A queue is not free capacity. Every queued request consumes time and memory and may expire before execution. Keep queue limits small, propagate cancellation, and reject excess work explicitly.

    ASP.NET Core fixed-window policy

    The following minimal API demonstrates a fixed-window policy on a POST endpoint. It allows up to 50 admissions per ten-second window, queues up to ten additional requests and rejects further requests with HTTP 429. A window boundary can allow nearly twice the quota in a short interval. The endpoint is a stub: it does not validate, persist or queue an order, so its 202 response is not proof of durable acceptance.

    C#
    using System.Threading.RateLimiting;
    using Microsoft.AspNetCore.RateLimiting;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddRateLimiter(options =>
    {
        options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    
        options.AddFixedWindowLimiter("write-api", limiter =>
        {
            limiter.PermitLimit = 50;
            limiter.Window = TimeSpan.FromSeconds(10);
            limiter.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
            limiter.QueueLimit = 10;
            limiter.AutoReplenishment = true;
        });
    
        options.OnRejected = async (context, cancellationToken) =>
        {
            context.HttpContext.Response.Headers.RetryAfter = "10";
            await context.HttpContext.Response.WriteAsJsonAsync(
                new { error = "capacity_exhausted" },
                cancellationToken);
        };
    });
    
    var app = builder.Build();
    
    app.UseRateLimiter();
    
    app.MapPost("/orders", (CreateOrder command) =>
            Results.Accepted(value: new { command.OrderId }))
        .RequireRateLimiting("write-api");
    
    app.Run();
    
    public sealed record CreateOrder(Guid OrderId, decimal Amount);

    The numbers above are examples, not universal recommendations. Derive limits from load tests, downstream capacity, and service-level objectives. The built-in limiter state is local to this application instance: replicas do not share a fleet-wide quota. Combine per-tenant limits with shared-resource/global protection where needed. A request-rate policy does not cap concurrent work if admitted requests are slow.

    The hard-coded ten-second Retry-After is an illustrative delay hint, not a reservation or guarantee that a retry will succeed. A replenishing limiter may expose a more specific estimate via lease metadata. Clients still need bounded, jittered, replay-safe retries. Endpoint-specific policies require routing before rate limiting; this minimal hosting model adds routing automatically. If a partition key uses authenticated identity, authenticate before reading it in rate-limiting middleware.

    Backpressure with a bounded channel

    A bounded channel makes the overload decision explicit. FullMode = Wait makes WriteAsync wait when the buffer is full, and the request cancellation token can cancel a write waiting for capacity; it does not remove an item already accepted. Buffer capacity does not bound the number of waiting HTTP handlers/producers or items they retain. Add admission/concurrency limits and a bounded waiting budget, or use TryWrite for immediate rejection when appropriate.

    The following is a separate integration fragment: place the endpoint registration before app.Run() in the application setup, and provide the worker and status endpoint.

    C#
    using System.Threading.Channels;
    
    var queue = Channel.CreateBounded<WorkItem>(
        new BoundedChannelOptions(capacity: 200)
        {
            FullMode = BoundedChannelFullMode.Wait,
            SingleReader = true,
            SingleWriter = false
        });
    
    app.MapPost("/reports", async (
        WorkItem work,
        CancellationToken cancellationToken) =>
    {
        await queue.Writer.WriteAsync(work, cancellationToken);
        return Results.Accepted($"/reports/{work.Id}");
    });
    
    public sealed record WorkItem(Guid Id, string ReportType);

    In a real service, register the channel as a singleton and consume it from a BackgroundService; SingleReader = true promises only one reader, so the implementation must honor that assumption. This in-memory queue is not durable and is not shared across replicas. A crash can lose accepted work, and a lost HTTP response can cause duplicate submission. If 202 means durable acceptance, persist the job or use a durable broker before returning it, provide the advertised status endpoint and make submission/processing idempotent. Define shutdown behavior: stop accepting new work, complete the writer, drain within a budget, and persist or requeue anything that cannot finish safely.

    Operational signals

    Monitor these together:

    1. accepted and rejected requests by policy and partition;
    2. current concurrency and queue depth;
    3. queue wait duration, not only processing duration;
    4. end-to-end latency percentiles and timeout count;
    5. downstream saturation such as database pool usage;
    6. retry volume and duplicate-work detection;
    7. background consumer throughput and oldest-item age.

    A falling error rate is not enough if queue age is still growing.

    Failure modes and design decisions

    • An unbounded queue converts traffic spikes into memory pressure and stale work.
    • A large queue hides overload and pushes failures beyond the caller's timeout.
    • One shared pool without tenant fairness can let a noisy tenant consume it; tenant partitions alone do not protect total shared capacity.
    • Returning 429 without a stable retry contract can create synchronized retry storms.
    • Retrying non-idempotent writes can duplicate side effects.
    • Limiting only HTTP traffic misses scheduled jobs and message consumers that share the same database.

    Senior interview checkpoint

    Be ready to explain:

    • why concurrency and request-rate limits solve different problems;
    • how you would partition capacity across free and paid tenants;
    • when to reject immediately versus wait briefly;
    • how cancellation travels from HTTP to a bounded queue;
    • which measurements provide evidence that the selected limit protects the dependency under the tested load;
    • how idempotency keys make a retryable write safer.

    Hands-on exercise

    Design an order API with a 100-connection database pool and three workload classes: interactive reads, writes, and exports. Define separate admission policies, queue limits, cancellation behavior, and dashboard metrics. Explain how you would tune them from load-test evidence rather than guesswork.

    Check the boundary

    A bounded channel has FullMode.Wait and is full. A request is waiting in WriteAsync when its supplied token is cancelled. Which statement is correct?

    A Every item already accepted into the channel is removed.
    B The channel is now durable across process crashes.
    C The waiting write can be cancelled; an item already accepted is not automatically removed by cancelling that token.
    D No HTTP handlers can wait because channel capacity bounds all producers.
    Show answer

    Correct answer: C

    The cancellation token controls the pending write operation. Buffer capacity, waiting producer admission, durability and cancellation of accepted work are separate concerns.

    Hint: Trace whether the item crossed the acceptance boundary before cancellation.

    Two-minute interview practice

    Attempt both before comparing. State the assumption, the repair and one limit of your evidence.

    1. A one-second fixed window allows 50 requests. Can it admit close to 100 in a very short interval around the boundary? Explain the two windows.
    2. An in-memory enqueue returns 202, then the process dies. What promise can you honestly make?

    Hint. Revisit the ownership, time, transaction or measurement boundary in the trace table.

    Check your reasoning.

    1. Yes: up to 50 just before one window ends and another 50 just after the next begins, subject to actual arrival timing and available permits. This is not a concurrency bound.
    2. You cannot claim durable acceptance from memory alone. Persist the job or use a suitable durable broker before making that contract, expose the promised status resource and define duplicate submission and recovery behavior.

    Evidence for the repair

    Load tests should record buffered depth, waiting-producer count, processing concurrency and oldest-item age separately. A queue-depth graph capped at 200 does not prove the process is protected from overload.

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·