“100 requests per minute” sounds like one rule. It is at least five different rules, and they disagree about what happens at 00:59. This lesson draws each algorithm, shows the exact moment the cheap one breaks, and then makes it work across a fleet of servers.
GET then INCR is a race condition; the fix is one atomic operation in a shared store, not a lock.Outcomes
A rate limiter caps how many requests a client may make in a period. It exists for three reasons, and they are worth separating because they imply different limits:
How to read: The limiter is in front of everything expensive. A rejected request costs one counter lookup, never a database query. That placement is the entire point.
A bucket holds up to N tokens and is refilled at a steady rate. Each request removes one token. No token, no service. That is the whole algorithm, and it is the default choice at Amazon and Stripe.
Run it: capacity 5, refill 1 token per second, bucket starts full. One burst, replayed on a loop — watch the spotlight.
token bucket · cap 5 · refill 1/s
Try it: the bucket refills in real time. Press Send 20 at once to spend a full bucket in one burst, then watch it recover — and notice that the long-run rate settles at the refill rate no matter how hard you press.
How many buckets? One per thing you want to isolate: per user ID for authenticated APIs, per IP for anonymous ones, per endpoint when some operations are far more expensive, or a global bucket to protect a single downstream dependency. Real systems run several at once, and the request must pass all of them.
The other family counts requests inside a time window. The entire design space comes down to how you define the window.
Keep one counter per clock-aligned minute. INCR it, reject above the limit, let it expire. Two integers of memory and one operation per request — it is the cheapest thing that works. Here is how it fails:
Run it: limit 5 per minute, 10 requests across one clock boundary. Same failure, counted out loud.
fixed window · limit 5/min
How to read: The limit is 5 requests per minute, and both windows respect it — each counter reads exactly 5, neither is ever exceeded. Now look at the red box.
Store a timestamp for every request in a sorted set. On each new request, drop everything older than 60 seconds and count what remains. The window now genuinely means “the last 60 seconds,” so the boundary leak is impossible and the limit is never exceeded in any rolling span.
The cost is memory, and it is worse than it sounds: you store timestamps for rejected requests too, so the client hammering you hardest consumes the most memory. At 1 million users and a 1,000/hour limit that is potentially a billion timestamps.
Run it: limit 5 per rolling 60 seconds. Six requests, then the slow recovery — watch old timestamps die.
sliding window log · limit 5 / 60s
Keep two fixed-window counters and weight the previous one by how much of it still falls inside the rolling window. One number instead of a list of timestamps, and the boundary leak mostly disappears.
Run it: limit 100 per minute, previous minute saw 84. Two decisions, arithmetic shown.
sliding window counter · limit 100/min
Try it: drag seconds into the minute toward zero with a busy previous minute, and watch the two algorithms disagree. The fixed window keeps saying “allowed” while the real last-60-seconds figure is over the limit.
Requests go into a FIFO queue and are processed at a constant rate. Overflow is dropped. Unlike token bucket it never bursts — outflow is perfectly smooth. Use it when the thing you are protecting has a hard fixed throughput (a legacy service, a payment processor with a contractual rate). Shopify uses it for exactly that. The cost is that a burst fills the queue, so later legitimate requests get rejected while older queued ones are still being drained.
Run it: queue holds 4, worker takes 1 every 2 seconds. Same burst as the token-bucket trace above — opposite outcome.
leaking bucket · queue 4 · outflow 1 / 2s
| Algorithm | Memory per client | Allows bursts? | The flaw | Reach for it when |
|---|---|---|---|---|
| Token bucket | 2 numbers | Yes, up to capacity | Two knobs to tune and they interact | Default. Amazon, Stripe |
| Leaking bucket | queue | No — perfectly smooth | Queued old requests starve fresh ones | Downstream has a hard fixed rate. Shopify |
| Fixed window | 1 number | Accidentally, at boundaries | Admits up to 2× across a boundary | Cheapest option; limits are soft |
| Sliding window log | 1 timestamp per request | No | Memory, including for rejected requests | The limit must be exact |
| Sliding window counter | 2 numbers | Slightly | Approximates; assumes even distribution | Best general trade. Cloudflare |
A bare 429 is a bad citizen: the client has no idea how long to wait, so it retries immediately and makes things worse. Return the state of the limit with every response, not just the rejections.
# On a successful request — the client can self-pace before it is ever blocked.
HTTP/1.1 200 OK
X-Ratelimit-Limit: 100 requests allowed per window
X-Ratelimit-Remaining: 36 left in the current window
X-Ratelimit-Reset: 24 seconds until the window resets
# On rejection — Retry-After is the one that actually changes client behaviour.
HTTP/1.1 429 Too Many Requests
X-Ratelimit-Limit: 100
X-Ratelimit-Remaining: 0
Retry-After: 24
Content-Type: application/json
{"error": "rate_limit_exceeded", "retry_after_seconds": 24}
Rules themselves belong in configuration, not in code — a YAML file or a config service that workers reload, so changing a limit does not require a deploy:
- domain: auth
descriptors:
- key: login_attempt
value: by_ip
rate_limit: { unit: minute, requests_per_unit: 5 } strict: credential stuffing
- domain: messaging
descriptors:
- key: send_message
value: by_user
rate_limit: { unit: day, requests_per_unit: 1000 }
- domain: search
descriptors:
- key: query
value: by_user
rate_limit: { unit: second, requests_per_unit: 20 } loose: cheap and read-only
429) or hold it and serve it later. Reject anything user-facing — a fast failure the client can retry beats a request that silently waits 30 seconds. Queue only non-urgent work where ordering and completion matter more than latency, such as a batch import.One limiter on one box is easy. Ten limiter instances sharing one limit introduces two genuine distributed-systems problems.
The obvious implementation is read, add one, write back. With concurrent requests that is wrong:
How to read: Two requests, two servers, one counter. Step through it. Both read before either writes, so one increment is lost and the limit is quietly exceeded.
INCR is atomic by itself — it returns the new value, so read and write are a single step.ZREMRANGEBYSCORE + ZCARD + ZADD inside one script does the whole thing.-- KEYS[1] = "ratelimit:user:42:1699891260" (counter key, window-aligned)
-- ARGV[1] = limit, ARGV[2] = window seconds
local current = redis.call('INCR', KEYS[1]) -- atomic: read and write in one step
if current == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[2]) -- first hit in this window: set the TTL
end -- the TTL is what garbage-collects old windows
if current > tonumber(ARGV[1]) then
return 0 -- reject
end
return ARGV[1] - current -- allow, and report what's left
-- KEYS[1] = "ratelimit:user:42" (a sorted set of request timestamps)
-- ARGV[1] = now_ms, ARGV[2] = window_ms, ARGV[3] = limit
local cutoff = ARGV[1] - ARGV[2]
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, cutoff) -- drop anything older than the window
local count = redis.call('ZCARD', KEYS[1])
if count < tonumber(ARGV[3]) then
redis.call('ZADD', KEYS[1], ARGV[1], ARGV[1]) -- record only requests we allow,
redis.call('EXPIRE', KEYS[1], math.ceil(ARGV[2]/1000)) -- which bounds the memory problem
return 1
end
return 0
Ten limiter instances must agree on the count. Two approaches, and only one survives contact with autoscaling:
INCR and EXPIRE are exactly the primitives needed, and it answers in about a millisecond.At global scale there is one more wrinkle. If your limiters run on edge servers in 100 cities, a synchronous call back to one central Redis adds the cross-ocean round trip from Day 3 — up to 150 ms on every request, to enforce a limit. Nobody accepts that. The answer is regional counters with eventual consistency: each region enforces locally against its own share and reconciles asynchronously. You over-admit slightly during the reconciliation lag. That is the price of not putting an ocean on the hot path, and it is the right trade.
You have put a dependency in front of every request. If Redis is unreachable, the middleware has to decide something, and there are only two options:
Also give the Redis call a tight timeout — a few milliseconds. A limiter that blocks for 2 seconds waiting on a sick Redis has become the outage it was supposed to prevent, and it does so on every request simultaneously.
Rate limiter questions in real loops are mostly operational: something is being limited that should not be, or the limiter itself has become the problem.
X-Forwarded-For — and you must only trust the hop your own proxy appended, because clients can forge the rest of that header. And IPv6 should be bucketed by prefix (commonly /64), since a single customer may be handed trillions of addresses.429s. Clients are retrying immediately and your error rate is climbing during every brief spike. What do you change on both sides?Retry-After plus the limit/remaining/reset headers, and have clients back off exponentially with jitter503 instead so clients treat it as a server errorRetry-After is the one header that changes behaviour, and X-RateLimit-Limit / Remaining / Reset on successful responses lets well-behaved clients self-pace before they are ever blocked. Client side: exponential backoff with jitter (Day 11), because without jitter every rejected client retries at the same instant and you get a synchronised thundering herd. Returning 503 is actively harmful: it tells the client your server is broken, which triggers retry logic and may trip their circuit breaker and take you out of their rotation entirely. 429 means “you, slow down”, which is the truth.(user, window) holding only the count; look the limit up from a cached config keyed on the user's current tier; compare. Now an upgrade is a config read that takes effect on the next request, and changing the free tier is a config push with no deploy and no data touched. Worth adding out loud: decide what an upgrade means mid-window — does the user get the new allowance immediately, or at the next window? Both are defensible; the bug is not having decided.This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.
Retry-After or clients will hammer you.What breaks next. This design leans on one shared Redis. Scale it and you need several — which means deciding which counter lives on which node. The obvious answer, hash(key) % N, works perfectly until you add the fourth node, at which point almost every counter moves and every limit resets at once. Day 6 is about why, and the fix that every distributed store uses.
Source: System Design Interview, Ch. 4 — Design a rate limiter (pp. 1–20). Algorithm diagrams, the Lua scripts, the response-header contract and the regional-counter discussion are standard practice added here to make the trade-offs concrete.