Design a Distributed Rate Limiter
A deceptively deep question. The algorithm is the easy part; the interview lives in distributed counter accuracy, latency budget, and what happens when the store is down.
#1. Requirements
Functional
- Limit requests per client to a configured rate.
- Multiple rules simultaneously: per-user, per-IP, per-endpoint, per-tenant.
- Return
429withRetry-Afterand remaining-quota headers. - Rules configurable at runtime, without a deploy.
Non-functional
- Latency: sub-millisecond added to every request. This is the hardest constraint — it's on the path of literally every request.
- Accurate enough — brief overshoot acceptable, order-of-magnitude error not.
- Highly available. The limiter must not become the reason the API is down.
- Scales to the full request volume of the platform.
Clarifying questions:
- Is this an edge service, a library linked into each app, or a sidecar (a small helper process running next to each service instance)?
- How exact must limits be? ("about 1000/min" vs "never more than 1000")
- What should happen if the rate-limit store is unavailable?
- Do limits need to be global across regions?
#2. Estimation
Assume 1M QPS across the platform, 10M active clients, and 3 rules evaluated per request.
Counter operations: 1M × 3 rules = 3M ops/s
State per counter (token bucket): tokens (8B) + last_refill (8B)
+ key overhead ≈ 100 B
Active counters: 10M clients × 3 rules = 30M
Memory: 30M × 100 B = 3 GB ← fits comfortably in RAM
Redis capacity: ~100K ops/s per shard (conservative, with Lua)
→ 3M / 100K = 30 shards minimum, ~50 with headroomWhat this decided: 3 GB means the entire state is memory-resident — no persistence needed, since counters are recreatable and worthless after their window. 3M ops/s means the naive "one Redis" answer fails and we must shard, which then raises the question of how to shard.
#3. Algorithm choice
Covered fully in Rate Limiting. For this design:
Token bucket, because real traffic is bursty. A user opening a page fires a dozen requests at once — legitimate behaviour that a fixed window would reject. Yet a fixed window still lets an attacker through at double the rate: with "100 per minute", they send 100 in the last second of one minute and 100 more in the first second of the next — 200 in two seconds (the 2× boundary burst).
Token bucket has two separate knobs: the bucket's capacity (how big a burst you allow at once, say 20) and its refill rate (the long-run average you allow, say 100 per minute). That separation of burst size from sustained rate is the distinction that matters.
Only two values are stored, and refill is computed lazily on access:
elapsed = now - last_refill
tokens = min(capacity, tokens + elapsed × refill_rate)
if tokens >= 1: tokens -= 1; ALLOW
else: DENY, retry_after = (1 - tokens) / refill_rateNo background timer, no per-tick work — the state is updated only when a request arrives.
#4. High-level design
client ──► ┌──────────────────────────────────────┐
│ EDGE / GATEWAY │
│ ┌────────────────────────────────┐ │
│ │ 1. resolve rules for request │ │
│ │ (from local rule cache) │ │
│ │ 2. check LOCAL token cache │ │──┐
│ │ 3. if needed, check Redis │ │ │
│ └────────────────────────────────┘ │ │
└──────────────┬───────────────────────┘ │
│ allowed │ 429
▼ ▼
upstream service client
┌─────────────────────────────────┐
│ Redis cluster (sharded by key) │ counters
└─────────────────────────────────┘
┌─────────────────────────────────┐
│ Config service → rules │ pushed to
└─────────────────────────────────┘ edge, cachedWhere to enforce: at the edge/gateway. A rejected request should cost as little as possible — one rejected after a database round trip has already consumed the resources you were protecting.
#5. Deep dive — distributed counters
This is the heart of the question.
#The atomicity requirement
With 50 gateway instances, GET then SET is a race — two instances read 99, both allow, both write 100. The check-and-decrement must be atomic.
Redis handles one command at a time per shard, and it will run a whole script as if it were a single command — nothing else gets in between. So the read, the arithmetic and the write below happen as one indivisible step:
-- KEYS[1]=bucket ARGV: now, rate, capacity, requested
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or ARGV[3]
local ts = tonumber(b[2]) or ARGV[1]
tokens = math.min(ARGV[3], tokens + (ARGV[1]-ts) * ARGV[2])
local allowed = 0
if tokens >= tonumber(ARGV[4]) then
tokens = tokens - ARGV[4]; allowed = 1
end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', ARGV[1])
redis.call('EXPIRE', KEYS[1], 3600) -- self-cleaning
return {allowed, tokens}One round trip, atomic, self-expiring. The EXPIRE matters at scale: inactive clients' counters vanish on their own, so memory tracks active clients rather than all clients ever seen.
#The latency problem
Even at 0.5 ms, a synchronous Redis call on every request is significant when your p50 API latency (the median: half of requests are faster than this) is 20 ms — and it makes Redis a hard dependency of every request.
Two-tier counting solves it:
Each gateway keeps a LOCAL bucket holding a share of the quota.
1. Serve from the local bucket → no network call at all
2. When local tokens run low, fetch a BATCH from Redis
("give me 50 tokens") in one round trip
3. Return unused tokens periodically / on shutdownNow Redis is hit once per ~50 requests instead of every request. Throughput requirement drops from 3M ops/s to ~60K, and typical added latency drops to roughly zero.
The cost: brief overshoot. A gateway holding 50 unspent tokens can serve them all instantly. With N gateways, worst-case overshoot is N × batch_size. Tune batch size against how strict the limit must be — and say that out loud:
#Sharding
Shard by the rate limit key (user:123:endpoint:/search). Same key always hits the same shard, so no cross-shard coordination is ever needed — a rare and pleasant property.
Use consistent hashing so adding shards doesn't remap everything. Since counters are ephemeral and short-lived, losing some during a rebalance is harmless — briefly, a few clients get a fresh allowance. That tolerance is worth naming: it means you can rebalance aggressively without a migration plan.
#Hot keys
A single very high-volume client (a large enterprise tenant, or an attacker) concentrates on one shard. Mitigations:
- Split that client's counter into ten keys,
key:0…key:9, that land on different shards, each holding a tenth of the quota. A client allowed 10,000 requests a minute becomes ten counters of 1,000, so no single shard takes all of its traffic. - Lean on the local-batch tier, which already absorbs most of the traffic for exactly the clients who send the most — a heavy client drains its local batch fast, but still only touches Redis once per batch.
#6. Failure modes
The question you will be asked: what if Redis is down?
FAIL OPEN FAIL CLOSED
allow all traffic through reject everything
✓ API stays up ✓ downstream protected
✗ no protection during the ✗ total outage caused by
outage — an attack lands the protective componentThe answer is "it depends, and here's on what":
- Abuse prevention → fail open. The limiter exists to protect against a possible attack; failing closed guarantees an outage to prevent a hypothetical one. Bad trade.
- Cost control / hard quota → fail closed. If exceeding the limit means unbounded spend or a contractual breach, rejecting is correct.
- Best of both: degrade to local-only limiting. When Redis is unreachable, keep enforcing per-gateway limits from local state at
global_limit / gateway_count. You lose global precision and keep meaningful protection. This is the answer to give — it refuses the false binary.
Other failures:
| Failure | Handling |
|---|---|
| One Redis shard down | Only keys on that shard degrade to local-only. Blast radius 1/N. |
| Config service down | Gateways use their cached rules. Never make a request wait on the config service — it should only push rule updates in the background. |
| Clock skew across gateways | Token refill uses elapsed time from a monotonic clock (one that only ever counts forward and is never adjusted to match other machines), not absolute timestamps — so gateways disagreeing about the time of day doesn't matter. Worth saying; it's a real trap. |
| Gateway restart | Loses local tokens. Slight under-serving; self-corrects. Preferable to over-serving. |
#7. Details that show experience
- Don't count rejected requests toward the limit. Otherwise a client that hits the limit and keeps retrying keeps using up its own allowance with requests that were refused anyway — so it can never get back under the limit within the window.
- Jitter
Retry-After, or every throttled client retries in the same instant. - Ship in log-only mode first. You will discover your "obviously safe" limit would have broken a major customer. This is the single most practically valuable thing to say.
- Allow-list internal traffic — health checks shouldn't consume quota.
- Emit metrics per rule: allowed, denied, and near-limit clients. Near-limit is the leading indicator that lets you talk to a customer before they're broken.
- Separate read and write limits — writes are more expensive and more abusable.
#8. Follow-ups
- "Global limits across regions?" — cross-region coordination on the hot path costs 100 ms+, which defeats the purpose. Standard answer: per-region limits at 1/N of the global budget, accepting imprecision. If a true global limit is required, it must be an approximate one reconciled asynchronously.
- "How do you handle a distributed attack from many IPs?" — per-IP limiting fails by design here. You need behavioural detection and challenges (CAPTCHA/proof-of-work) at the edge; rate limiting alone is the wrong tool, and saying so is better than pretending otherwise.
- "Can clients cheat?" — anything client-side is advisory. Enforce server-side, and treat client-side limiting purely as a courtesy that helps well-behaved clients stay under.
#Check yourself
What is the hardest constraint on a distributed rate limiter?Show answer
Why token bucket for an API limiter?Show answer
How do you make check-and-decrement atomic in Redis?Show answer
What is two-tier counting?Show answer
What does two-tier counting cost, and when shouldn't you use it?Show answer
How should you shard the counters?Show answer
What should happen when Redis is down?Show answer
Name three details that show experience.Show answer
#What to carry forward
- The algorithm is easy; distributed accuracy, latency and failure are the interview.
- Atomic Lua scripts with EXPIRE make each check one self-cleaning round trip.
- Local token batches cut Redis load about 50× at the cost of bounded overshoot.
- Choose exactness by purpose: approximate for abuse, central for cost control.
- When the store fails, degrade to local limits rather than choosing open or closed.