skip to content

In ASP.NET Core, how do RateLimiterOptions.GlobalLimiter and an endpoint's named rate limiting policy combine on one request, and what does [DisableRateLimiting] switch off?

level: middleimportance: should knowfreq 35%

answer

  1. global first, then endpoint
  2. both must grant a permit
  3. PartitionedRateLimiter.Create for GlobalLimiter
  4. CreateChained for several global limits
  5. DisableRateLimiting skips global too

basics

~10 s

GlobalLimiter runs on every request first, then the endpoint's policy; the request proceeds only if both grant a permit. [DisableRateLimiting] or DisableRateLimiting() removes all limits from that endpoint, including the global limiter.

solid answer

~40 s

`RateLimiterOptions.GlobalLimiter` is a `PartitionedRateLimiter<HttpContext>`, usually built with `PartitionedRateLimiter.Create`, and it applies to every request through the middleware whether or not the endpoint names a policy. When an endpoint also has `RequireRateLimiting("free")` or `[EnableRateLimiting("free")]`, the middleware acquires from the global limiter first and then from the policy; if either refuses, the request is rejected and any global lease already taken is released. Several global limits (per IP per second plus per IP per day) chain with `PartitionedRateLimiter.CreateChained`. `[DisableRateLimiting]` is checked before anything else and skips both the global limiter and any policy. When several `[EnableRateLimiting]` sources apply, the last one in the endpoint's metadata wins: an action's attribute beats its controller's, and a `RequireRateLimiting` convention on `MapControllers` beats both.

code

csharp · 19 lines
csharp
builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;

    var perIpBurst = PartitionedRateLimiter.Create<HttpContext, string>(ctx =>
        RateLimitPartition.GetFixedWindowLimiter(ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
            _ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromSeconds(1) }));
    var perIpDaily = PartitionedRateLimiter.Create<HttpContext, string>(ctx =>
        RateLimitPartition.GetFixedWindowLimiter(ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
            _ => new FixedWindowRateLimiterOptions { PermitLimit = 5000, Window = TimeSpan.FromDays(1) }));
    options.GlobalLimiter = PartitionedRateLimiter.CreateChained(perIpBurst, perIpDaily);

    options.AddFixedWindowLimiter("forecast", o => { o.PermitLimit = 60; o.Window = TimeSpan.FromMinutes(1); });
});

var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/forecast/{city}", (string city) => Results.Ok(city)).RequireRateLimiting("forecast");
app.MapGet("/healthz", () => Results.Ok()).DisableRateLimiting();

go deeper

for a junior

Know that a global limiter covers every request and named policies cover the endpoints that ask for them, and that DisableRateLimiting exempts an endpoint.

for a middle

Walk through the middleware's order: DisableRateLimiting check, global acquire, endpoint acquire, both required; explain how CreateChained adds several global limits.

for a senior

Spot the metadata precedence traps: action over controller, Program.cs conventions over attributes, and DisableRateLimiting silently removing the global safety net.

for a principal

Design the layering so new endpoints are protected by default, product rules stay per endpoint, and exemptions are deliberate and reviewed.

