Design a Rate Limiter
How to design a distributed API rate limiter: algorithms, shared atomic counters, behaviour when the store fails, and what interviewers ask about it.
On this page
A rate limiter sits in front of an API and rejects requests from clients that send more than they are allowed to. It protects the backend from overload and abuse, and it stops one client from using the capacity that other clients need.
The question is popular because the service is small but touches several hard topics: counters shared by many servers, atomic updates, race conditions, clocks, and deciding what to do when the limiter's own dependency fails. Rate Limiting explains the algorithms on their own; this case study builds the whole service, following A Framework for Any Design.
Clarify the problem
"Design a rate limiter" can mean a class in one process or a company-wide service, so first find out which.
Design a rate limiter for our public API.
Does the limiter run inside one service, or is it shared by many gateway servers? And do we limit by API key, account or IP address, with different limits for different plans?
It is shared, because every request passes through one of our API gateways. We limit per API key for logged-in traffic and per IP address for anonymous traffic. Plans have different limits, and the login endpoint has its own strict limit.
How many requests a day do we handle, and how many distinct clients are there?
About a billion requests a day, from around 10 million API keys and a similar number of IP addresses.
Then I will assume the check adds under 2 ms at p99, a limiter outage must not take the API down, and limits may be a few percent loose but never ten times loose. Billing and dashboards are out of scope.
- Functional: limit requests per API key, per IP address and per account, with rules that vary by endpoint and plan. Reject excess requests with status
429and a retry time. Allow operators to change rules without a deploy. - Non-functional: the check adds under 2 ms at p99. The API stays up if the limiter's store is down. Counts are shared across gateways and accurate to within a few percent. Rule changes take effect within about 10 seconds.
- Out of scope: billing, usage dashboards and bot detection.
Estimate the scale
A day has 86,400 seconds. The estimate assumes that peak traffic is three times the average and that each request is checked against two rules, one for its API key and one for its IP address.
How many counter operations per second must the shared store handle at peak?
- 1 billion API requests a day
- Peak is 3x the average
- Each request is checked against 2 rules, one store operation each
Show the working
- Average: 109 ÷ 86,400 s ≈ 11,600, rounded up to 12,000 a second
- Peak: 12,000 × 3 = 36,000 requests a second
- Store operations: 36,000 × 2 = 72,000 a second
Estimate 72 thousand/s (anything from 30 thousand/s to 200 thousand/s is a good answer)
An in-memory node handles about 100,000 simple operations a second, but each check runs a small script, so plan for about 50,000 a node. That needs 2 nodes at minimum, and 4 shards leave room for failures.
Sketch three interfaces before reading on: what clients see, what the gateway asks the counter store, and how operators change rules.
Compare with a model answer
Clients see a 429 response with a Retry-After header, and headers on every response that show how much of the limit is left. The gateway makes one atomic "take a token" call to the counter store for each rule. Operators write rules to a config store, and the gateways reload them.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
Every response from the API:
X-RateLimit-Limit: 100 bucket size for the tightest rule
X-RateLimit-Remaining: 36 tokens left after this request
Rejected request:
429 Too Many Requests
Retry-After: 1 seconds until a token is available
body: { "error": "rate_limited", "rule": "key-free-plan", "retry_after_s": 1 }
Gateway to counter store, one atomic call per rule:
take(key, capacity, refill_per_sec, cost = 1)
-> { allowed, remaining, retry_after_ms }
Operators:
PUT /admin/rules/{rule_id} body: the rule (see the data model)
400 if the rule is invalid; gateways pick up changes within 10 sThe API decision worth arguing is the status code. A 429 means that this client sent too much, while a 503 means that the service is overloaded. The limiter should return 429, so that a well-behaved client reads Retry-After and slows down. Keep 503 for load shedding, because a client that reads a limit as a server fault retries at the wrong times.
List the records the system keeps, how big each one is, and how often it is read and written. Pick a kind of store for each.
Compare with a model answer
Rules are a few hundred records that are read constantly and changed rarely, so every gateway keeps them in memory. Counters are 20 million small records that are written on almost every request, so they belong in an in-memory key-value store.
Model the data
rule
rule_id "key-free-plan"
match endpoint pattern and plan, e.g. "/v1/*", plan = free
key_by api_key | ip | account
capacity 100 burst size
refill_per_sec 10 long-run rate
on_store_down open | local | closed
counter key = "rl:{rule_id}:{subject}" e.g. "rl:key-free-plan:k_8f3a"
tokens float, 8 bytes
last_refill_ms integer, 8 bytes
TTL capacity / refill_per_sec = 100 / 10 = 10 sThe rules are a few hundred records in any durable config store, and each gateway polls them into memory every 10 seconds.
The counters are updated on almost every request and must answer in about half a millisecond. That calls for an in-memory key-value store, such as Redis, that runs small scripts atomically and expires keys. Losing a counter only gives one client a fresh, full bucket, so durability matters little.
Twenty million buckets of about 100 bytes each come to 2 GB, so memory does not limit the design. The TTL frees idle buckets without changing any answer, because a bucket idle for 10 seconds is full again and a missing key is treated as full.
Sketch where the check happens, where the counters and rules live, and what a rejected request touches.
Compare with a model answer
The limiter is a library inside each gateway, so the only extra hop is the call to the counter store. A rejected request never reaches the backend services.
High-level design
The limiter runs as a library inside each API gateway. Making it a separate service would add a network hop to every request and a second fleet of servers to operate. The counter store has 4 shards by key, each with a replica.
request and replyasynchronous message
- tokens
- 37
- allowed
- 0
- rejected
- 0
1A free-plan client with key
k_8f3acallsGET /v1/orders. Its bucket holds 37 of 100 tokens and refills 10 a second.- tokens
- 36
- allowed
- 1
- rejected
- 0
2The gateway makes one atomic call to the shard that owns
rl:key-free-plan:k_8f3a. The shard refills the bucket and takes one token in about 0.5 ms.- tokens
- 0
- allowed
- 38
- rejected
- 0
3A buggy client loop then sends 80 requests in 0.1 seconds. The bucket holds 36 tokens and refills 1 more in that time, so 37 of the 80 requests pass and the bucket reaches zero. Allowed requests are forwarded to the backend.
- tokens
- 0
- allowed
- 38
- rejected
- 43
4The other 80 − 37 = 43 requests receive
429withRetry-After: 1, and the backend never sees them.5The shard that holds this key dies and the call times out after 5 ms. The rule says
on_store_down: local, so the gateway checks an in-memory bucket that holds its share of the limit.6Requests that fit within the local limit pass, so the API stays available and is still roughly limited while the shard's replica is promoted.
Deep dives
Interviewers usually push on the algorithm, the shared counter, store failure and the identity a limit applies to.
Choosing the algorithm for each rule
The problem is to count requests so that the limit is enforced cheaply and without surprising clients. Different rules protect different things, so the choice is made per rule.
A token bucket gives each client a bucket that holds a fixed number of tokens and refills at a steady rate. Each request removes one token, and a request that finds the bucket empty is rejected. The state is two numbers per key, and it allows a burst as large as the bucket while holding the long-run rate at the refill rate. Its weakness is that a full bucket lets a whole burst through at once, which a fragile backend may not tolerate.
A sliding window log stores the timestamp of every accepted request and counts those inside the last window. The count is exact, but a limit of 5,000 requests an hour needs up to 5,000 timestamps per client.
A fixed window counter keeps one integer per client per window and resets it when the window ends. It is the cheapest option, but a client can send the full limit at the end of one window and again at the start of the next, which is up to twice the limit in a short time.
A sliding window counter removes most of that error by keeping the counts of the current and previous window. With a 60-second window and a request 15 seconds in, the estimate is the current count plus 75 percent of the previous count. It stores two integers and is accurate to within a few percent.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Token bucket Usual default | It allows short bursts and holds the long-run rate. | A full bucket lets a whole burst through at once. | General per-key and per-IP limits. This is my default here. |
| Sliding window log | The count over the window is exact. | It stores one timestamp per request. | Small limits that must be exact, such as login attempts. |
| Sliding window counter | It stores two integers and avoids most of the edge error. | The count is an estimate. | Large limits where bursts should not be allowed. |
I would use a token bucket for the general per-key and per-IP rules, because bursts from real clients are normal and the backend has headroom for them. Login uses a sliding window log, because its limit is tiny and has to be exact. A fixed window counter is enough for coarse daily quotas.
Sharing counters across gateways with atomic updates
If each of 20 gateways counted on its own, a client whose requests were spread across all of them could send up to twenty times its limit. So the count for each key lives in one place, on the shard chosen by consistent hashing of the key, which means that adding a shard moves only a small share of the keys. The danger is to split the check from the update, as the next tracer shows.
- tokens
- 1
- allowed
- 0
1The bucket for
k_8f3aholds 1 token. Two requests from this key reach gateways A and B in the same millisecond.- tokens
- 1
- allowed
- 0
2In the naive version, both gateways read the bucket before either has written back, so each sees 1 token and decides to allow its request.
- tokens
- 0
- allowed
- 2
3Both gateways write
tokens = 0and both requests pass, so two requests used one token.- tokens
- 0
- allowed
- 1
4The fix is to run refill, check and take as one script that the shard finishes before starting the next. A's script takes the token and B's finds 0 tokens, so one token allows one request without locks.
take(key, capacity, rate, cost):
now = store's own clock, in ms
tokens, last = read key (missing key: tokens = capacity, last = now)
tokens = min(capacity, tokens + (now - last) / 1000 * rate)
if tokens >= cost:
tokens = tokens - cost
allowed = true
else:
allowed = false
write key = (tokens, now), expire after capacity / rate seconds
return allowed, floor(tokens), time until tokens >= costTwo details show that you have built this before.
- Use the store's clock, not the gateway's. Gateway clocks drift apart, and if gateway A's clock is behind gateway B's, then
now - lastcan become negative and the refill calculation breaks. - Never retry a take that timed out. The store may have taken the token before the reply was lost, so a retry would charge the client twice. Treat a timeout as "store unavailable" and apply the failure behaviour below.
Failing open, failing closed, or limiting locally
The problem is that the limiter now depends on the counter store, and the gateway must decide what to do when the store does not answer within its 5 ms timeout. There are three choices, and the right one depends on the endpoint.
Failing open means allowing every request while the store is down. A limiter outage then never becomes an API outage, but there is no protection until the store returns, and one abusive client can hurt everyone in the meantime.
Falling back to local limits means that each gateway keeps an in-memory bucket per key and enforces its own share of the limit. With 20 gateways and a rule that refills 10 tokens a second, each gateway allows 10 ÷ 20 = 0.5 a second for that key, so a client spread evenly across all gateways still gets 20 × 0.5 = 10 a second. The weakness is that a client routed to only one gateway gets just 0.5 a second.
Failing closed means rejecting requests while the store is down. No request ever skips the limit, but a store outage rejects every request on that endpoint.
I would use local limits for the general API and fail closed for login, which is why each rule carries its own on_store_down setting.
Combining per-IP, per-key and per-account rules
A single request can match several rules at once, for example one for its IP address, one for its API key and one for the endpoint. The gateway allows the request only if every rule allows it, and returns the longest Retry-After among the rules that rejected it. It checks the IP rule first, so a flood is rejected before it costs a second store call.
An IP address is a poor identity on its own, because an office or a mobile carrier can put thousands of users behind one address. Use the IP address for anonymous traffic and floods, and switch to the key or account as soon as it is known. The login endpoint needs two limits: one per IP address, which stops one attacker trying many accounts, and one per target account, which stops many addresses trying one account.
Bottlenecks and failures
At 10 times the traffic, the peak is 360,000 requests a second and the store sees 720,000 operations a second. At about 50,000 operations per shard that needs 16 shards, and a key that moves to a new shard simply starts as a full bucket.
The first thing that breaks is usually a hot key. One abusive client sending 50,000 requests a second puts every check on a single shard. A deny cache handles this: once a key has been rejected, the gateway remembers it for the 0.1 s until its next token arrives and rejects that key's requests from memory without calling the store.
A large customer allowed 20,000 requests a second is a harder hot key, because the deny cache does not help when requests pass. Each gateway can instead take tokens from the store in batches of 50 and spend them locally, which cuts the store calls by a factor of 50.
| When this fails | What happens | What you do |
|---|---|---|
| A gateway node | The requests it was handling fail. | The load balancer removes it from rotation. Counters are shared, so no counts are lost. |
| A counter shard's primary | Its keys time out for a few seconds until the replica is promoted. | Each rule's on_store_down setting applies. Replication is asynchronous, so a few extra requests may pass once. |
| The whole counter store | There are no shared counts. | Most rules use local limits and login fails closed. An alert pages the on-call engineer. |
| The rules store | Rules cannot be changed. | Gateways keep enforcing the last rules they loaded. |
| The network to the store is slow | Checks exceed the 2 ms budget. | A 5 ms timeout sends the request to the fallback, and repeated timeouts make the gateway skip that shard for a few seconds. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Describes one algorithm in one process, and needs a hint that separate gateway counts multiply the limit. |
| Mid | Uses a shared counter store with an atomic check, returns 429 with Retry-After, and estimates the load on the store. |
| Senior | Chooses the algorithm and the failure behaviour for each rule, uses the store's clock, avoids retrying a timed-out take, handles hot keys, and says what each endpoint does when the store is down. |
Your counter store is down. What happens to the login endpoint?
Login fails closed. Without a limit an attacker can try passwords as fast as we answer, and a few minutes of failed logins is the smaller harm. The rest of the API falls back to local limits, so it stays up.
Isn't rejecting every login a bad experience for real users?
It is, so I would soften it. During the outage each gateway applies a strict local limit, for example 1 attempt per IP address per minute. Real users can still log in slowly, and an attacker gets almost nothing.
Follow-up questions
How do you limit across several regions?
A store shared between regions would add tens of milliseconds to every request, which breaks the 2 ms budget. Instead, give each region its own counters and divide each client's limit between regions in proportion to its traffic.
Why not put the limit in the load balancer?
Many load balancers can limit requests per IP address, and that is a good first layer against floods. They do not know the API key, the plan or the endpoint rules, though, so they cannot enforce the per-customer limits. Use both.
How do you charge more for expensive requests?
Give each endpoint a cost, for example 1 token for a read and 10 for an export, and pass it as the cost argument to the atomic take. A request whose cost exceeds the tokens left is rejected, and Retry-After says how long until enough tokens have refilled.
How do you roll out a new or stricter rule safely?
Run the rule in shadow mode first, where the gateway evaluates it and records what it would have rejected but allows the request anyway. Once the logged rejections look right, for example that they hit only abusive clients, switch the rule to enforcing.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".