GuidesDesign a rate limiter
Design a rate limiter: a system design interview walkthrough
10 min read · Updated 1 December 2026
Your API serves 20,000 requests a second. One customer's script has a bug and starts calling you 5,000 times a second in a loop. Your servers slow down, and every other customer waits behind that one script.
You need a rule like "each client gets at most 100 requests a minute", and something that enforces it before the request reaches your servers. That something is a rate limiter.
The rule is easy to state. The interview is about the hard parts: which counting method to use, where the counter lives when you have 30 servers, and what happens when the counter itself goes down. This guide walks through the answer in the order you would give it.
Key takeaways
- Token bucket is the usual default: it allows short bursts but holds the average rate.
- Fixed windows are cheap but let through up to twice the limit at a window boundary.
- Every server must share one counter per client, so use a fast store like Redis with atomic increments.
- Reject with 429 and a Retry-After header so well-behaved clients know when to come back.
- Decide up front whether to fail open or fail closed when the counter store is down.
Step 1: Pin down what you are building
Ask what is being limited, and by what. A good first minute:
- Must have: limit requests per client (by API key, user ID or IP address) to a configurable rate, such as 100 a minute. Reject extra requests with a clear error.
- Nice to have: different limits per plan (free vs paid), per endpoint limits (login is stricter than reading a profile), and headers telling clients how much they have left.
- Out of scope: blocking large network attacks. That needs network-level protection in front of everything, not an application rate limiter.
Then the qualities. The limiter sits in front of every request, so it must add very little delay (about a millisecond) and must not become the reason the API is down. It also needs to be roughly accurate. Letting through 102 requests instead of 100 is fine. Letting through 10,000 is not.
Step 2: Estimate the load
Assume 10 million active clients and 50,000 requests a second at peak.
- Every request needs one counter check, so the counter store must handle 50,000 operations a second, plus headroom.
- Each client needs one small counter: a key, a number and an expiry time. Call it about 100 bytes. 10 million × 100 bytes ≈ 1 GB, which fits in memory on one machine.
- A round trip to an in-memory store in the same data centre usually takes well under a millisecond, so the extra delay per request is small.
What the numbers decide: the data is tiny, but the operation rate is high and every request waits on it. So the counter must live in memory, and a few store nodes split by client key will carry the load with room to spare.
| Quantity | Value | What it means |
|---|---|---|
| Counter checks at peak | ~50,000 / s | One check per request; needs an in-memory store |
| Counter memory | ~1 GB | Fits in RAM; split across a few nodes for headroom |
| Added delay per request | under ~1 ms | Acceptable on the hot path |
Step 3: Pick a counting algorithm
There are five common ways to count. Explain each in a sentence, then pick one.
Token bucket. Picture a bucket that holds 100 tokens and gets 10 new tokens a second, up to its size. Each request takes one token. No token, no request. A client that has been quiet can burst up to 100 requests at once, but over time it cannot beat 10 a second. You store just two numbers per client: tokens left and the last refill time.
Leaky bucket. Requests go into a queue, and the queue is drained at a fixed rate, say 10 a second. If the queue is full, new requests are dropped. The output is perfectly smooth, which suits work that must arrive at a steady pace, but a burst waits in line instead of being served quickly.
Fixed window. Count requests in each calendar minute, and reset to zero when the minute changes. It is one counter per client and very cheap. The flaw: a client can send 100 requests at 12:00:59 and another 100 at 12:01:00. That is 200 requests in two seconds, double the limit.
Sliding window log. Store the timestamp of every request. To decide, drop timestamps older than one minute and count the rest. It is exact, but a client allowed 1,000 requests a minute costs you 1,000 stored timestamps.
Sliding window counter. Keep the count for the current minute and the previous one, then blend them. If you are 15 seconds into this minute, estimate the last 60 seconds as this minute's count plus 75% of last minute's count. It needs two numbers, fixes most of the boundary problem, and is only slightly approximate.
A strong answer picks token bucket for a public API (bursts are normal, and it is cheap) or sliding window counter when the limit must look like "N per minute" to customers. Say why, and mention what you gave up.
| Algorithm | Memory per client | Bursts | Accuracy | Good for |
|---|---|---|---|---|
| Token bucket | 2 numbers | Allowed up to bucket size | Good | Public APIs; the common default |
| Leaky bucket | A queue | Smoothed out | Good | Steady output to a fragile system |
| Fixed window | 1 number | Up to 2× at the boundary | Weak at edges | Simple, coarse limits |
| Sliding window log | 1 timestamp per request | Not allowed | Exact | Low limits where precision matters |
| Sliding window counter | 2 numbers | Mostly prevented | Close approximation | Per-minute limits at scale |
Step 4: Where the limiter sits
You have two main choices.
In the API gateway (the single front door that every request passes through before reaching your services). One place enforces every limit, services stay simple, and bad traffic is dropped before it costs you anything. Most designs start here.
Inside each service. The service knows things the gateway does not, like "this user is exporting a 2 GB report, so count it as 50 requests". This is useful for expensive operations, but every team now has to build and run the limiter correctly.
A common answer is both: coarse per-client limits at the gateway, and a few targeted limits inside the services that need them.
Limit rules (which plan gets which rate, which endpoints are stricter) belong in configuration that the gateway loads and caches, not in code. Changing a limit should not need a deploy.
Step 5: A shared counter in Redis
Here's the problem. You run 30 gateway servers behind a load balancer. If each one counts on its own, a client whose requests are spread across all 30 could send 30 × 100 = 3,000 requests a minute before any single server says no.
So the count must live in one shared place. An in-memory store like Redis fits: it is fast, and it supports atomic operations, meaning a single operation that reads and changes a value with no chance of another request slipping in between.
That second part matters. A naive "read the count, add one, write it back" breaks when two gateways read 99 at the same moment. Both write 100 and both let the request through. Instead, use one atomic increment:
-- fixed window: one key per client per minuteINCR rl:{client}:{minute}EXPIRE rl:{client}:{minute} 60-- if the returned count is over 100, rejectFor a token bucket or sliding window, the check needs several steps (read, refill, compare, write). Put them in a small Lua script, which Redis runs as one uninterrupted step, so the whole check stays atomic.
Shard the counters across a few Redis nodes by client key. One client's counter always lives on one node, so no single check ever touches two machines.
Check the counter
A request arrives at the gateway. The gateway looks up this client's limit in its cached rules, then sends one atomic increment to Redis and gets back the new count.
Step 6: Telling the client what happened
A rejected client should know it was rate limited, not that your server broke. Use the standard status code 429 Too Many Requests and add a Retry-After header saying how many seconds to wait:
HTTP/1.1 429 Too Many RequestsRetry-After: 12X-RateLimit-Limit: 100X-RateLimit-Remaining: 0429 and Retry-After are standard HTTP. The X-RateLimit-* headers are a widely used convention rather than a standard, but clients find them useful, so many APIs send them on every response, not just rejected ones.
Good clients back off and retry after the wait. Mention that retries should add a little random delay (jitter), or every rejected client retries at the same second and you get another spike.
Step 7: What can go wrong
- Redis is down or slow. You must choose. Fail open lets every request through: the API stays up, but nothing is limited for a while. Fail closed rejects everything: safe for the backend, but a limiter outage takes the whole API down. Most public APIs fail open, with a timeout of a few milliseconds on the Redis call. A login endpoint, where the limit protects against password guessing, may fail closed.
- One hot client. A single huge client hammers one Redis node. Keep a small in-memory counter on each gateway as a first filter, and only check Redis for clients near their limit.
- Clock differences. Gateways disagree on the time by a few milliseconds, so window keys can be off at the edges. Use the Redis server's time inside the script, or accept the small error.
- Multiple regions. A client can hit your US and EU regions at once. A single global counter means a cross-ocean round trip on every request, around 100 ms, which is too slow. The usual answer is a counter per region, each with a share of the limit (say 50 each), or local counters that sync to a global total every second or so. Either way the global limit becomes approximate. Say that this is a fair trade.
Trade-offs to say out loud
- Token bucket vs sliding window: token bucket allows friendly bursts, sliding window matches "N per minute" more closely. Both cost two numbers per client.
- Gateway vs service: the gateway is one place to manage limits; services can judge expensive work better.
- Shared counter vs local counters: a shared Redis counter is accurate across servers, at the cost of a network hop on every request.
- Fail open vs fail closed: availability of the API vs protection of the backend while the limiter is down.
- Exact vs approximate across regions: exact global counts are too slow to check; per-region shares are fast and slightly loose.
For how a shared store splits keys across nodes, see consistent hashing.
Questions people ask
Which rate limiting algorithm is best?
There is no single best one. Token bucket is the most common default because it is cheap and allows short bursts while holding the average rate. Use a sliding window counter when customers expect a strict per-minute limit, and a leaky bucket when the output must be perfectly steady.
What is the difference between token bucket and leaky bucket?
A token bucket lets a client spend saved-up tokens in a burst, so requests are served immediately as long as tokens remain. A leaky bucket puts requests in a queue and releases them at a fixed rate, so bursts are smoothed out by waiting. One controls the average, the other controls the output pace.
Why use Redis for a rate limiter?
All your servers need to share one count per client, and the check happens on every request. Redis keeps data in memory, answers in well under a millisecond on a local network, and has atomic increments and scripts, so two servers can never both read the same old count.
What HTTP status code should a rate limiter return?
Return 429 Too Many Requests. Add a Retry-After header with the number of seconds the client should wait, so well-behaved clients can back off instead of retrying straight away.
Should a rate limiter fail open or fail closed?
Most public APIs fail open, so a limiter outage does not take the whole API down, and keep a small local limit on each server as a backstop. Fail closed only where the limit is a security control, such as limiting login attempts.