Skip to content
FunCoding

rate-limiting

Built-in ASP.NET Core 10 rate limiting: fixed/sliding window, token bucket, concurrency, per-user and per-IP partitions, strict login limits, 429 with Retry-After, multi-instance behaviour. Use for "rate limiting", "throttling", "429", "Retry-After", "AddRateLimiter", "brute force on login". Do NOT use for outbound retries (use resilience).

Star
856
License
MIT
Last commit
Nov 29, 2026

skills/rate-limiting/SKILL.md

View on GitHub

Rate Limiting

Core Principles

  1. Use the built-in middleware. AddRateLimiter + UseRateLimiter ship in the shared framework (no package) and cover fixed window, sliding window, token bucket and concurrency limits. A hand-written counter in a filter misses partitions, queueing and metadata.
  2. Partition by who is calling. One shared bucket lets a single client lock everyone out. Partition by user ID when signed in and by client IP otherwise. The IP is only real after forwarded headers are configured (api-hardening); without that, every request shares the load balancer's IP.
  3. Auth endpoints get the strictest limit. Login, token, password reset and sign-up are where brute force and credential stuffing land. Give them a small, IP-partitioned policy separate from the general API limit.
  4. Reject with 429 and tell the client when to retry. Set RejectionStatusCode = 429 (the default is 503, which looks like an outage) and write Retry-After from the lease metadata so well-behaved clients back off.
  5. The limiter is per instance. Counters live in each process's memory, so three instances allow three times the limit. Plan for that, or enforce the hard limit at the gateway.

Patterns

Registration with a global limit, named policies and a 429 response

builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    options.OnRejected = async (context, ct) =>
    {
        if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
            context.HttpContext.Response.Headers.RetryAfter =
                ((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(NumberFormatInfo.InvariantInfo);

        await TypedResults.Problem(
                statusCode: StatusCodes.Status429TooManyRequests,
                title: "Too many requests.",
                extensions: new Dictionary<string, object?> { ["code"] = "rate-limited" })
            .ExecuteAsync(context.HttpContext);
    };

    // Every request: per user when signed in, per IP otherwise.
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(http =>
        RateLimitPartition.GetTokenBucketLimiter(RateLimitKeys.ForCaller(http), _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = 100,
            TokensPerPeriod = 50,
            ReplenishmentPeriod = TimeSpan.FromSeconds(10),
            QueueLimit = 0,
        }));

    // Login and token endpoints: per IP, small fixed window.
    options.AddPolicy(RateLimitPolicies.Auth, http =>
        RateLimitPartition.GetFixedWindowLimiter(RateLimitKeys.ForIp(http), _ => new FixedWindowRateLimiterOptions
        {
            PermitLimit = 5,
            Window = TimeSpan.FromMinutes(1),
            QueueLimit = 0,
        }));

    // Expensive reports: at most two running at once per user.
    options.AddPolicy(RateLimitPolicies.Reports, http =>
        RateLimitPartition.GetConcurrencyLimiter(RateLimitKeys.ForCaller(http), _ => new ConcurrencyLimiterOptions
        {
            PermitLimit = 2,
            QueueLimit = 0,
        }));
});
public static class RateLimitPolicies
{
    public const string Auth = "auth";
    public const string Reports = "reports";
}

public static class RateLimitKeys
{
    public static string ForCaller(HttpContext http) =>
        http.User.FindFirstValue(ClaimTypes.NameIdentifier) is { } userId ? $"user:{userId}" : ForIp(http);

    public static string ForIp(HttpContext http) =>
        $"ip:{http.Connection.RemoteIpAddress?.ToString() ?? "unknown"}";
}

Partition keys from user input (an IP, a header, an API key) let an attacker create unlimited partitions. Keep QueueLimit = 0 for API traffic, so a rejected request fails fast instead of holding a connection.

Applying policies to endpoints

internal sealed class LoginEndpoint : IEndpoint
{
    public void Map(IEndpointRouteBuilder endpoints) =>
        endpoints.MapPost("/login", (LoginRequest request, CancellationToken ct) => TypedResults.Ok())
            .RequireRateLimiting(RateLimitPolicies.Auth)
            .AllowAnonymous();
}

internal sealed class HealthEndpoint : IEndpoint
{
    public void Map(IEndpointRouteBuilder endpoints) =>
        endpoints.MapGet("/health/live", () => TypedResults.Ok())
            .DisableRateLimiting()          // probes must never be throttled
            .AllowAnonymous();
}

public sealed record LoginRequest(string Email, string Password);

A group (MapGroup(...).RequireRateLimiting(...)) applies one policy to a whole module. An endpoint policy runs in addition to the GlobalLimiter.

Pipeline order

app.UseForwardedHeaders();     // real client IP first
app.UseAuthentication();       // so partitions can read the user
app.UseAuthorization();
app.UseRateLimiter();          // endpoint policies need routing, which WebApplication adds implicitly

