In ASP.NET Core, why does AddFixedWindowLimiter give every caller one shared counter, and how would you limit a weather API's free tier per user and per IP?
answer
- one limiter per policy name
- AddPolicy with a partitioner
- RateLimitPartition.GetFixedWindowLimiter(key, factory)
- User.Identity.Name, else RemoteIpAddress
- counters live in one process
basics
~10 sAddFixedWindowLimiter keys its limiter on the policy name, so all callers share it. Use AddPolicy with a partitioner returning RateLimitPartition.GetFixedWindowLimiter keyed on the user name, or on Connection.RemoteIpAddress for anonymous callers.
solid answer
~50 sThe four `Add*Limiter` helpers build their partition from a constant key derived from the policy name, so every request on every endpoint using that policy draws from one counter: one heavy caller can exhaust the free tier for everybody. For per-client limits, call `options.AddPolicy("free-tier", httpContext => ...)` and return a `RateLimitPartition`, for example `RateLimitPartition.GetFixedWindowLimiter(key, _ => new FixedWindowRateLimiterOptions { PermitLimit = 100, Window = TimeSpan.FromHours(1) })`. Use `httpContext.User.Identity?.Name` when the caller is authenticated and `httpContext.Connection.RemoteIpAddress` otherwise, prefixing the keys so a user name cannot collide with an address. The middleware creates and caches one limiter per key and evicts limiters that sit idle at full allowance. Those counters live in the process's memory, so three instances behind a load balancer allow roughly three times the limit, and a key taken from an unverified header lets clients mint fresh partitions at will.
code
csharp · 23 linespublic sealed class FreeTierPolicy(ILogger<FreeTierPolicy> logger) : IRateLimiterPolicy<string>
{
public Func<OnRejectedContext, CancellationToken, ValueTask>? OnRejected => (ctx, _) =>
{
logger.LogInformation("Free tier limit hit for {Path}", ctx.HttpContext.Request.Path);
return ValueTask.CompletedTask;
};
public RateLimitPartition<string> GetPartition(HttpContext httpContext)
{
var user = httpContext.User.Identity?.Name;
if (user is not null)
return RateLimitPartition.GetFixedWindowLimiter("user:" + user,
_ => new FixedWindowRateLimiterOptions { PermitLimit = 1000, Window = TimeSpan.FromDays(1) });
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
return RateLimitPartition.GetFixedWindowLimiter("ip:" + ip,
_ => new FixedWindowRateLimiterOptions { PermitLimit = 50, Window = TimeSpan.FromDays(1) });
}
}
// Program.cs
builder.Services.AddRateLimiter(o => o.AddPolicy<string, FreeTierPolicy>("free-tier"));go deeper
Remember that the simple Add*Limiter helpers give one shared counter, and that per-client limits use AddPolicy with RateLimitPartition.
Explain how the partitioner's key selects a cached limiter, the factory runs once per key, and idle limiters are evicted.
Choose a verified key, prefix keys to avoid collisions, account for proxies and NAT, and state that counters are per process, so N replicas multiply the effective limit.
Decide whether in-app per-instance limits are good enough for the business promise of a quota, or whether quotas must be enforced centrally with shared state.
## Why the helpers share one counter `AddFixedWindowLimiter("free", ...)`, `AddSlidingWindowLimiter`, `AddTokenBucketLimiter` and `AddConcurrencyLimiter` are thin wrappers over `RateLimiterOptions.AddPolicy`. Each wrapper builds a single key object from the **policy name** and returns `RateLimitPartition.GetFixedWindowLimiter(key, ...)` with that same key for every request. The middleware's endpoint limiter is a `PartitionedRateLimiter<HttpContext>` that keeps **one limiter per partition key**, so a constant key means one limiter for: - every client, authenticated or not; - every endpoint that names that policy, not just one. That is the right behaviour for protecting a shared resource (a downstream service that can take 500 calls a minute in total). It is the wrong behaviour for a **free tier**, where one script hammering `/forecast` must not use up the allowance of every other user. ## Partitioning with AddPolicy A **partition** is a bucket of requests that share a limiter. You choose the bucket by returning a `RateLimitPartition<TKey>` from a function of `HttpContext`: ```csharp options.AddPolicy("free-tier", httpContext => { var user = httpContext.User.Identity?.Name; return user is not null ? RateLimitPartition.GetTokenBucketLimiter("user:" + user, _ => new TokenBucketRateLimiterOptions { TokenLimit = 20, TokensPerPeriod = 5, ReplenishmentPeriod = TimeSpan.FromMinutes(1) }) : RateLimitPartition.GetFixedWindowLimiter("ip:" + httpContext.Connection.RemoteIpAddress, _ => new FixedWindowRateLimiterOptions { PermitLimit = 30, Window = TimeSpan.FromHours(1) }); }); ``` How the middleware uses it: 1. On each request it calls your function and reads the partition's key. 2. If a limiter for that key is cached, it is reused; otherwise the factory runs once and the new limiter is cached. 3. A background timer replenishes all cached limiters and **evicts** any limiter that is back at its full allowance and has sat that way for more than ten seconds, so the cache does not grow forever with one-off visitors. `RateLimitPartition` also offers `GetSlidingWindowLimiter`, `GetConcurrencyLimiter`, `GetNoLimiter` (an unlimited partition, useful for an internal health probe or a paying tier) and `Get` (any `RateLimiter` you build). For a policy that needs dependencies from DI, implement `IRateLimiterPolicy<TPartitionKey>` and register it with `AddPolicy<string, FreeTierPolicy>("free-tier")`; the class is activated from the service provider. ## Choosing the key | Key | Good for | Watch out for | |---|---|---| | `User.Identity.Name` or a user-id claim | signed-in users, stable across devices | only meaningful after authentication has run | | `Connection.RemoteIpAddress` | anonymous callers | behind a proxy this is the proxy's address until forwarded headers are processed; many users can share one NAT address | | An API key from a header | developer tiers | an **unverified** header value lets a client invent a new key, and so a fresh allowance, on every request | The ASP.NET Core docs warn explicitly that partitioning on client-controlled input exposes the app to denial of service: every distinct value creates a limiter, and spoofed values bypass the limit entirely. Key on something the server has verified. ## Limits of an in-process limiter - **Per instance**: the partitions live in the memory of one process. Three replicas behind a load balancer each keep their own counters, so a client can get up to three times the configured allowance, depending on how requests are spread. The built-in middleware has no shared store; a cluster-wide quota needs a gateway or a custom `RateLimiter` backed by shared storage. - **Restarts reset everything**: a deploy gives every client a fresh window. - **Prefix keys** (`user:`, `ip:`) so that a user called `10.0.0.1` cannot share a bucket with that address. ## Putting it on the endpoints Attach the policy as usual with `RequireRateLimiting("free-tier")` on a route group, or `[EnableRateLimiting("free-tier")]` on a controller. Rejections still use `RejectionStatusCode`, which is **503** until you change it.
- Two endpoints both use RequireRateLimiting("free-tier") with the partitioned policy above. Do they share a user's allowance?Yes. The partition key is what your function returns, here `user:alice`, and the middleware caches one limiter per key for the policy, so both endpoints draw from Alice's single bucket. To give each endpoint its own allowance, include the endpoint or route in the key, or register separate policies.
- How do you exempt a paying customer from the free-tier policy without a second endpoint?Return `RateLimitPartition.GetNoLimiter(key)` from the partitioner when the authenticated principal carries the paid-plan claim. That partition always grants a lease, so the endpoint stays unlimited for that caller while anonymous and free users keep their limiters.
- Why might every anonymous caller suddenly share one IP partition after a deploy behind a new load balancer?`Connection.RemoteIpAddress` is the address of whoever opened the TCP connection, which is now the load balancer. Until the app is configured to trust and process its forwarded headers, every anonymous request carries the load balancer's address and lands in the same partition, so all anonymous callers share one allowance.
A museum that hands out a single day's worth of free tickets from one box at the door runs out for everyone once a tour group grabs them; giving each visitor a personal punch card, checked against their ID, is partitioning. If visitors may write any name on a blank card, they can take a new card whenever the old one is full.
- AddFixedWindowLimiter keeps a separate counter for each client IP automatically.
- Partitioning on a raw X-Api-Key header value is safe without validating it.
- Partitioned limiters are shared across all instances of the app.
- Each endpoint using the same partitioned policy gets its own counter per user.
- RateLimitPartition.GetNoLimiter rejects every request in that partition.