Design a distributed rate limiter
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
Rate limiting looks like a simple counter until it becomes distributed. Interviewers probe the algorithmic trade-offs — fixed versus sliding windows, token versus leaky buckets — and then the correctness trap: two servers reading the same token before either writes. Candidates who reach for an atomic shared operation, and who design a clean 429 contract, stand out from those who only sketch an in-memory counter.
Mental model
At its core a limiter answers one atomic question: does this key have budget left? The token bucket is the usual choice because it allows bursts up to capacity while enforcing the refill rate on average. In a distributed system the bucket lives in a shared store, and the read-refill-decrement happens in one atomic step so concurrent servers cannot double-spend.
Step-by-step solution
Step 1: Compare four rate limiters
Four standard algorithms fit different goals. Fixed window counts requests per interval: trivial and memory-light, but bursts at a window boundary can pass twice the limit because the counter resets. Sliding window counter interpolates the previous window count, smoothing boundaries at almost no extra memory, while a full sliding-window log is exact but stores every timestamp. Token bucket holds up to C tokens and refills at R tokens per second; each request costs one token, so steady traffic is limited to R while short bursts up to C are allowed — the best fit for public APIs. Leaky bucket is the mirror image: requests enter a queue and drain at a constant rate, which smooths output but adds queueing latency. Watch the animation compare their shapes: the fixed window boundary spike, the smoothed sliding edge, the bucket burst then cap, and the leaky bucket steady drip. Choose based on whether you are protecting a backend or shaping traffic.
Step 2: Token bucket allows a request
Follow one allowed request. It arrives at the edge and is keyed by identity — API key for partners, user id for logged-in traffic, IP as a fallback. The edge asks the rate limiter for that key, and the limiter loads the bucket state: current tokens and last refill timestamp. Tokens regenerate at a fixed rate, so the limiter computes how many accumulated since the last check, caps the total at capacity, and checks the request cost. If at least one token is available, the limiter deducts it and returns allow, and the edge forwards the request to the backend. The backend never sees the limiter on the allowed path; the check is out-of-band and adds sub-millisecond overhead. Watch the animation: one token leaves the bucket, the request flows through, and the response carries limit headers so well-behaved clients can self-throttle before they are ever rejected.
Step 3: Bursts drain the bucket
Token bucket limits the average rate but intentionally allows bursts. If the bucket capacity is 100 and the refill is 10 requests per second, a client that has been idle accumulates up to 100 tokens; when it fires, the first 100 requests pass instantly and the bucket hits empty. From then on the client is limited to the 10-per-second refill, so a sustained overload cannot last. This matches real traffic: a mobile app waking up and syncing should not be throttled to the same rate as its long-run average. Watch the animation as the bucket drains in a burst to exactly zero, then sees each refill token consumed by the next request. Capacity is the maximum burst; refill rate is the sustained throughput. Tune C to the largest burst you can absorb behind the limiter and R to what the backend can actually serve per key, and remember that many keys burst at once even when each individual bucket looks fine.
Step 4: Atomic check across servers
One server can keep buckets in memory, but ten servers each allowing the full limit multiply the real limit by ten. The state must be shared, and the check-and-decrement must be atomic: between a GET and a SET, another request can read the same token count and both proceed — a classic race that silently doubles the allowed rate. Redis solves this with a single-threaded execution model plus atomic operations. The standard pattern is a small Lua script: read tokens and the last refill time, compute regenerated tokens, and if at least one is available, write back the decremented count and return allow, all in one atomic step. Set the key to expire after a few refill periods so idle buckets do not leak memory. Watch the animation as two simultaneous requests serialize inside Redis: the first decrements, and the second sees the new value and is correctly rejected when the bucket runs dry.
lua-- Atomic refill + check + decrement (Redis) local key = KEYS[1] local rate = tonumber(ARGV[1]) -- tokens per second local capacity = tonumber(ARGV[2]) -- max burst local now = tonumber(ARGV[3]) local cost = tonumber(ARGV[4] or '1') local tokens = tonumber(redis.call('HGET', key, 'tokens') or capacity) local ts = tonumber(redis.call('HGET', key, 'ts') or now) tokens = math.min(capacity, tokens + (now - ts) * rate) if tokens >= cost then redis.call('HSET', key, 'tokens', tokens - cost, 'ts', now) redis.call('EXPIRE', key, math.ceil(capacity / rate) * 4) return 1 -- allow end return 0 -- denyStep 5: Deny with 429 headers
When the limiter says no, the response itself is part of the design. Return HTTP 429 Too Many Requests, not a generic 500 and not a silent drop, and include machine-readable headers: RateLimit-Limit for the quota, RateLimit-Remaining for tokens left, RateLimit-Reset for seconds until refill, and Retry-After so well-behaved clients can back off precisely. Do not leak implementation details; a clear contract lets SDKs implement exponential backoff with jitter and avoids a thundering herd when a window resets. Key granularity matters too: per API key protects the platform, per user protects fairness, and per IP catches anonymous abuse but risks punishing everyone behind one NAT address. Watch the animation: the bucket is empty, the limiter returns deny, the edge short-circuits with 429 and headers, and the backend never sees the request. Cheap rejection at the edge is the entire point of a limiter.
Edge cases & traps
- Distributed races double the effective limit: make check-and-decrement atomic with a Redis Lua script or a single atomic operation, never a GET followed by a SET.
- Fixed windows allow twice the limit at boundaries: use a sliding window counter or a token bucket that enforces a sustained refill rate.
- A limiter outage must not take down the API: fail open by default or fail closed on security-sensitive routes, and fall back to a local in-memory limiter meanwhile.
- Per-IP limiting punishes users behind a shared NAT: prefer API keys or user ids when available and treat IP as a fallback dimension only.
- Clients retrying immediately after 429 create a thundering herd: return Retry-After and require jittered exponential backoff.