In ASP.NET Core, how do AddFixedWindowLimiter, AddSlidingWindowLimiter, AddTokenBucketLimiter and AddConcurrencyLimiter differ in what they count and how you configure them?
answer
- three count rate, one counts in-flight
- PermitLimit plus Window
- SegmentsPerWindow for sliding
- TokenLimit, TokensPerPeriod, ReplenishmentPeriod
- QueueLimit defaults to 0
basics
~20 sFixed window, sliding window and token bucket cap requests per time period; the concurrency limiter caps requests in flight at once. Each takes its own options class (Window, SegmentsPerWindow, TokensPerPeriod, PermitLimit), and all queue nothing unless QueueLimit is set.
solid answer
~40 sAll four are extension methods on `RateLimiterOptions` that register a named policy around a `System.Threading.RateLimiting` limiter. `AddFixedWindowLimiter` takes `FixedWindowRateLimiterOptions` (`PermitLimit` per `Window`); `AddSlidingWindowLimiter` adds `SegmentsPerWindow` so permits from old segments come back gradually; `AddTokenBucketLimiter` uses `TokenLimit` as the bucket size and adds `TokensPerPeriod` every `ReplenishmentPeriod`, which allows bursts up to the bucket size. `AddConcurrencyLimiter` is different in kind: its `PermitLimit` is how many requests may run simultaneously, and a permit returns when a request finishes, not when time passes. Every options class has `QueueLimit` (default 0, so excess requests are rejected at once) and `QueueProcessingOrder` (default `OldestFirst`). `AutoReplenishment` is ignored here because the middleware's partitioned limiter drives replenishment itself.
code
csharp · 21 linesbuilder.Services.AddRateLimiter(options =>
{
options.AddSlidingWindowLimiter("forecast", o =>
{
o.PermitLimit = 60;
o.Window = TimeSpan.FromMinutes(1);
o.SegmentsPerWindow = 6;
});
options.AddTokenBucketLimiter("history-export", o =>
{
o.TokenLimit = 10;
o.TokensPerPeriod = 1;
o.ReplenishmentPeriod = TimeSpan.FromSeconds(6);
});
options.AddConcurrencyLimiter("radar-render", o =>
{
o.PermitLimit = 4;
o.QueueLimit = 8;
o.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
});
});go deeper
Know there are four built-in kinds and that three of them limit requests per time while the concurrency limiter limits requests running at once.
Name each options class and its key properties, and state the shared defaults: QueueLimit 0 and QueueProcessingOrder OldestFirst; AutoReplenishment is overridden by the middleware.
Match the kind to the scarce resource of each endpoint, and explain why a missing Window only fails on the first request that builds the limiter.
Weigh queueing against fast rejection for each tier of clients, and decide which limits belong in the app and which in shared infrastructure.
## Four registration helpers, one shape `RateLimiterOptionsExtensions` in `Microsoft.AspNetCore.RateLimiting` defines four helpers. Each has the same shape: a **policy name** and a callback that fills in an options object from `System.Threading.RateLimiting`. ```csharp options.AddFixedWindowLimiter("name", o => { /* FixedWindowRateLimiterOptions */ }); options.AddSlidingWindowLimiter("name", o => { /* SlidingWindowRateLimiterOptions */ }); options.AddTokenBucketLimiter("name", o => { /* TokenBucketRateLimiterOptions */ }); options.AddConcurrencyLimiter("name", o => { /* ConcurrencyLimiterOptions */ }); ``` The algorithms behind the first three (why a fixed window allows a burst at the boundary, how a token bucket smooths traffic) are general rate-limiting theory. What an ASP.NET Core interview checks is which options each class has, what their defaults are, and which kind fits which endpoint. ## What each one counts | Helper | Options class | Key options | What a permit means | |---|---|---|---| | `AddFixedWindowLimiter` | `FixedWindowRateLimiterOptions` | `PermitLimit`, `Window` | one request in the current window; the count resets when the window ends | | `AddSlidingWindowLimiter` | `SlidingWindowRateLimiterOptions` | `PermitLimit`, `Window`, `SegmentsPerWindow` | one request in the trailing window; permits from the oldest segment return as the window slides | | `AddTokenBucketLimiter` | `TokenBucketRateLimiterOptions` | `TokenLimit`, `TokensPerPeriod`, `ReplenishmentPeriod` | one token; up to `TokensPerPeriod` tokens are added every period, never above `TokenLimit` | | `AddConcurrencyLimiter` | `ConcurrencyLimiterOptions` | `PermitLimit` | one request **currently executing**; returned when the request completes | The first three limit a **rate** (requests per time). The concurrency limiter limits **parallelism** and has no time option at all: a slow report endpoint with `PermitLimit = 4` can serve far more than four requests a minute, but never more than four at the same moment. ## The options every kind shares - **`QueueLimit`** (default **0**): how many requests may wait for a permit. At 0 a request that finds no permit is rejected immediately. - **`QueueProcessingOrder`** (default **`OldestFirst`**): which queued request gets the next permit. With `NewestFirst`, a new arrival that finds the queue full pushes the oldest waiter out with a failed lease. - **`AutoReplenishment`** (default `true` on the three time-based classes; the concurrency options have none): the three time-based helpers force it to `false`, because the middleware's `PartitionedRateLimiter` runs one timer for all its limiters and replenishes them itself. Setting it has no effect. ## Validation happens late The options are validated when the limiter is constructed, which for a policy is the first request that needs it. `PermitLimit` and `TokenLimit` must be greater than 0, `Window` and `ReplenishmentPeriod` greater than `TimeSpan.Zero`, `SegmentsPerWindow` and `TokensPerPeriod` greater than 0, and `QueueLimit` at least 0; otherwise the constructor throws `ArgumentException`. A policy that forgets to set `Window` therefore compiles, starts, and fails on its first request. ## Choosing one for a weather-data API 1. **Hourly forecast lookups** on the free tier: a fixed or sliding window of, say, 60 per minute. Sliding with 6 segments avoids a client spending a whole minute's allowance on both sides of the boundary. 2. **A bulk historical download**: a token bucket with `TokenLimit = 10`, `TokensPerPeriod = 1`, `ReplenishmentPeriod = 6 s`, which tolerates a short burst but averages ten a minute. 3. **A CPU-heavy radar-image render**: a concurrency limiter with `PermitLimit = 4` and a small `QueueLimit`, because the scarce resource is simultaneous work, not calls per minute. ## A note on shared counters Each of the four helpers creates **one limiter per policy name**: every caller and every endpoint that uses the policy draws from the same counter. They are the right tool for protecting a resource as a whole. A per-user or per-IP allowance needs `AddPolicy` with a `RateLimitPartition` instead, built from the same options classes.
- Why can't a concurrency limiter put a Retry-After value on its rejection?A concurrency permit comes back when some other request finishes, which the limiter cannot predict, so its failed lease carries no `MetadataName.RetryAfter` entry (only an optional `ReasonPhrase`). Failed leases from the fixed window, sliding window and token bucket limiters can carry `RetryAfter`, because those limiters know when the next window, segment or token arrives.
- What does raising QueueLimit cost on a rate-limited endpoint?Queued requests hold their connection and the client's time while they wait for a permit, and the client sees latency instead of a fast rejection. A small queue smooths brief bursts; a large one turns overload into slow responses and timeouts. A queued request that the client cancels is dropped without `OnRejected` running.
- A concurrency limiter caps how many requests a client sends per minute.
- Setting AutoReplenishment = false in AddFixedWindowLimiter stops the window from resetting.
- QueueLimit defaults to a small buffer, so bursts are queued automatically.
- Missing Window or PermitLimit values fall back to sensible defaults.
- A token bucket's TokenLimit is how many tokens are added each period.