What it is
A distributed rate limiter decides, for every request entering an API, whether the caller (an API key, user, IP or route) is still within its allowance, and refuses the request with 429 Too Many Requests if not. In this case study it is a library inside every API gateway instance, backed by a regional in-memory counter store, with rules delivered by a separate control plane.
The Rate Limiting lesson covers the basics (why limits exist, per-client buckets, burst size, Retry-After). This lesson designs the system that enforces them across a fleet. The full interview walk-through, with API, data model and estimates, is at /system-design/interviews/rate-limiter.
Why it exists
A public API is shared capacity. Without per-key limits, one tenant's runaway batch job or scraper decides latency for everyone. Limits also protect expensive endpoints (login, search) from abuse. The hard part is not the algorithm; it is enforcing one limit consistently when requests for the same key land on hundreds of gateways, within a millisecond or two, and without making the limiter a new way for the API to fail.
How it works
Requirements and estimates. The interview version assumes about 1M requests/s at peak over roughly 300 gateways, so ~3,300 checks/s per gateway. With up to three matching rules per request, grouped by subject so most requests need about 1.2 store calls, that is ~1.2M counter operations/s. Planning ~50,000 script executions/s per store primary (well under what a single primary can do, to leave headroom) gives about 24 primaries per region. Memory is small: ~20M active buckets × ~150 B ≈ 3 GB. The latency budget, p99 under ~3 ms per check, fits only a same-region round trip (0.2–0.5 ms), which is why limits are enforced per region.
One instance: a local token bucket. Each key's bucket holds up to burst tokens and refills at rate tokens per second. A request takes one token or is refused. Refill is computed lazily from the time since the last check, so there is no background job. On one gateway this is exact.
A fleet breaks local counters. With N gateways and an independent bucket on each, a key gets up to N × the limit. Giving each instance limit ÷ N only works if every key's traffic is spread evenly; per-connection balancing and long-lived connections make the split lumpy, so a gateway that receives more than its slice refuses requests while the key is under its plan. Small limits (5 per minute) cannot be divided at all.
Shared counters. Keep each bucket in one place: a hash such as rl:{k_7f3a}:plan with fields tokens and ts, in an in-memory store (Redis Cluster in the interview design). Every key gets a TTL equal to its full refill time, so idle buckets disappear. The {...} hash tag puts all rules for one subject on the same shard, so one call can check them all.
Atomicity. GET, compute in the gateway, SET races: two gateways read "1 token", both allow. The fix is a short server-side script that refills, checks and decrements in one step and uses the store's own clock (TIME) so 300 gateway clocks do not need to agree. Denied requests do not consume tokens. For several rules on one subject, compute all buckets first and decrement only if all allow.
Window algorithms. A fixed window counter is a single atomic INCR with an expiry, but allows up to 2× the limit around a boundary. A sliding window counter keeps the previous and current window counts and estimates previous × (1 − elapsed/W) + current; it is approximate (it assumes the previous window's requests were evenly spread) but smooth and cheap. A sliding log is exact but stores one entry per request. Token bucket maps directly onto "rate plus burst" plans; sliding windows suit quotas such as "5 login attempts per minute".
Failure handling. Each store call has a strict timeout (around 5 ms in the interview design) and a breaker per shard. When the breaker is open, the gateway uses a local fallback bucket per subject of about limit × safety factor ÷ gateway count, and marks those decisions as fallback in its metrics.
When to use it
- Public or partner APIs with plans or quotas per key.
- Protecting expensive or abuse-prone endpoints (authentication, search, writes).
- Multi-tenant platforms where fairness between tenants matters.
- Any fleet where a per-key limit must hold regardless of which instance receives the request.
When not to
- Volumetric DDoS: absorb network floods upstream (CDN, WAF, network-level filtering); an application limiter behind them is too late and too expensive per packet.
- Billing quotas that must be exact over a month: use durable counters and reconciliation, not a cache that may lose a few hundred milliseconds of updates on failover.
- Very high per-key limits spread evenly across a fleet: plain local limits are accurate enough and avoid the store call.
- Protecting a backend from overload in general: that is load shedding and backpressure based on the backend's own health, not per-client limits.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Shared counters instead of local buckets | Exact limits regardless of traffic spread; small limits work | One round trip per check (~0.5 ms); a store to run and size |
| Atomic script instead of GET/SET | No over-admission under concurrency | Logic lives in the store; script deployment and versioning |
| Token bucket instead of sliding window | Natural "rate + burst" semantics, constant memory | Harder to explain as "N per window" quotas |
| Fail open with local fallback | API stays up when the store fails | Approximate limits (up to the safety factor) during the outage |
| Regional limits | Fits the latency budget; no cross-region dependency | A tenant's limit must be split between regions |
| Asynchronous store replication | Sub-millisecond writes | A failover forgets recent counts: brief over-admission |
Alternatives
- Purely local limits (limit ÷ instances): no dependency and no extra hop; accurate only for large limits with even balancing.
- A dedicated limiter service in the request path: central logic and language-agnostic, but another hop and another fleet, without better accuracy than the shared store it would also need.
- Token leasing: gateways take batches of tokens from the store and spend them locally; far fewer store calls for hot keys, slightly less precise.
- Managed gateway limits: cloud API gateways and service meshes offer per-key limits; check whether they are global or per instance and how they behave when their backing store fails.
Failure modes
- Fail-closed outage: treating "store unreachable" as "denied" refuses every request. The simulation shows the backend idle while the API is down.
- Over-admission after failover: asynchronous replication loses the latest decrements, so some buckets reset towards full. Usually acceptable for fairness limits.
- Hot keys: one tenant at very high rate saturates the shard that owns its key. Lease tokens or limit locally for such subjects.
- Bad rule rollout: a limit published as 1 instead of 1,000 causes mass false 429s. Validate changes, start new or tightened rules in shadow mode, keep the last good snapshot, make rollback one click.
- Cardinality attacks: creating counters for any string a client sends lets an attacker fill the store. Create per-key counters only after the key is validated.
- Synchronised retries: a constant
Retry-Afterbrings every refused client back at the same moment. Compute it from the bucket and ask clients to add jitter.
In production
Rules live in a durable, versioned store; gateways poll a validated snapshot and keep running on the last good one if the control plane is down. Export the rules version each gateway runs. Measure decisions per rule (allowed, denied, shadow-denied, fallback), store script latency and CPU per shard, and evictions. Page on fallback mode or a sustained limiter p99 above budget. Sample 429 logs instead of logging each one, since denial volume is driven by the very clients you are refusing. Return RateLimit-* headers and Retry-After so well-behaved clients can pace themselves.
Common misconceptions
- "Each instance can just enforce the limit." That multiplies the limit by the instance count.
- "Divide the limit by the number of instances." Only with perfectly even, per-request balancing; otherwise keys are refused while under their plan.
- "Redis is single-threaded, so GET then SET is safe." Each command is atomic; the sequence across the network is not. Use a script.
- "A rate limiter should fail closed to be safe." For fairness limits, failing closed causes the outage the limiter exists to prevent.
- "Fixed windows enforce N per window." Across a boundary a client can get 2N in a moment.
Interview angle
Start from requirements: what is limited (key, user, IP, route), rule shape (rate + burst, per-window quotas), accuracy tolerance and the latency budget. Estimate checks per second and store operations to size the counter store, then justify a regional in-memory store with atomic scripts. Interviewers probe the race condition, window algorithm trade-offs, what happens when the store dies (fail open with a local cap), hot keys, multi-region limits and how clients learn to back off. Work the full problem at /system-design/interviews/rate-limiter.
Model assumptions
The simulation follows a single API key, so a node's token bucket stands for that key's bucket; numbers are illustrative, not benchmarks. Arrivals are Poisson. Gateways have 32 workers and ~1 ms of work; the backend has 8 workers at a 50 ms mean (lognormal, cv 0.35), about 160 req/s. The shared counter store is modelled as a tiny server with a token bucket (50/s, burst 50) that every gateway calls before the backend; a request it refuses is counted as failed at the client (in reality a 429). The engine has no per-key script, so the store's internal atomicity is assumed, not simulated. Uneven connection-level balancing is modelled with weights (half the key's traffic on Gateway 1). Fail-open is shown as the state after the gateways' breakers have opened: they no longer call the store and enforce local buckets of 25/s (limit × 1.5 ÷ 3); timeouts and breaker transitions themselves are not simulated. The GET/SET race and the fixed versus sliding window comparison (5 requests per 1-second window) are scripted illustrations, not simulation output. Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together.