## Two layers of limiting The rate limiting middleware has two independent sources of limits: - **The global limiter** — `RateLimiterOptions.GlobalLimiter`, a single `PartitionedRateLimiter<HttpContext>` that sees **every** request passing through `UseRateLimiter`, including requests to endpoints with no policy. - **The endpoint limiter** — built from the named policies you register (`AddFixedWindowLimiter`, `AddPolicy`, ...) and applied only to endpoints whose metadata carries an `EnableRateLimitingAttribute`. The global limiter cannot be one of the simple named helpers; you build it yourself: ```csharp options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext => RateLimitPartition.GetFixedWindowLimiter( httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new FixedWindowRateLimiterOptions { PermitLimit = 300, Window = TimeSpan.FromMinutes(1) })); ``` ## The order on one request 1. **`DisableRateLimitingAttribute` present?** Call the next middleware. No global, no endpoint limiting. 2. **No `EnableRateLimitingAttribute` and no global limiter?** Call the next middleware. 3. **Global limiter** (if configured): try to acquire. On refusal, reject with reason "global". 4. **Endpoint limiter**: resolve the policy named by the metadata (or the `GetNoLimiter` partition when there is none) and acquire. On refusal, dispose the global lease and reject with reason "endpoint". 5. Both granted: run the endpoint, holding a combined lease that releases both when the request ends. So a request needs **both** a global and an endpoint permit, and a free-tier caller can be stopped by either: the site-wide 300-per-minute-per-IP ceiling, or the stricter 60-per-minute `/forecast` policy. ## Several global limits `PartitionedRateLimiter.CreateChained(first, second)` wraps several partitioned limiters into one, acquiring from each in the order given. That is how one global limiter enforces both a burst limit and a daily cap per IP. Leases from a chain merge their metadata, keeping the first value when two limiters report the same name. ## Which policy an endpoint gets The middleware asks the endpoint's metadata for the **most significant** `EnableRateLimitingAttribute`, which is the last one added. In practice: | Sources on one MVC action | Policy used | |---|---| | `[EnableRateLimiting("a")]` on the controller only | `a` | | `"a"` on the controller, `[EnableRateLimiting("b")]` on the action | `b` | | attributes on the action, plus `app.MapControllers().RequireRateLimiting("c")` | `c`, because conventions added in `Program.cs` come after attribute metadata | | any of the above plus `[DisableRateLimiting]` anywhere on the endpoint | no limiting at all | The third row trips people up: a convention applied to every controller route overrides action-level attributes. If actions need their own policies, attach the default with an attribute on the controllers instead of on `MapControllers`. ## Practical guidance - Use the **global limiter** as a coarse safety net per IP or per user that every route inherits, including ones nobody remembered to annotate. - Use **named policies** for the product rules of specific endpoints. - Use **`DisableRateLimiting`** sparingly, for example on a health endpoint polled by the orchestrator; it disables the global safety net for that endpoint as well. - A global rejection runs `RateLimiterOptions.OnRejected`, never a policy's own callback, so put shared rejection formatting at the options level. ## Mistakes seen in code review - **A constant key in the global partitioner** (`GetFixedWindowLimiter("all", ...)`) turns the safety net into one site-wide counter that a single noisy client can exhaust for everyone. - **`[DisableRateLimiting]` on a base controller**: the attribute is declared with `Inherited = true`, so every derived controller silently loses both the global limiter and its policies. - **Assuming a policy replaces the global limiter**: a generous endpoint policy cannot raise a limit the global limiter already enforces, because both permits are required. - **Policy names as magic strings** scattered across attributes and `Program.cs`; a constant per policy avoids the run-time `InvalidOperationException` that a typo causes.

  • An endpoint has no rate limiting policy, but GlobalLimiter is set. Is it limited?
    Yes, by the global limiter only. The middleware runs whenever a global limiter exists; for the endpoint stage it uses an internal no-limit partition, so only the global permit is required. Only `[DisableRateLimiting]` or `.DisableRateLimiting()` takes an endpoint out of the global limiter.
  • Why can't you register the global limiter with AddFixedWindowLimiter("global", ...)?
    `AddFixedWindowLimiter` registers a named endpoint policy that applies only where an endpoint references it. `GlobalLimiter` is a separate property of type `PartitionedRateLimiter<HttpContext>`, so you construct one with `PartitionedRateLimiter.Create` (or `CreateChained`) and a partitioner, using `RateLimitPartition` helpers for the per-key limiters.

  • [DisableRateLimiting] removes the endpoint policy but the global limiter still applies.
  • When an endpoint has a named policy, the global limiter is skipped for it.
  • An action's [EnableRateLimiting] always beats RequireRateLimiting on MapControllers.
  • GlobalLimiter is registered by naming a policy "global" in AddFixedWindowLimiter.
  • The endpoint policy runs before the global limiter.