Every public endpoint will eventually be called far more often than you planned: a buggy client in a loop, a scraper, someone guessing passwords. ASP.NET Core ships rate limiting in the box, so you can cap that traffic without a gateway or a third-party package. This guide covers the four limiters, partitioning per client, and returning a useful 429. Examples target ASP.NET Core on .NET 10.
The four limiters
| Limiter | How it counts | Good for |
|---|---|---|
| Fixed window | N requests per window, counter resets at the edge | Simple per-minute caps, sign-in attempts |
| Sliding window | Window split into segments, smoother at the edges | Public APIs where bursts at the boundary matter |
| Token bucket | Tokens refill at a rate, each request spends one | Allowing short bursts with a steady average |
| Concurrency | At most N requests in flight at once | Expensive endpoints, report exports |
The fixed window's weakness is the boundary: a client can send N requests at 0:59 and N more at 1:00. The sliding window and token bucket smooth that out.
Register policies
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddFixedWindowLimiter("login", o =>
{
o.PermitLimit = 5;
o.Window = TimeSpan.FromMinutes(1);
o.QueueLimit = 0;
});
options.AddTokenBucketLimiter("api", o =>
{
o.TokenLimit = 40; // burst size
o.TokensPerPeriod = 20; // steady rate
o.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
o.QueueLimit = 0;
});
options.AddConcurrencyLimiter("exports", o =>
{
o.PermitLimit = 2;
o.QueueLimit = 4;
o.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
});
});
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseRateLimiter();Then attach a policy to an endpoint:
app.MapPost("/auth/login", Login).RequireRateLimiting("login");
app.MapGet("/api/orders", GetOrders).RequireRateLimiting("api");In MVC, use the attribute: [EnableRateLimiting("login")] on an action or controller, and [DisableRateLimiting] to opt one out.
Partition per client
The helpers above create one shared limiter: five sign-ins per minute for the whole site, not per person. Almost always you want a limit per client. Use AddPolicy with a partition key:
options.AddPolicy("login", http => RateLimitPartition.GetFixedWindowLimiter(
partitionKey: http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
}));Choose the key to match the threat:
- IP address for anonymous endpoints: sign-in, sign-up, newsletter, comments.
- User id for signed-in API use:
http.User.FindFirstValue("sub"), so one heavy user can't starve the rest. - API key for machine clients.
Behind a reverse proxy, RemoteIpAddress is the proxy's address, so every visitor shares one partition. Configure the forwarded headers middleware with your proxy's address before relying on IP limits.
builder.Services.Configure<ForwardedHeadersOptions>(o =>
{
o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
o.KnownProxies.Add(IPAddress.Parse("10.0.0.5"));
});
app.UseForwardedHeaders();Return a useful 429
A bare 429 leaves the client guessing. Tell it what happened and when to retry:
options.OnRejected = async (context, ct) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter =
((int)retryAfter.TotalSeconds).ToString(CultureInfo.InvariantCulture);
}
await context.HttpContext.Response.WriteAsJsonAsync(
new { success = false, message = "Too many attempts. Try again in a few minutes." }, ct);
};Different endpoints can carry different wording: read the policy name from the endpoint metadata (EnableRateLimitingAttribute.PolicyName) and pick the message from it.
A global safety net
A global limiter applies to every request before named policies run. Use it as a generous ceiling per IP, not as your main control:
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(http =>
RateLimitPartition.GetTokenBucketLimiter(
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 200,
TokensPerPeriod = 100,
ReplenishmentPeriod = TimeSpan.FromSeconds(10),
}));Limits to know about
- Limiter state lives in memory, per instance. With three servers behind a load balancer, a client effectively gets three times the limit. For strict global limits you need shared state (Redis) or a gateway.
- Static files served before
UseRateLimiteraren't limited, which is usually what you want. - Put limits in configuration so you can tune them without a deploy.
Wrapping up
Pick the limiter by the shape of traffic you expect, partition by the identity that matches the threat, and return a 429 that tells the client when to come back. Five sign-in attempts per IP per minute alone closes off most password guessing.