Rate Limiting in ASP.NET Core: Protect Your API Without a Gateway

Fixed window, sliding window, token bucket and concurrency limiters with the built-in middleware, partitioned per client, with friendly 429s.

R M Shahidul Islam Shahed · 3 min read

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

csharp
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:

csharp
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:

csharp
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.

csharp
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:

csharp
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:

csharp
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 UseRateLimiter aren'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.

Keep reading

All articles →
ASP.NET Core & Web APIs

Output Caching in ASP.NET Core: Tags, Eviction and the Traps

Cache whole pages on the server, clear them the moment content changes, and avoid the antiforgery and nonce traps that break cached HTML.

4 min read
ASP.NET Core & Web APIs

Minimal APIs vs Controllers in 2026: Which Should You Pick?

A practical comparison for real projects: organisation, filters, validation, OpenAPI and testing.

1 min read
Security

Security Headers and CSP in ASP.NET Core Without Breaking Your Site

Add CSP, HSTS and the other security headers with one small middleware, keep inline scripts working by hash, and roll it out without breaking pages.

4 min read