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.
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.
"ASP.NET Core has had rate limiting middleware since .NET 7, built on
System.Threading.RateLimiting. I register policies withAddRateLimiter, addUseRateLimiterto the pipeline, and opt endpoints in withRequireRateLimiting. Two settings matter straight away:RejectionStatusCodedefaults to 503, which I change to 429, and theOnRejectedcallback is where I setRetry-Afterfrom 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
subclaim 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 getDisableRateLimiting. 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."
| 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 |
| 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 |
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.
Checks whether the candidate can configure the middleware correctly and knows its operational limits.
Green flags
Red flags
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.
GlobalLimiter (if any) for a lease.EnableRateLimitingAttribute / DisableRateLimitingAttribute metadata on the endpoint and resolves the named policy.HttpContext and returns a RateLimitPartition<TKey>: a key plus a factory for its limiter.PartitionedRateLimiter looks up (or creates) the limiter for that key and calls AcquireAsync.OnRejected runs with an OnRejectedContext holding the HttpContext and the failed Lease, after the status code is set.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.
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.
+-> 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.
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.
/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.RejectionStatusCode = 429 and see the default 503.dotnet-counters monitor --counters Microsoft.AspNetCore.RateLimiting -n <app> while load testing.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();
}
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.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.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.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.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.DisableRateLimiting() on health endpoints.aspnetcore.rate_limiting.requests by result and policy, and log the partition key in OnRejected.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 |
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.
CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.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.
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], 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.
Last updated 23 Nov 2026.