Rate Limiting in ASP.NET Core
The built-in middleware (since .NET 7) - Microsoft.AspNetCore.RateLimiting
Previously rate limiting required external libraries (AspNetCoreRateLimit) or your own implementation - since .NET 7 it is built into the framework.
using System.Threading.RateLimiting;
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.Window = TimeSpan.FromSeconds(10);
opt.PermitLimit = 5; // at most 5 requests per 10 seconds
opt.QueueLimit = 2; // additionally, 2 requests may wait in the queue
});
});
var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/api/data", () => "wynik").RequireRateLimiting("fixed");
Four built-in algorithms - which one when
1. Fixed Window - the simplest
The limit resets every N seconds at fixed intervals.
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.Window = TimeSpan.FromMinutes(1);
opt.PermitLimit = 100;
});
The drawback: a possible "burst" at the window boundary - 100 requests at the end of one minute + 100 at the start of the next = 200 in a short time.
2. Sliding Window
Like Fixed Window, but the window "slides" smoothly, divided into segments - it eliminates the burst-at-the-boundary problem.
options.AddSlidingWindowLimiter("sliding", opt =>
{
opt.Window = TimeSpan.FromMinutes(1);
opt.PermitLimit = 100;
opt.SegmentsPerWindow = 6; // splits the minute into 6 segments of 10s
});
3. Token Bucket
A "bucket of tokens", replenished at a steady rate; each request takes a token. It allows a controlled burst (if the bucket was full), but limits the average rate over the long term.
options.AddTokenBucketLimiter("token", opt =>
{
opt.TokenLimit = 50; // maks. rozmiar "wiadra"
opt.TokensPerPeriod = 10; // how many tokens it adds each period
opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10); // how often it replenishes
});
4. Concurrency Limiter
Limits concurrent requests (not over time, just "at a given moment"), useful for resource-expensive endpoints (e.g. generating a PDF report).
options.AddConcurrencyLimiter("concurrency", opt =>
{
opt.PermitLimit = 10; // at most 10 requests run CONCURRENTLY
opt.QueueLimit = 20;
});
Partitioning - a limit PER client, not global
This is a key, practical feature - without partitioning the limit is shared by all users at once (one bad client uses up the whole limit). Partitioning gives a separate counter per key (e.g. per IP, per user, per API key):
options.AddPolicy("per-user", context =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: context.User.Identity?.Name ?? context.Connection.RemoteIpAddress?.ToString() ?? "anonymous",
factory: _ => new FixedWindowRateLimiterOptions
{
Window = TimeSpan.FromMinutes(1),
PermitLimit = 20
}));
Each logged-in user (or, for anonymous ones, each IP address) gets their own, independent counter of 20 requests/minute - one over-active client doesn't eat up other clients' limit.
Reacting to exceeding the limit - status 429
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, token) =>
{
context.HttpContext.Response.Headers["Retry-After"] = "10";
await context.HttpContext.Response.WriteAsync("Too many requests, please try again later.", token);
};
The HTTP standard for rate limiting is the code 429 Too Many Requests, optionally with a Retry-After header telling the client after how many seconds to try again.
A full example in Web API - a controller + a global and a per-endpoint policy
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
// A GLOBAL policy - per IP address, applied by default to ALL endpoints
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
Window = TimeSpan.FromMinutes(1),
PermitLimit = 100
}));
// Polityka DODATKOWA, bardziej restrykcyjna - dla konkretnego, kosztownego endpointu
options.AddTokenBucketLimiter("expensive-operation", opt =>
{
opt.TokenLimit = 5;
opt.TokensPerPeriod = 1;
opt.ReplenishmentPeriod = TimeSpan.FromSeconds(30);
});
});
var app = builder.Build();
app.UseRateLimiter(); // MUST come after UseRouting(), before MapControllers/the endpoints
app.MapControllers();
app.Run();
[ApiController]
[Route("api/reports")]
public class ReportsController : ControllerBase
{
[HttpGet]
[EnableRateLimiting("expensive-operation")] // OVERRIDES the global policy ONLY for this action
public async Task<IActionResult> GenerateReport()
{
await Task.Delay(2000); // symulacja kosztownej operacji
return Ok(new { generated = true });
}
[HttpGet("summary")]
[DisableRateLimiting] // TURNS OFF rate limiting for this ONE action (e.g. a health check)
public IActionResult GetSummary() => Ok("lekki endpoint, bez limitu");
}
This example shows a typical, layered configuration: a global limiter (per IP, 100/min) protecting the whole API, plus a more restrictive policy (token bucket, 1 token/30s) applied to one expensive endpoint through [EnableRateLimiting], and [DisableRateLimiting] as a safety valve for endpoints that must always be available (e.g. /health).
Summary - which algorithm when
| Algorithm | When to use |
|---|---|
| Fixed Window | A simple limit, a small burst at the window boundary is acceptable |
| Sliding Window | You need a smoother distribution, with no bursts at the boundary |
| Token Bucket | You want to allow a momentary burst, but limit the average rate |
| Concurrency | Protecting resource-hungry endpoints from too many concurrent calls |
Summary
Rate limiting in ASP.NET Core (since .NET 7,
Microsoft.AspNetCore.RateLimiting) protects the API from excessive load through four algorithms (Fixed/Sliding Window, Token Bucket, Concurrency), configured globally or per endpoint ([EnableRateLimiting]/[DisableRateLimiting]). Partitioning (RateLimitPartition) gives an independent counter per client (IP, user, API key), and exceeding the limit by default returns429 Too Many Requests, optionally with aRetry-Afterheader.