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

📚 Interview question

Show how you would configure ASP.NET Core's rate limiting middleware for a .NET 10 API: AddRateLimiter, a policy partitioned by API key or user, different limits per endpoint, a 429 response with Retry-After, and what changes when the API runs on several instances.

Configuring Microsoft.AspNetCore.RateLimiting in .NET 10: AddRateLimiter, partitioned limiters by API key or user, per-endpoint policies, OnRejected with 429 and Retry-After, middleware order, and the per-instance limitation.

Mid-Level Coding Intermediate api-keys aspnet-core minimal-apis partitioning rate-limiting web-api

🎯 Key points

  • AddRateLimiter + UseRateLimiter; RequireRateLimiting or [EnableRateLimiting] per endpoint (middleware since .NET 7, unchanged shape in .NET 10)
  • RejectionStatusCode still defaults to 503 in .NET 10: set it to 429
  • OnRejected reads MetadataName.RetryAfter from the lease and sets Retry-After
  • RateLimitPartition.Get*Limiter keyed by a validated API key, user or tenant, never a raw header
  • UseRateLimiter after UseRouting (endpoint policies) and after authentication (user partitions)
  • GlobalLimiter for a blanket cap; DisableRateLimiting for health checks
  • State is in memory per instance: N instances allow N x limit; Redis or API Management for shared limits
  • Monitor the Microsoft.AspNetCore.RateLimiting meter and log the partition key on rejection

⏱ 30-second answer

Register limiters with builder.Services.AddRateLimiter, add app.UseRateLimiter() after routing and authentication, then attach named policies to endpoints with RequireRateLimiting("name") or [EnableRateLimiting]. For fairness use RateLimitPartition.GetTokenBucketLimiter (or fixed/sliding window) keyed by the API key, user id or tenant so one client can't exhaust another's quota. Set RejectionStatusCode = 429 (the default is 503) and use OnRejected to copy the lease's RetryAfter metadata into the Retry-After header with a ProblemDetails body. The catch: the middleware keeps state in memory per process, so with several instances the effective limit multiplies; contractual limits belong in a shared store or the gateway.

🗣 Full answer (senior)

How I would answer this in an interview

"ASP.NET Core has had rate limiting middleware since .NET 7, built on System.Threading.RateLimiting. I register policies with AddRateLimiter, add UseRateLimiter to the pipeline, and opt endpoints in with RequireRateLimiting. Two settings matter straight away: RejectionStatusCode defaults to 503, which I change to 429, and the OnRejected callback is where I set Retry-After from the lease metadata and write a ProblemDetails body.

For a real API I almost never use a single shared limiter, because then one noisy client blocks everyone. I write a partitioned policy: the partition key is the API key for partners, the user's sub claim for signed-in users, and the remote IP only as a last resort for anonymous traffic. Each partition gets its own token bucket, and I can give different tiers different sizes. Expensive endpoints, such as exports, get an extra concurrency policy. Health checks and the OpenAPI document get DisableRateLimiting. Order matters: the middleware must run after routing so it can see endpoint metadata, and after authentication if I partition by user.

The mistake I see is forgetting that the counters live in each process. With six instances behind a load balancer, a limit of 100 a minute becomes roughly 600, and it changes every time we autoscale. That is fine for protection, but not for a limit in a partner contract. For those I enforce at Azure API Management with rate-limit-by-key, or use a Redis-backed limiter. The in-process limiter protects the instance; the gateway enforces the contract."


The building blocks

API Purpose
AddRateLimiter(o => ...) Registers options and named policies
o.AddFixedWindowLimiter / AddSlidingWindowLimiter / AddTokenBucketLimiter / AddConcurrencyLimiter Simple, unpartitioned named policies (one limiter shared by all callers)
o.AddPolicy(name, ctx => RateLimitPartition.Get...) Partitioned policy: one limiter per key
o.GlobalLimiter A PartitionedRateLimiter<HttpContext> applied to every request before endpoint policies
o.RejectionStatusCode, o.OnRejected What the client receives
RequireRateLimiting, [EnableRateLimiting], [DisableRateLimiting], DisableRateLimiting() Endpoint selection

Choosing the partition key

Key Good for Pitfall
API key / client id Partner and B2B APIs Validate the key first, or attackers create unlimited partitions with random keys
User id (sub) Signed-in apps Needs authentication to run first
Tenant id Multi-tenant SaaS fairness One large tenant may need a custom tier
Remote IP Anonymous endpoints (login, sign-up) NAT and proxies; requires UseForwardedHeaders with known proxies

