Rate limiting
Rate limiting caps how many requests a client can make in a period. It protects logins from password guessing, APIs from abuse and your server from overload. This lesson uses the built-in rate limiting middleware with fixed window, sliding window, token bucket and concurrency limiters.
- Fixed window5 per minute; simple, good for logins
- Sliding windowSmoother limits without edge bursts
- Token bucketSteady rate with short bursts; good for APIs
- ConcurrencyAt most N running at once; heavy exports
The four limiters
- Fixed window: N requests per window, such as 5 per minute. Simple; bursts are possible at window edges.
- Sliding window: like fixed, but the window moves in segments, which smooths the edges.
- Token bucket: tokens refill at a steady rate and each request spends one; allows short bursts.
- Concurrency: limits how many requests run at the same time, such as 10 report exports.
Setting it up
Partition limits by something that identifies the caller: the signed-in user, an API key or, for anonymous users, the IP address.
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
o.AddPolicy("login", ctx => RateLimitPartition.GetFixedWindowLimiter(
partitionKey: ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) }));
o.AddPolicy("api", ctx => RateLimitPartition.GetTokenBucketLimiter(
partitionKey: ctx.User.Identity?.Name ?? ctx.Connection.RemoteIpAddress?.ToString() ?? "anon",
factory: _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 20, TokensPerPeriod = 10, ReplenishmentPeriod = TimeSpan.FromSeconds(1)
}));
o.AddConcurrencyLimiter("exports", c => { c.PermitLimit = 3; c.QueueLimit = 5; });
});
var app = builder.Build();
app.UseRouting();
app.UseRateLimiter();Applying policies
public class AccountController : Controller
{
[HttpPost, ValidateAntiForgeryToken, EnableRateLimiting("login")]
public Task<IActionResult> Login(LoginModel m) { /* ... */ return Task.FromResult<IActionResult>(View()); }
}
app.MapGroup("/api").RequireRateLimiting("api");
app.MapGet("/reports/export", ExportAsync).RequireRateLimiting("exports");Things to watch
- Behind a proxy or load balancer, configure ForwardedHeaders so RemoteIpAddress is the real client, not the proxy.
- Limits are per server in memory; with several instances each has its own counters.
- Return 429 with a Retry-After header so well-behaved clients slow down.
- For large-scale protection, add limits at the edge too (Cloudflare, Azure Front Door, API Management).
Interview question
Which rate limiter would you choose to protect a login endpoint, and how would you partition it?
A fixed or sliding window limiter, such as 5 attempts per minute, works well for logins because it directly caps guessing. Partition by client IP address (with forwarded headers configured correctly) and ideally also by the username being tried, so one attacker cannot guess many passwords for one account from many IPs, and one IP cannot try many accounts.
Want the full details? Read the official Microsoft documentation for this topic.