UseRateLimiter must come after routing when you use endpoint policies, and after authentication when partitions read HttpContext.User. Anonymous traffic still lands in the per-IP partition.

Which algorithm

LimiterBehaviourUse for
Fixed windowN requests per window, counter resets at the boundaryLogin attempts, simple quotas
Sliding windowWindow split into segments, smooths the boundary burstPublic APIs where a 2× burst at the boundary matters
Token bucketBucket refills at a steady rate, allows short burstsGeneral per-user API traffic
ConcurrencyN requests in flight at once, no time windowExpensive endpoints (exports, reports, AI calls)
builder.Services.AddRateLimiter(options => options.AddPolicy("public", http =>
    RateLimitPartition.GetSlidingWindowLimiter(RateLimitKeys.ForIp(http), _ => new SlidingWindowRateLimiterOptions
    {
        PermitLimit = 60,
        Window = TimeSpan.FromMinutes(1),
        SegmentsPerWindow = 6,
        QueueLimit = 0,
    })));

AddFixedWindowLimiter, AddSlidingWindowLimiter, AddTokenBucketLimiter and AddConcurrencyLimiter create one shared bucket for the policy. Use AddPolicy with RateLimitPartition when the limit is per caller, which is almost always.

Behind a load balancer with several instances

The middleware keeps counters in memory, per process. With three instances behind a round-robin load balancer:

  • A per-user limit of 100/minute lets a user make up to about 300/minute.
  • The 5-per-minute login limit becomes about 15 per IP.

Pick one of these deliberately:

  1. Divide the limit by the instance count when the count is fixed and approximate fairness is enough.
  2. Enforce the hard limit at the edge (Azure Front Door, API Management, nginx limit_req, YARP) and keep the in-app limiter as a per-instance safety net.
  3. Use a distributed limiter backed by Redis when the limit is a contract (paid API tiers). Write it as a PartitionedRateLimiter<HttpContext> so the middleware and policies stay the same.

Configure forwarded headers on every instance, or the per-IP partition sees only the load balancer.

Anti-patterns

One bucket for everyone

// BAD — one noisy client uses up the limit for every user
options.AddFixedWindowLimiter("api", limiter => { limiter.PermitLimit = 1000; limiter.Window = TimeSpan.FromMinutes(1); });

// GOOD — partition per caller
options.AddPolicy("api", http => RateLimitPartition.GetFixedWindowLimiter(RateLimitKeys.ForCaller(http),
    _ => new FixedWindowRateLimiterOptions { PermitLimit = 100, Window = TimeSpan.FromMinutes(1) }));

Default 503 with no Retry-After

// BAD — clients see "service unavailable" and retry immediately
builder.Services.AddRateLimiter(options => options.AddPolicy("api", http => RateLimitPartition.GetNoLimiter("none")));

// GOOD — 429 plus Retry-After from the lease (see the registration pattern)
builder.Services.AddRateLimiter(options => options.RejectionStatusCode = StatusCodes.Status429TooManyRequests);

Login on the same limit as the rest of the API

// BAD — 100 password guesses a minute per user is a brute-force allowance
endpoints.MapPost("/login", (LoginRequest request) => TypedResults.Ok()).RequireRateLimiting("api");

// GOOD — a dedicated, IP-partitioned policy
endpoints.MapPost("/login", (LoginRequest request) => TypedResults.Ok()).RequireRateLimiting(RateLimitPolicies.Auth);

Partitioning on the proxy's IP

// BAD — no forwarded headers: every client shares the load balancer's address and one bucket
app.UseRateLimiter();

// GOOD — real client IP first, then the limiter
app.UseForwardedHeaders();
app.UseRateLimiter();

Decision Guide

ScenarioRecommendation
General API trafficGlobalLimiter with a per-caller token bucket
Login, token, password reset, sign-upFixed window, per IP, 5–10 per minute, RequireRateLimiting("auth")
Expensive endpoint (export, report, LLM call)Concurrency limiter per user
Public anonymous APISliding window per IP
Health and readiness probes.DisableRateLimiting()
Rejected request429, Retry-After, ProblemDetails with code: rate-limited
Several instances, approximate limits are fineDivide limits by instance count
Several instances, the limit is a contractGateway limit, or a Redis-backed PartitionedRateLimiter
Behind a proxyForwarded headers before UseRateLimiter (api-hardening)
Retrying calls to other servicesUse the resilience skill

Similar Skills

rea-analysis-optimization

MOmorluto/rea485k9,215 new stars in the last 7 days

codebase-design

MAmattpocock/skills336k5,004 new stars in the last 7 days

Featured

diagnosing-bugs

Diagnose hard bugs and performance regressions by building a feedback loop with tests or scripts.

MAmattpocock/skills336k5,004 new stars in the last 7 days

setup-ts-deep-modules

MAmattpocock/skills336k5,004 new stars in the last 7 days

code-review

MAmattpocock/skills336k5,004 new stars in the last 7 days

implement

MAmattpocock/skills336k5,004 new stars in the last 7 days