Production example

On a [partner orders API], one integrator's retry bug sent about 3,000 requests a minute and pushed p95 latency for everyone from 180 ms to 2.4 s. A token bucket per API key (bucket 60, 10 a second) plus a concurrency limit of 4 on the export endpoint kept other partners' p95 under 250 ms during the next incident, and the integrator got clear 429s with Retry-After instead of timeouts.

🔍 What the interviewer is checking

Checks whether the candidate can configure the middleware correctly and knows its operational limits.

Green flags

  • Sets 429 explicitly and writes Retry-After from lease metadata
  • Uses partitioned policies keyed on validated identity
  • Knows middleware order relative to routing and authentication
  • Raises the per-instance limitation and where contract limits should live
  • Excludes health checks

Red flags

  • Single global limiter for all clients
  • Partitions on unvalidated headers or the proxy's IP
  • Believes the limit is global across instances

📚 Learn in depth

1. Where the middleware sits

UseForwardedHeaders -> UseRouting -> UseAuthentication -> UseAuthorization -> UseRateLimiter -> endpoint
      (real client IP)   (endpoint chosen)   (User populated)                    (reads metadata, acquires lease)

WebApplication adds routing implicitly at the start of the pipeline, but if you call UseRouting explicitly, UseRateLimiter must come after it for endpoint-specific policies to work. Putting it after authorisation also means unauthenticated requests are rejected with 401 before they spend a permit.

2. What happens per request

  1. The middleware asks the GlobalLimiter (if any) for a lease.
  2. It reads EnableRateLimitingAttribute / DisableRateLimitingAttribute metadata on the endpoint and resolves the named policy.
  3. The policy's partition function runs with the HttpContext and returns a RateLimitPartition<TKey>: a key plus a factory for its limiter.
  4. The PartitionedRateLimiter looks up (or creates) the limiter for that key and calls AcquireAsync.
  5. If the lease is acquired, the request continues and the lease is disposed when the response completes (this matters for concurrency limiters).
  6. If not, OnRejected runs with an OnRejectedContext holding the HttpContext and the failed Lease, after the status code is set.

3. Memory and idle partitions

Each distinct key creates a limiter. The partitioned limiter periodically removes idle limiters, but high-cardinality keys (an IP on a public endpoint under a botnet, or unvalidated API keys) still create many objects. Validate keys and keep anonymous partitions coarse.

4. Queueing

QueueLimit > 0 means requests wait for permits: throttling. QueueProcessingOrder.NewestFirst favours fresh requests over ones that have waited long enough for the client to give up. Queued requests still hold a Kestrel connection, so keep queues short.

5. Multiple instances

          +-> instance A (100/min) 
LB -------+-> instance B (100/min)   effective limit ~300/min
          +-> instance C (100/min)

Options: divide by instance count; enforce at API Management (rate-limit-by-key is per gateway region and approximate, quota-by-key for longer periods); or implement a custom RateLimiter backed by Redis with a Lua script for atomic token-bucket updates. The third adds about a millisecond per request and a dependency; decide whether to fail open (allow traffic if Redis is down) or closed.

6. Observability

ASP.NET Core emits metrics on the Microsoft.AspNetCore.RateLimiting meter, including aspnetcore.rate_limiting.requests with a result tag (acquired, endpoint_limiter, global_limiter, request_canceled) and lease and queue durations. Watch rejected requests per policy in Application Insights or Prometheus, and log the partition key on rejection so you can tell partners exactly what happened.

Try it yourself

  1. Build the code example, run it, and hammer /orders with for i in $(seq 1 30); do curl -s -o /dev/null -w "%{http_code}\n" -H "X-Api-Key: a" localhost:5000/orders; done.
  2. Repeat with a second key and confirm partitions are independent.
  3. Remove RejectionStatusCode = 429 and see the default 503.
  4. Run dotnet-counters monitor --counters Microsoft.AspNetCore.RateLimiting -n <app> while load testing.
  5. Start two instances on different ports behind YARP and measure the effective limit.

💻 Code

A partitioned token bucket per API key, a stricter export policy, and a proper 429:

using System.Globalization;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();

builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; // default is 503

    // Per-client token bucket: burst 60, then 10 per second.
    options.AddPolicy("per-client", httpContext =>
    {
        // Validated client id (set by your API key auth handler), never the raw header.
        string key = httpContext.User.FindFirst("client_id")?.Value
            ?? httpContext.Connection.RemoteIpAddress?.ToString()
            ?? "anonymous";

        return RateLimitPartition.GetTokenBucketLimiter(key, _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = 60,
            TokensPerPeriod = 10,
            ReplenishmentPeriod = TimeSpan.FromSeconds(1),
            QueueLimit = 0,
            AutoReplenishment = true
        });
    });

    // Expensive endpoint: at most 2 concurrent exports per client.
    options.AddPolicy("exports", httpContext =>
        RateLimitPartition.GetConcurrencyLimiter(
            httpContext.User.FindFirst("client_id")?.Value ?? "anonymous",
            _ => new ConcurrencyLimiterOptions { PermitLimit = 2, QueueLimit = 0 }));

    options.OnRejected = async (context, cancellationToken) =>
    {
        if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
        {
            context.HttpContext.Response.Headers.RetryAfter =
                ((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
        }

        var problems = context.HttpContext.RequestServices.GetRequiredService<IProblemDetailsService>();
        await problems.WriteAsync(new ProblemDetailsContext
        {
            HttpContext = context.HttpContext,
            ProblemDetails = { Title = "Too many requests", Status = 429,
                Detail = "Rate limit exceeded for this client. See Retry-After." }
        });
    };
});

builder.Services.AddAuthentication(/* your API key or JWT scheme */);
builder.Services.AddAuthorization();
builder.Services.AddHealthChecks();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter(); // after auth, so partitions can use the client id

var api = app.MapGroup("/").RequireRateLimiting("per-client");
api.MapGet("/orders", () => Results.Ok(Array.Empty<object>()));
api.MapPost("/exports", async (CancellationToken ct) =>
{
    await Task.Delay(TimeSpan.FromSeconds(5), ct); // stands in for a slow report
    return Results.Accepted();
}).RequireRateLimiting("exports"); // both policies apply: group + endpoint

app.MapHealthChecks("/health").DisableRateLimiting();

app.Run();

The controller equivalent:

[ApiController]
[Route("api/[controller]")]
[EnableRateLimiting("per-client")]
public sealed class ReportsController : ControllerBase
{
    [HttpGet("status")]
    [DisableRateLimiting]
    public IActionResult Status() => Ok();
}

⚠ Common mistakes

  • Mistake: Leaving RejectionStatusCode at its default. Why it is wrong: the default is StatusCodes.Status503ServiceUnavailable (it is still initialised that way in RateLimiterOptions in .NET 10, whatever some blog posts claim), which tells clients and monitors the server is down. Instead: set it to 429.
  • Mistake: Partitioning on the raw X-Api-Key header before validating it. Why it is wrong: an attacker sends random keys and gets a fresh bucket each time, plus unbounded memory. Instead: authenticate the key first (an authentication handler that looks it up and issues a client_id claim) and partition on that claim.
  • Mistake: Calling UseRateLimiter before UseAuthentication. Why it is wrong: HttpContext.User is empty, so every user falls into one partition. Instead: run it after authentication and authorisation.
  • Mistake: Partitioning by RemoteIpAddress behind Azure Front Door or a load balancer without forwarded headers. Why it is wrong: every request has the proxy's IP, so all users share one bucket. Instead: configure UseForwardedHeaders with known proxies or partition by identity.
  • Mistake: Using AddFixedWindowLimiter("name", ...) and assuming it is per user. Why it is wrong: those helpers create one limiter shared by every caller. Instead: use AddPolicy with RateLimitPartition.
  • Mistake: Treating the in-memory limit as a contractual limit. Why it is wrong: it multiplies with instance count and resets on deploy. Instead: enforce contract limits at the gateway or in shared state such as Redis.
  • Mistake: Rate limiting health probes. Why it is wrong: a busy instance fails its probe and gets restarted, making overload worse. Instead: DisableRateLimiting() on health endpoints.
  • Mistake: Shipping limits with no telemetry. Why it is wrong: you can't tell a limit that is too tight from an abusive client. Instead: chart aspnetcore.rate_limiting.requests by result and policy, and log the partition key in OnRejected.

🏛 Senior insight: trade-offs

