A full distributed rate limiter design: requirements and plans, algorithm choice (token bucket vs sliding window), placement (edge, gateway, in-app), shared state in Redis with atomic Lua scripts, per-key and per-region limits, 429 with Retry-After, fail-open vs fail-closed, and the .NET 10 rate limiting middleware.
A rate limiter protects the service and enforces fairness between customers. I'd use a token bucket per API key: capacity = burst, refill rate = plan limit. It allows short bursts but caps the average. Limits sit in layers: per IP at the edge (Front Door WAF), per API key at the gateway or in the API, and per endpoint for expensive operations. With many instances, the bucket lives in Redis, updated by an atomic Lua script in one round trip, sharded by key. Rejections return 429 with Retry-After. When Redis is unavailable I fail open to a local in-memory limiter with the limit divided by instance count, because rejecting all paying traffic is worse than briefly over-admitting. The trade-off is accuracy versus latency and availability: an exact global limit costs a network hop on every request.
"First I'd clarify what we're protecting and from whom. Here it's fairness between [thousands of] partner API keys, each on a plan, say Free at 10 requests a second and Enterprise at 500, plus protecting the backend from overload. I'd ask whether the limit is global or per region, whether bursts are allowed, and whether a few percent over the limit is acceptable. Usually it is, which matters a lot for the design.
Then numbers: say 50,000 requests a second at peak across 30 instances and two regions, with 2 million keys of which maybe 50,000 are active in any minute. If every request does one Redis call, that's 50,000 operations a second. Redis handles that, but a Lua script per request is heavier than a GET, so I'd use a clustered Redis sharded by key. Memory is tiny: 50,000 active buckets at 100 bytes is 5 MB.
For the algorithm I pick a token bucket: each key has capacity for its burst and refills at its plan rate. The check is one Lua script that refills based on elapsed time, takes a token if there is one, and returns the remaining tokens and wait time, atomically, so two instances can't both spend the last token. Placement is layered: Front Door WAF rate rules per IP to absorb floods cheaply, then per-key limits in API Management with
rate-limit-by-key, or in ASP.NET Core with aPartitionedRateLimiterif we don't have a gateway. Rejected requests get 429 with Retry-After so well-behaved clients back off.The mistake I see is using the built-in ASP.NET Core limiter alone on 30 instances: it's per process, so a partner effectively gets 30 times their limit, unevenly. And deciding failure behaviour too late. If Redis goes away I fail open to a local limiter at limit รท instances. A rate limiter that takes the API down is worse than no rate limiter."
| Type | Requirement | Assumption |
|---|---|---|
| Functional | Limit per API key by plan (e.g. 10, 100, 500 req/s) | Plans change rarely; cache plan lookups |
| Functional | Stricter limit on costly endpoints (exports, search) | Concurrency limit, not rate |
| Functional | Clients learn limits and retry time | 429, Retry-After, RateLimit-* headers |
| Non-functional | Adds < 2 ms p99 | One Redis round trip in-region |
| Non-functional | ~5% over-admission acceptable | Allows per-region buckets and local fallback |
| Non-functional | Limiter failure must not take the API down | Fail open by default |
| Quantity | Arithmetic | Result |
|---|---|---|
| Peak requests | given | 50,000/s |
| Redis script calls | 1 per request | 50,000/s (โ 25k per region) |
| Active buckets per minute | assumption | 50,000 |
| Memory | 50,000 ร ~100 B | โ 5 MB |
| Added latency | in-region Redis RTT | ~0.5โ1 ms |
Client โโโบ Front Door WAF (per-IP rate rule: floods, scrapers)
โ
โผ
API Management (rate-limit-by-key / quota-by-key on subscription or API key)
โ
โผ
ASP.NET Core API (per-tenant + per-endpoint limits, concurrency limits on exports)
โ
โผ
Azure Managed Redis (token buckets, Lua script, keyed rl:{apiKey})
| Algorithm | Behaviour | Good for | Weakness |
|---|---|---|---|
| Fixed window | Count per minute bucket | Simple quotas | 2ร burst at window edges |
| Sliding window log | Store each timestamp | Exact | Memory per request |
| Sliding window counter | Weighted current + previous window | Strict per-minute quotas | Approximate |
| Token bucket | Refill rate + capacity | APIs with bursts | Two parameters to explain |
| Concurrency limiter | Max in-flight | Expensive endpoints | Not a rate |
For a partner API at [40,000] req/s across two Australian regions, per-region token buckets in Redis added about 0.8 ms p99. During a 4-minute Redis failover the API fell back to local limiters; over-admission peaked at about 7% and no partner saw errors, whereas the previous fail-closed design had returned 429 to everyone.
Checks that the candidate can design a correct distributed limiter and reason about where it lives and how it fails.
Green flags
Red flags
A bucket holds up to capacity tokens and gains rate tokens per second. A request costs one token (or more for expensive calls). You don't need a timer: store tokens and lastRefill, and on each request compute
now = server time
tokens = min(capacity, tokens + (now - lastRefill) ร rate)
allowed = tokens >= cost
if allowed: tokens -= cost
retryAfter = allowed ? 0 : (cost - tokens) / rate
A plan of "100 req/s, burst 200" is rate = 100, capacity = 200.
With GET-then-SET from two instances:
Instance A: GET tokens โ 1 Instance B: GET tokens โ 1
Instance A: SET tokens = 0 Instance B: SET tokens = 0 โ both admitted
A Lua script runs atomically on the Redis shard that owns the key, so read-modify-write happens without interleaving, and it is one network round trip. Use the Redis server time (TIME) inside the script, or pass a single clock source, so instance clock skew doesn't mint tokens. Keep each key's data in one hash slot (rl:{apiKey}) so Redis Cluster can run the script.
A truly global limit across Australia East and Southeast needs cross-region Redis calls (~10โ15 ms) or active geo-replication, which is eventually consistent anyway. The usual compromise is per-region buckets with the limit split by traffic share, or the full limit per region when ~2ร over-admission during a failover is acceptable. State the choice explicitly.
Microsoft.AspNetCore.RateLimiting middleware: AddRateLimiter, policies with AddTokenBucketLimiter, AddSlidingWindowLimiter, AddConcurrencyLimiter, and PartitionedRateLimiter.Create to partition by API key. State is in process, so it's per instance.System.Threading.RateLimiting lets you write a custom RateLimiter (e.g. backed by Redis) and plug it into the same middleware.rate-limit-by-key (short window, per gateway) and quota-by-key (longer quotas). Check the current docs for how counters are shared in multi-region deployments; they are not guaranteed to be exact globally.429 Too Many Requests with Retry-After: <seconds>. Many APIs also send RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset (or the newer combined RateLimit / RateLimit-Policy fields from the IETF draft). Document them so SDKs back off with jitter instead of hammering.
TokenBucketRateLimiter at limit รท instance count. Log and alert.rl:{key}:0..n) with limit รท n each, or give them a dedicated limit layer.CloudFront + AWS WAF rate-based rules, API Gateway usage plans with throttling per API key, ElastiCache for Redis for custom limits.
bombardier -c 50 -n 2000; confirm the 429 count matches the maths.ScriptEvaluateAsync, and test two concurrent callers never both take the last token.dotnet-counters and Application Insights dependency timings.Per-key token buckets with the built-in middleware (per instance), plus the atomic Redis script for a shared limit.
// Program.cs: built-in limiter, partitioned by API key. Per process only.
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(http =>
{
var apiKey = http.Request.Headers["X-Api-Key"].ToString();
var perSecond = PlanLookup.RequestsPerSecond(apiKey); // cached plan lookup
return RateLimitPartition.GetTokenBucketLimiter(apiKey, _ => new TokenBucketRateLimiterOptions
{
TokenLimit = perSecond * 2, // burst capacity
TokensPerPeriod = perSecond, // refill rate
ReplenishmentPeriod = TimeSpan.FromSeconds(1),
QueueLimit = 0, // reject, don't queue: clients retry
AutoReplenishment = true
});
});
options.OnRejected = (ctx, _) =>
{
if (ctx.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
ctx.HttpContext.Response.Headers.RetryAfter = ((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString();
return ValueTask.CompletedTask;
};
});
var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/api/orders", () => Results.Ok());
app.Run();
static class PlanLookup
{
public static int RequestsPerSecond(string apiKey) => string.IsNullOrEmpty(apiKey) ? 1 : 100;
}
// Shared token bucket in Redis (StackExchange.Redis). One atomic round trip per request.
using StackExchange.Redis;
namespace RateLimiting;
public sealed record RateDecision(bool Allowed, double RetryAfterSeconds);
public sealed class RedisTokenBucket(IConnectionMultiplexer redis)
{
// KEYS[1] = bucket; ARGV = rate, capacity, cost. Uses Redis TIME so instance clocks don't matter.
private const string Script = """
local t = redis.call('TIME')
local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
local rate, cap, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or cap
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + (now - ts) * rate)
local allowed = 0
local wait = 0
if tokens >= cost then tokens = tokens - cost; allowed = 1 else wait = (cost - tokens) / rate end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(cap / rate) + 1)
return { allowed, tostring(wait) }
""";
public async Task<RateDecision> TryTakeAsync(string apiKey, double rate, double capacity, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var result = (RedisResult[])(await redis.GetDatabase().ScriptEvaluateAsync(
Script, [new RedisKey($"rl:{{{apiKey}}}")], [rate, capacity, 1]))!;
return new RateDecision((int)result[0] == 1, double.Parse((string)result[1]!, System.Globalization.CultureInfo.InvariantCulture));
}
}
INCR with expiry for fixed windows) so the check is atomic.TIME inside the script.The senior conversation is about accuracy versus availability. Exact global limits need a coordinated store on every request; most businesses are happy with ยฑ5% if it means no added outage risk. I also push for buying before building: Front Door WAF and API Management cover most needs, and a custom Redis limiter is justified only when limits depend on business data the gateway can't see (per tenant, per expensive operation, cost-weighted calls).
| Placement | When it fits | Cost | When not to |
|---|---|---|---|
| Front Door WAF rules | Floods, scrapers, per-IP | Cheap, at the edge | Per-customer plans |
| API Management rate-limit-by-key / quota-by-key | Plans per subscription key | APIM tier cost, approximate across regions | Limits need domain data |
| ASP.NET Core in-process | Single instance, or fallback | Free | Many instances needing a shared limit |
| Custom Redis limiter | Per tenant/endpoint, cost-weighted | Redis + code to own | When a gateway already does it |
I measure it with rejections per key, Redis script latency (p99), over-admission against the plan in load tests, and the fallback activation count.
Rate limiting caps how many requests a client may make in a period and rejects the excess; throttling usually means slowing or queueing the excess instead of failing it. The common algorithms are: fixed window (N requests per minute, simple but allows a 2N burst across a window boundary), sliding window (the window is split into segments so the boundary burst is smoothed), token bucket (tokens refill at a steady rate, the bucket size is the allowed burst) and a concurrency limiter (caps requests in flight, not per second). A good API returns 429 Too Many Requests with Retry-After so clients back off instead of hammering. The trade-off is precision versus cost: exact, distributed limits need shared state; per-instance in-memory limits are cheap but approximate.
The built-in middleware keeps counters in each process, so 10 instances allow roughly 10x the limit. Options: divide the limit by the instance count (cheap, approximate, and wrong as soon as autoscaling changes the count); enforce at a shared edge such as Azure API Management rate-limit-by-key / quota-by-key; or use a Redis-backed limiter (sliding window or token bucket in an atomic Lua script) for exact limits, at the cost of a network hop per request. Decide up front what happens when Redis is unreachable: fail open with a per-instance local limiter as a fallback, or fail closed for abuse-sensitive endpoints such as login.
A capacity estimate turns user numbers into load. Start with daily active users ร actions per user to get requests per day, divide by ~86,400 s (round to 10^5) for average requests/s, then multiply by a peak factor (2โ10ร, often 3ร). For storage, multiply writes per day by record size and 365, then add indexes and replicas. For bandwidth, multiply requests/s by payload size.
Example: 10M DAU ร 20 reads = 200M reads/day โ 2,300/s average, ~7,000/s peak.
The point is not precision โ it's deciding whether one database and a cache are enough or you need partitioning. The trade-off is speed versus accuracy: round hard, but state every assumption.
How to tell it (STAR)
**S:** At [company] our partner API slowed for everyone each evening, and one partner's batch job was the trigger. **T:** I had to find why our rate limits weren't stopping it. **A:** In Log Analytics I grouped requests by key and replica and saw the partner getting their full limit on each of [24] replicas, because the built-in limiter keeps state in process. I added a gateway limit that night, then built a shared Redis token bucket with an atomic Lua script and a local fallback, and added Retry-After so their SDK backed off. **R:** The partner settled at their [100 req/s] plan, evening p95 went back to [130 ms], and database CPU dropped from [95%] to [45%].
Last updated 23 Nov 2026.