Design a Distributed Rate Limiter
A rate-limiting service for an API platform handling millions of requests per second — rules and configuration, placement (gateway, sidecar, library), the algorithm choice, atomic Redis implementation, latency budgets, fail-open vs fail-closed, local batching and approximate limits, multi-region limits, and observability.
1. Requirements
Functional
- Limit requests by configurable keys: API key, user, IP, tenant, endpoint — e.g., free tier: 100 req/min; pro: 2,000 req/min with bursts of 200.
- Return
429 Too Many RequestswithRetry-Afterand rate-limit headers. - Rules change without deploys; shadow mode for new rules.
Non-functional
- Adds < 2 ms p99 latency.
- Handles 1M+ checks/s.
- Highly available; a limiter failure must not take down the API.
- Accuracy: small overshoot acceptable for most rules; exact for security rules.
2. Estimation
| Quantity | Value |
|---|---|
| Checks | 1M/s peak |
| Active keys | 10M |
| State per key (token bucket) | ~50 B (key + tokens + timestamp) → ~500 MB + overhead |
| Redis throughput | ~100k–200k ops/s per shard → ~10 shards with headroom |
3. High-level design
Flow: request arrives → gateway authenticates and extracts keys (API key, IP, route) → finds matching rules (in-memory) → for each rule runs an atomic script in Redis (all rules for one request can be batched in a single script/pipeline) → allowed: forward and add RateLimit-* headers; denied: return 429 with Retry-After.
4. The atomic check
-- KEYS[1] = bucket key; ARGV = capacity, refill_per_ms, now_ms, cost
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local cap, rate, now, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4])
local tokens = tonumber(b[1]) or cap
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + math.max(0, now - ts) * rate)
local allowed = tokens >= cost
if allowed then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate) * 2)
local retry_ms = allowed and 0 or math.ceil((cost - tokens) / rate)
return { allowed and 1 or 0, math.floor(tokens), retry_ms }
The algorithms themselves (token bucket, sliding window variants, in-process implementations) are covered in depth in Backend: rate limiting, and the object-oriented design in LLD case studies II.
5. Deep dives
Scaling beyond one Redis round trip per request
- Batch reservations: each node takes N tokens at a time from the central bucket and spends them locally.
- Periodic sync: nodes count locally and push deltas every 100 ms; the central store returns the global count.
- Sticky routing (consistent hashing of API key → gateway node) makes local limiting exact without a shared store, until nodes change.
Hot keys
One giant tenant hammering one Redis key: shard that key into sub-buckets (key#0..7, each with 1/8 of the limit, chosen randomly) or use local reservation for that tenant.
Failure handling
| Failure | Behaviour |
|---|---|
| Redis timeout (> 5 ms) | fail open for normal API limits; log + metric |
| Redis shard down | replica promotion; fall back to local in-memory limits meanwhile |
| Security limits (login, OTP) | fail closed or strict local limit |
| Config store down | keep using last-known rules in memory |
Multi-region
Each region enforces its share locally; counters replicated asynchronously for monitoring; per-tenant home region for strict quotas. Accept that a client spraying all regions can briefly exceed the global limit.
6. Client contract
HTTP/1.1 429 Too Many Requests
Retry-After: 12
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 12
Content-Type: application/problem+json
{"type": "https://api.example.com/errors/rate-limited", "title": "Too many requests", "status": 429}
7. Trade-offs summary
| Decision | Choice | Why |
|---|---|---|
| Algorithm | token bucket (+ sliding window for some) | bursts + O(1) state |
| Store | Redis Cluster + Lua | atomic, ~0.5 ms |
| Placement | gateway (+ service-level for business limits) | reject early |
| Failure policy | fail open (most), closed (security) | availability vs safety |
| Global limits | per-region split + async reconciliation | latency over precision |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.