Design a Rate Limiter
Ch. 5 Building Blocks System designThe problem
A rate limiter caps how many requests a client, IP or key may send in a period of time.
Requests over the cap are rejected, usually with 429 Too Many Requests.
Why bother? It shields your APIs from denial-of-service bursts, keeps paid third-party calls within the budget you are billed for, and stops a single misbehaving client from starving everyone else of server time.
Today you will build one: pick a home for it, compare the classic algorithms, wire the counters to Redis, and make it correct across many machines.
Requirements
Functional — what it must do
- Throttle per API key, falling back to the caller's IP address when a request has no key. One key's traffic never affects another's.
- A rule is a number of requests over a window of time, per action: for example 5 login attempts per 60 seconds per key.
- A request inside the limit is forwarded to the API servers unchanged. A request over the limit is never forwarded.
- A rejected request gets <code>429 Too Many Requests</code> with three headers: <code>X-RateLimit-Limit</code> (the cap), <code>X-RateLimit-Remaining</code> (what is left in this window) and <code>Retry-After</code> (seconds until the window resets).
- Allowed responses carry the same three headers, so a client can slow down before it is ever cut off.
- Rules are configuration, not code: an edited rule applies to new requests within a few seconds, with no redeploy.
Non-functional — how well it must do it
- Latency: the check adds at most 5 ms at the 99th percentile — about 1 ms to look up the rule locally and 1–4 ms for one round trip to the counter store.
- Availability: 99.9%. If the counter store is unreachable the limiter fails open (lets traffic through and raises an alert) instead of taking the whole API down with it.
- Correctness: taken together, all limiter replicas let a key pass no more than a few percent over its limit, even when two replicas check the same key at the same instant.
- Memory: proportional to the number of active keys (about 100 bytes each), never to the number of requests.
- Observability: allowed and rejected counts per rule are exported as metrics, so a mis-set limit is visible within minutes.
Scale — how much it must take
- 20,000 requests per second at peak, from about 200,000 keys active in any minute, arriving through several limiter replicas at once.
Assumptions — the numbers this design is sized for
A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.
Takeaways
- Fix the scale before the algorithm: 20,000 requests a second is 20,000 counter writes a second, which one Redis node absorbs with room to spare.
- Enforce limits on the server side (middleware or gateway) — never trust the client.
- Token bucket allows bursts, leaky bucket smooths them out; pick by the traffic shape you want.
- Fixed windows are cheap but leak at boundaries; sliding windows are exact but cost memory; the weighted counter splits the difference.
- Keep counters in an in-memory store like Redis, with atomic INCR/EXPIRE — never in a relational database.
- Make the check-and-increment atomic (Lua / atomic INCR) and share one counter across all replicas.
- A 429 is only useful with Limit / Remaining / Retry-After headers, so clients can back off politely.
Where to put it
The limiter is a gate on the request path. Where that gate lives decides whether anyone can sneak past it.
- 1No limit today
Right now every request goes straight from the client to the API servers. A single client can send as many as it wants.
- 2A gate in the middle
We insert a rate limiter between the client and the servers. It checks every request first, and only forwards the ones inside the limit.
- 3Do not trust the client
You could ship the limiter in the client itself, but clients can be forged, modified or simply ignored by bad actors. Enforcement has to happen where you control the code: the server side.
- 4…or an API gateway
In a microservice setup the limiter often lives in the API gateway, which already does authentication, TLS termination and routing. Same job, different home. Pick the one your team already runs.
Token bucket
A bucket of tokens that refills with time. Each request pays one token to pass — no token, no ride. This is the algorithm most public APIs use.
- 1The bucket
A token bucket holds at most 4 tokens, and a refiller adds 2 every second. Each request that passes takes one token out.
- 2A request arrives
A request rolls in along the lane and stops at the bucket. To pass, it has to pay one token.
- 3One request, one token
One request in, one token out. The bucket is down to three.
- 4Two more follow
Two more requests follow straight away and take two more tokens: three requests in, a single token left.
- 5Empty means 429
The bucket is empty and the refiller has not caught up, so the next two requests are rejected with 429.
- 6It refills
Two seconds later the refiller has added four tokens again, capped at capacity. Traffic flows once more. That built-in burst allowance is the bucket's nicest property.
Leaky bucket
Instead of paying a token, requests wait in a line inside the bucket and leak out at a steady pace. Smooth output, no matter how spiky the input.
- 1A FIFO queue
The leaky bucket queues requests instead of letting them through. The queue holds at most 4, and a worker drains it at a fixed pace, one request per tick.
- 2Burst lands in the queue
A burst arrives faster than the worker can drain it. Three of the four slots fill up at once, and the requests wait their turn instead of all hitting the server together.
- 3Full queue, one dropped
The queue is full, so the next request cannot even be enqueued. It is dropped with a 429 instead of being processed.
- 4Steady outflow
Meanwhile the worker keeps pulling one request out per tick. The outflow is perfectly smooth, no matter how spiky the inflow was. That steadiness is the point — and the price: waiting requests age in the queue.
Fixed window counter
The simplest counter: chop time into fixed windows and count the requests that fall in each. Cheap — and leaky at the edges.
- 1Count per second
The simplest counter: divide time into one-second windows, count requests in each, and reject the ones past 3 per window.
- 2Full window
This window is full at 3, so any further request in the same second gets a 429.
- 3The boundary spike
Here is the flaw. A client can send 3 in the last part of window one and another 3 in the first part of window two: 6 requests in a fraction of a second — double the limit. Counters reset on a wall-clock boundary, so the edges of two windows are the soft spot.
Sliding window log
Keep the timestamp of every allowed request and look back exactly 60 seconds from now. Exact — and hungry for memory.
- 1Log every timestamp
Instead of a counter we keep a log of the timestamps of allowed requests. The limit is 2 per minute. The log is empty, so the first request is accepted and stamped 1:00:01.
- 2Second one fits
A request at 1:00:30 is logged. Two entries, exactly at the limit, so it is accepted.
- 3Third one is rejected
At 1:00:50 the log would hold three entries — one too many — so the request is rejected. Note it does not get a slot; the log keeps only what was allowed.
- 4The window slides
Time moves on. When a request arrives at 1:01:40, entries older than one minute drop off: 1:00:01 and 1:00:30 are evicted, leaving room. The new request is accepted. Because the window is measured relative to now, the boundary-spike trick cannot work here.
- 5Accurate but hungry
Sliding-window log is the most accurate algorithm of the bunch — the limit can never be exceeded in any rolling minute. The cost is memory: one entry per allowed request, for every client. At interview scale that is a lot of entries.
Sliding window counter
Two integers instead of a log: the count for this minute and the count for the last one, blended by how far the rolling window overlaps each.
- 1Two counters, one estimate
A middle ground: keep a count for the current minute and one for the previous. Currently: 3 this minute, 5 last minute, limit 7.
- 2Weight the overlap
We are 30% into the current minute, so the previous minute still overlaps 70% of the rolling window. Estimate: 3 + 5 × 0.70 = 6.5, round to 6.
- 3Under the limit
6 is under the limit of 7, so the request goes through. One more and we are at the cap. This approximates the sliding log with two integers — memory-light and close enough: real-world measurements show the error stays in the ten-thousandths of requests.
Counters in Redis
Every replica needs the same number. An in-memory store with an atomic increment gives it to them in about a millisecond.
- 1Not the database
Every request must read and bump a counter, so the store has to be fast and in memory. A relational database is far too slow for the hot path. Redis is the usual choice: two commands do the whole job.
- 2INCR + EXPIRE
INCR bumps the client's counter atomically and returns the new value. EXPIRE tags the key with a time-to-live, so a counter that nobody touches simply vanishes — no cleanup job needed.
- 3The decision
New counter value is 3, under the limit of 5, so the request is forwarded to the API servers. Had it been 6, the limiter would have answered the client with a 429 before anything reached the backend.
- 4Sized for the peak
Check it against the assumptions: 20,000 requests a second means 20,000 INCRs a second, and one Redis node takes about 100,000. A single primary with a replica has five times the headroom it needs, and the whole counter set is about 20 MB.
Rules & the 429 response
Limits are data, and a rejection should tell the client exactly what happened and when to come back.
- 1Rules are data
Limits are not hard-coded; they are configuration. A rule says: for the auth domain, login actions, at most 5 per minute. Change the file, the workers reload it into the cache, done — no redeploy.
- 2Tell the client
When a request is rejected, a bare 429 is not useful. The response carries the limit, how many requests are left in this window, and how many seconds to wait before retrying — so well-behaved clients can back off on their own.
- 3Drop or defer
Depending on the endpoint, over-limit requests are simply dropped — or pushed to a queue to be replayed later, which suits things like orders that must not be lost.
Correct across replicas
Two limiters with two separate counters each let 5 through — 10 in total. The fix is one shared counter, updated atomically.
- 1Two replicas, two views
Scale the limiter out and each replica keeps its own counter in memory. Client one hits replica A, client two hits replica B — each replica only knows half the traffic, so together they allow twice the limit.
- 2The race condition
Even on one machine: two threads read the counter, both see 3, both conclude 4 is under the limit, and both write 4. Two requests got in, the counter moved by one. The read-check-write must be atomic.
- 3One shared counter
The fix is a single source of truth. Every replica bumps the same counter in Redis, and Redis executes INCR atomically. Add a Lua script and the check-and-increment becomes one indivisible operation, so no two requests can ever see the same value.
End to end
Everything above in one run: a request comes in from the client, the limiter checks the cached rule and bumps the counter in Redis, and its budget drains until the sixth request is turned away.
- 1The whole system
Everything in one picture. Requests arrive from the client. The limiter — our bucket, holding the 5 requests this key may spend this minute — stands in front of the API servers. The rule it applies is cached beside it, and every count it makes is kept in Redis.
- 2Request arrives
A request leaves the client, rolls along the lane and stops at the limiter. The limiter looks up the rule for this action in its local cache — no disk, no network hop: 5 per minute for this key.
- 3Check the counter
The limiter atomically bumps the shared counter in Redis. It reads 2, so this request is number 2 of the minute — under the limit of 5. One token leaves the bucket with the request.
- 4Allowed, with headers
The request is forwarded to the API servers, and the response goes back to the client with the rate-limit headers: 3 of 5 remaining this minute.
- 5Burst gets a 429
The client pushes on. Requests 3, 4 and 5 go through and empty the bucket, but the sixth bumps the counter past the limit — the limiter rejects it on the spot with a 429 and a Retry-After header, and the backend never sees it. The limit held exactly.
In the wild
The same three pieces — a gate on the request path, per-key rules, a shared counter — run at internet scale. Here is who runs which piece.
- 1These patterns run the internet
Everything you just built is not interview theory. The exact same pieces — a gate on the request path, per-key rules, a shared counter — show up in the systems that carry a huge share of the web's traffic. Let's match the diagram to the companies.
- 2The gate, at the edge
Cloudflare stops abusive traffic before it ever reaches origin servers: rate limiting runs at the network edge, in front of the web, for millions of domains. That is your 'where to put it' answer, executed at planetary scale — the limiter is the front door, not a library call deep inside the app.
- 3Published per-key quotas
Google, Twitter, Stripe and Shopify all publish limits to their API users — requests per minute or per token, with a 429 and a Retry-After when you cross them. That is your 'rules' box made public: a table of per-key quotas that a gateway enforces on every call.
- 4The shared counter, at scale
ClassDojo solved the 'count correctly across many machines' problem by sliding a per-user window in Redis sorted sets — exactly your Redis counter and sliding-log ideas, in production. The store is the memory of the limiter: fast, shared, and atomic.
- 5Open-sourced and gateway-built
Lyft built a rate limiter for its own platform and open-sourced it, and AWS bakes throttling into API Gateway so every API gets per-key and per-route ceilings without custom code. The design is now a standard layer of infrastructure — you rarely build it from scratch, you configure it.