The built-in middleware is excellent instance protection and a poor billing system. I use it to keep each instance healthy and to give partners fair shares, and I put commercial quotas (per month, per subscription tier) in Azure API Management or a dedicated store where they survive deploys and scale-outs. I also decide up front what happens when the limiter's own dependency fails: a Redis-backed limiter that fails closed can turn a cache outage into a full API outage.

Measure before tuning: chart requests per key (p50, p99, max per second) from Application Insights for a fortnight, set limits a comfortable margin above the p99 legitimate client, and alert on rejections per policy so a new limit doesn't silently break a partner.

Option When it fits Cost When not to
In-process middleware Instance protection, fairness, single-instance apps Free, sub-microsecond Contractual or billed limits across instances
API Management rate-limit-by-key / quota-by-key Partner APIs, subscription tiers APIM cost, approximate across regions Business-aware limits needing app data
Redis-backed custom limiter Exact global limits in app code ~1 ms per request, a new dependency When approximate is good enough

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the limiter is in-memory per instance Why: Checks distributed-state trade-offs and gateway-level enforcement
    How to answer

    The built-in middleware keeps counters in each process, so 10 instances allow roughly 10x the limit. Options: divide the limit by the instance count (cheap, approximate, and wrong as soon as autoscaling changes the count); enforce at a shared edge such as Azure API Management rate-limit-by-key / quota-by-key; or use a Redis-backed limiter (sliding window or token bucket in an atomic Lua script) for exact limits, at the cost of a network hop per request. Decide up front what happens when Redis is unreachable: fail open with a per-instance local limiter as a fallback, or fail closed for abuse-sensitive endpoints such as login.

  2. When: Candidate partitions by client IP Why: Checks understanding of reverse proxies and forwarded headers when identifying the real client
    How to answer
    • A forward proxy sits in front of clients (corporate egress proxy): clients send requests through it to the internet. For HTTPS it tunnels with CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.
    • A reverse proxy sits in front of servers (nginx, Envoy, YARP, App Gateway, ingress): it terminates TLS, routes, load balances, caches and adds headers.

    Behind a reverse proxy, the app sees the proxy's IP and often plain http. The proxy passes the originals in X-Forwarded-For and X-Forwarded-Proto, but ASP.NET Core only applies them via the ForwardedHeaders middleware, and by default only trusts proxies on loopback. So UseHttpsRedirection sees http, redirects to https, the proxy forwards as http again: a loop.

    Fix: UseForwardedHeaders first, configured with the proxy's IPs or network in KnownProxies/known networks. Do not trust all sources, or clients can spoof their IP and scheme.

  3. When: Candidate adds a concurrency policy for an expensive endpoint Why: Checks the link between concurrency limits and the bulkhead pattern
    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

One partner's retry loop slows the API for every partner
Situation
A [partner orders API] on [6] App Service instances in Azure Australia East serves [40] integrators. One integrator deploys a client with a retry loop and no backoff.
Signals
Application Insights shows requests jumping from [500] to [3,000] per minute, p95 latency from [180 ms] to [2.4 s], SQL DTU at 100%, and other partners raising tickets about timeouts.
Investigation
Grouped Application Insights requests by the client_id custom dimension and found one client making 80% of calls, mostly identical POSTs seconds apart. Checked dependency telemetry to confirm the database was saturated by those calls, and checked the API Management analytics for the same client.
Resolution
Immediately blocked the client's subscription in API Management and contacted them. Then added a partitioned token bucket per validated client_id, a concurrency limit on the export endpoint, 429 with Retry-After and ProblemDetails, and a contractual quota in API Management.
Prevention
Load test with one abusive client in the k6 suite, alert on 429 rate and top-N clients per minute, publish limits and retry guidance in the developer portal, and add an ADR on where each kind of limit is enforced.

How to tell it (STAR)

**S:** At [company], one of our [40] partners shipped a client that retried every failed call instantly, and within minutes the whole partner API slowed to a [2.4 s] p95. **T:** I had to protect the other partners quickly and stop it happening again. **A:** I traced the traffic to one client_id in Application Insights, had the subscription suspended in API Management, then added per-client token buckets and a concurrency cap on exports using the ASP.NET Core rate limiter, with proper 429s and Retry-After. I also moved the contractual quota into API Management because the in-process limiter is per instance. **R:** In the next incident of that kind, other partners' p95 stayed under [250 ms], and the integrator fixed their backoff within [a day] because the 429s told them exactly what was wrong.

↩ Usually asked after

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me