Design a distributed rate limiter - 200 API gateways share one count per client, answer every request in under 10 ms, and handle one million checks a second. The limiter sits in front of every request, so it must be fast, it must be right when two gateways decide at the same moment, and it must never become the outage itself. The staff-level signal is one atomic script inside Redis, a token bucket with two knobs, a fail mode chosen per rule, and stopping a flood in the gateway before it reaches Redis.
Written by a Staff+ Engineer and an Engineering Manager
12+ years of experience in distributed systems and real-time messaging. Tech lead for large-scale chat applications serving billions of users. Over 12 years of industry experience with 6 years in engineering leadership, building and scaling tech infrastructure teams that deliver end-to-end large-scale distributed systems.
Finished this lesson?
Sign in to save your progress across devices.
Tip: use ← and → to move between lessons.
Was this lesson helpful?
Rehearse this exact question with the author
45-minute mock with a Staff+ engineer who interviews at your target company. Premium members save $20.
What to Design?
Could you answer these today? Tick what you already know.
The first drawing takes a minute: a gateway, a counter in Redis, a 429 when the counter is too high. The interview is decided by four questions about what happens when 200 gateways use that counter at once. Each one is a deep dive later on this page, with three designs side by side: the one that sounds right, a better one, and the one that holds.
Swipe to see all columns
| The four questions, and the answer that sounds right | |||
|---|---|---|---|
| # | The interviewer asks | The answer that sounds right | What it misses |
| DD1 | Two gateways see the last token at the same moment. How many requests pass? | The gateway reads the count, checks it and writes it back | Both read 1 and both allow. Read, check and write must be one step inside Redis |
| DD2 | "120 requests a minute." How do you count? | One counter per minute, reset at the minute | 120 requests at 11:59:59 and 120 at 12:00:01 are 240 in two seconds |
The same three habits answer all four:
Do not spend your questions on which HTTP framework runs the gateway. Spend them on how exact the limit must be and what happens in a failure.
Swipe to see all columns
| Scope Decisions | ||
|---|---|---|
| Question | Agreed answer | Why it matters |
| Must the limit be exact? | No. A small overshoot for a short time is fine. A client that is never limited is not | We can use a fast store with copies that lag a little, not a slow store that is always exact |
| How many checks? | 1,000,000 a second at peak | One Redis node does about 100,000. The counts must be split over many nodes |
| How much time may a check cost? | Under 10 ms at p99 | No database query on the request path. Rules sit in memory, counts in Redis |
Out of scope (say this out loud): analytics on who was limited, keeping counts for the long term, the code inside client libraries, network-level attack protection in front of the gateway, and pricing tiers.
FR1 — Know the client. Find the client of each request by user ID, API key or IP address, and pick the rules that apply.
FR2 — Enforce the rule everywhere. A rule such as "120 requests a minute" holds for the client in total, whichever of the 200 gateways its requests reach.
FR3 — Reject clearly. A request over the limit gets HTTP 429. Every answer says how many requests are left and when the limit is fresh again. A 429 also says how long to wait.
FR4 — Change rules live. An operator changes a rule and it is in force within seconds. Nothing is deployed or restarted.
The key principle behind all four
Swipe to see all columns
| Five facts and the conclusions they do not supportRead each row as: the fact on the left does not, by itself, imply the claim in the middle. | ||
|---|---|---|
| Fact | Does not imply | Why the gap exists |
| My gateway read 1 token left | 1 token is left | Another gateway read the same number in the same millisecond |
NFR1 — Fast. A check adds less than 10 ms at p99. In the normal case it is one round trip to Redis, about 1 ms.
NFR2 — Scale. 1,000,000 checks a second at peak, for 100 million daily users.
NFR3 — Never the outage. When the count store is slow or down, API requests still get answered. The limiter may be less exact. It may not block the API.
NFR4 — Close enough. A short overshoot is accepted: a few extra requests after a failover. A lasting way around the limit is not.
NFR5 — One client cannot hurt the others. A client that floods the API is stopped without slowing down the checks of everyone else.
| Capacity Thought Experiment | |
|---|---|
| Parameter | Value |
| Users | 100 million a day |
| Checks at peak | 1,000,000 a second |
| Gateways | 200, each handling 5,000 requests a second |
| One Redis shard | About 100,000 checks a second. A check reads, computes and writes |
| Shards | 16, each at 62,500 a second: 62.5% of what it can do |
The number that identifies the real system is the gap between one node and the target:
needed 1,000,000 checks /s
one Redis shard 100,000 checks /s 10 shards would run at 100%
chosen 16 shards 62,500 /s each = 62.5%
memory 1.5 GB for all 10 million buckets
Memory is tiny. The limit is operations a second, so the design is about spreading checks, and about not sending checks that are not needed. The 200 gateways, the 16 shards and the timeouts are illustrative assumptions.
Interviewer signal: candidates who say "10 shards, because 1,000,000 divided by 100,000 is 10" have sized the system with no room for a spike or a lost node. Candidates who say "memory is 1.5 GB, so this is not a storage problem. It is 1,000,000 operations a second, I plan each shard at about 60%, so 16 shards" have found the system.
Three ideas shape everything:
A client's requests land on many gateways. If each gateway counted alone, a rule of 120 a minute would allow 120 times 200. So one shared store holds the count. And because two gateways can ask in the same millisecond, the store itself must read, check and change the count as one step.
Whatever the limiter does, every request pays for it. So the request path has no database query and no second network hop: the rules are in the gateway's memory, and the count is one call to Redis. And when that call fails, the request must still get an answer within milliseconds.
A bucket is not money. If a count is lost, the client starts with a full bucket and gets a few extra requests, once. That lets us pick speed over safety everywhere: memory only, copies that lag, no backups.
The core recognition
This is a fast shared counter with a clear rule for when it is unreachable. The counter is split over shards by client. The logic runs inside the store. The gateways keep everything else in memory.
| Design Decisions | |
|---|---|
| Design choice | Reason |
| The limiter is a library inside the gateway | No extra network hop for every request |
Token bucket, with capacity and refill_per_sec | |
Two records carry the design: the rule, which is durable and rarely changes, and the bucket, which changes on every request and may be lost.
One row per rule. A few hundred rows in total.
Swipe to see all columns
| rate_limit_rules (PostgreSQL) | ||
|---|---|---|
| Field | Type | Comment |
rule_id | STRING | Key, for example r1 |
name | STRING | For example "API default" |
scope | ||
One small record per client and rule, in Redis.
Swipe to see all columns
| Bucket (Redis hash) | ||
|---|---|---|
| Field | Type | Comment |
| key | STRING | {key_alice}:r1: the client in braces, then the rule |
tokens | FLOAT | Tokens left. Can be a fraction, for example 0.4 |
A token bucket works like this. The bucket holds at most capacity tokens. It gains refill_per_sec tokens every second. A request takes one token. If less than one token is there, the request is rejected. Nothing runs in the background: the tokens gained since last_refill are added when the next request arrives.
A bucket that sees no request for an hour is deleted. Its client starts again with a full bucket, which is what an hour of waiting would have given anyway.
Swipe to see all columns
| Supporting records | ||
|---|---|---|
| Record | What it holds | Why it exists |
| Rule cache | All rules, in the memory of each gateway | The request path reads rules without a network call |
Channel rules-changed | A message such as "r1 v8" | Tells every gateway to reload a rule (Phase 3) |
Counter violations:{client} | ||
Why the braces? Redis Cluster splits all keys over 16,384 hash slots and gives each shard a range of slots: 1,024 each with 16 shards. Normally the whole key decides the slot. With braces, only the part inside them does. {key_alice}:r1 and {key_alice}:r2 both hash key_alice, land in slot 6,500, and live on shard 7. A script may only touch keys of one slot, so this keeps every check on one shard.
Swipe to see all columns
| Storage | ||
|---|---|---|
| Store | Data | Consistency |
| Redis Cluster | Buckets, violation counters, blocked flags | Memory only. One script at a time per shard. A replica lags by a few milliseconds. Losing a bucket is acceptable |
| PostgreSQL | Rules | The source of truth for rules. Durable |
| Gateway memory | Rule cache, recent denials, blocked clients | A copy per gateway. At most 30 s behind for rules |
The limiter has no public API. It is a function call inside the gateway, plus a small admin API for rules.
Swipe to see all columns
| The calls | ||
|---|---|---|
| Call | Sent to | What it does |
check(client_id, rule_id) | Limiter library, in the gateway | Returns allowed, remaining, reset and retry_after_ms |
EVALSHA token_bucket {key_alice}:r1 20 2 | ||
What the script does, in five lines:
read tokens, last_refill
add (now - last_refill) x refill_per_sec never above capacity
if tokens >= 1: take 1, answer "allowed"
else answer "denied", and the wait until 1 token is there
write tokens, last_refill = now
now is the clock of Redis, not of the gateway. 200 gateway clocks never agree to the millisecond, and a bucket must be measured with one clock.
What the client sees. Every answer carries two headers. A 429 carries a third.
Swipe to see all columns
| Rate limit headers | ||
|---|---|---|
| Header | Example | Meaning |
X-RateLimit-Remaining | 6 | Requests the client can still send right now |
X-RateLimit-Reset | A time 7 s from now | When the bucket is full again |
Retry-After | 1 | Only on a 429. Seconds to wait before the next try, rounded up |
A client that reads these headers can slow down before it is rejected, and knows how long to wait after it is.
Present the design as four short stories, each in its own colour on one whiteboard: Phase 1 allow (black), Phase 2 reject (blue), Phase 3 change a rule (green), Phase 4 a Redis shard dies (purple). The number on an arrow is the same number in the animation and in the step table.
Swipe to see all columns
| The four phases | |||
|---|---|---|---|
| Phase | Colour | Story | What it leaves behind |
| Phase 1: Allow (FR1, FR2) | Black | Alice's request arrives, one script call takes a token, the request goes on | One token less in one bucket |
| Phase 2: Reject (FR3) | Blue | Alice's bucket is empty. She gets a 429, waits one second, and is let in again | An updated bucket. The backend saw only the allowed request |
How to read the picture
key_alice and rule r1: 2 tokens a second, capacity 20. Her bucket is {key_alice}:r1 on shard 7.Each phase below is an interactive walkthrough of the same picture. It plays on its own. You can pause it, step with the arrow keys, and click any component to read its role.
Goal: decide in about a millisecond, with a count that all 200 gateways share.
/v1/ordersClient → API gateway G1Nothing is written in this step.
Swipe to see all columns
| Phase 1 step by step (black arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | Alice's service sends GET /v1/orders with the API key key_alice. The request reaches gateway G1. | Nothing |
| 2 | G1 looks in its rule cache, in memory: API keys fall under rule r1, 2 tokens a second, capacity 20. The bucket key is {key_alice}:r1. | Nothing. No database call |
Why it is built this way
key_alice to slot 6,500 and knows that shard 7 owns that slot. There is no router in between.A separate service would add a second network hop to every request: gateway to limiter, limiter to Redis. With the limiter as a library, the gateway talks to Redis directly and a check stays at about 1 ms. A separate service makes sense when many different kinds of callers need limits and cannot all carry the library. The script and the buckets would be the same.
Goal: stop the request at the gateway, and tell the client exactly how long to wait.
Alice's service is stuck in a fast loop. At 12:00:10.000 it used its last token.
/v1/ordersClient → API gateway G1Nothing is written in this step.
Swipe to see all columns
| Phase 2 step by step (blue arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | At 12:00:10.200 the next GET /v1/orders reaches G1. | Nothing |
| 2 | G1 runs the same script. The bucket has 0 tokens. 200 ms have passed: that adds 0.4. Less than one token, so no token is taken. | Bucket: tokens 0.4, last_refill |
Why it is built this way
Retry-After is in whole seconds, so the header says 1.It does not get more requests through: each try finds less than one token. But every try still costs a round trip to Redis. One impatient client is harmless. A client that sends 50,000 requests a second is not, and that is DD4: the gateway remembers the "no" and stops asking Redis.
Goal: a changed rule is in force in all 200 gateways within seconds, and a gateway that missed the news still catches up.
/admin/rules/r1Operator → Admin serviceNothing is written in this step.
Swipe to see all columns
| Phase 3 step by step (green arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | An operator raises the burst of rule r1: PUT /admin/rules/r1 with capacity 40, up from 20. | Nothing yet |
| 2 | The admin service saves the rule in PostgreSQL and raises its version from 7 to 8. | Rule r1: capacity 40, version 8 |
Why it is built this way
From the rule store. At start it loads all rules, a few hundred rows, then subscribes to the channel. It takes no traffic before the rules are loaded. If the rule store is down at that moment, a running gateway keeps working from its cache, and a new one waits: a gateway without rules would let everything through.
Goal: a dead Redis node costs some accuracy for a few seconds. It never costs a request.
EVALSHA token_bucket {key_alice}:r1 20 2G1 → Redis shard 7 (primary)no answerNothing is written in this step.
Swipe to see all columns
| Phase 4 step by step (purple arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The primary node of shard 7 dies. G1 runs the script for Alice and gets no answer within 5 ms. | Nothing |
| 2 | Rule r1 has fail mode open: G1 forwards the request to the backend without a decision. G1 starts to measure how long it has been in this degraded mode. | Nothing |
| 3 | After 5 timeouts in a row G1 stops calling shard 7 and tries again only once a second. Requests no longer wait 5 ms each. | |
Why it is built this way
The primary answers a script first and sends the change to its replica just after. That saves waiting for the replica on every check. When the primary dies, the changes of its last few milliseconds never arrived. The replica's buckets are a little older, so they show a few tokens that were in fact spent. A client can get those requests a second time. The extra is small and happens once, which the question allows.
The deep dives are the four questions from the top of the page. Each one compares three designs for the same scenario: a Bad one, which is usually the answer that sounds right; a Good one, which still leaves a gap; and a Great one, which holds. The answers start covered. Read the scenario, decide what you would build, then click each card.
Swipe to see all columns
| Deep Dive Map | |||
|---|---|---|---|
| Deep Dive | Topic | Scenario | NFR |
Scenario: Alice's bucket holds exactly 1 token. Two of her requests arrive in the same millisecond, one at gateway G1 and one at G2. How many get through?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The gateway reads the bucket from Redis, does the token maths itself, and writes the new values back.
Where it breaks. G1 and G2 both read tokens 1. Both decide "allowed". Both write tokens 0. Two requests passed on one token. With 200 gateways, up to 200 can pass on one token, and a client that sends in bursts hits this all the time.
Wrapping the write in a Redis transaction (MULTI and EXEC) does not help. It makes the writes one unit. The read and the decision still happened earlier, outside of it.
The idea. Before reading, the gateway tells Redis to watch the bucket (WATCH). If anyone changes the bucket before the gateway's write, Redis refuses the write and the gateway starts again.
What it fixes. The count is right. G1's write goes through. G2's write is refused, G2 reads again, sees 0 tokens and denies.
What it still misses. It costs two round trips when nothing goes wrong, and four for the loser. And it gets worse exactly when it matters: the busier a bucket, the more writes are refused and repeated. A client that floods makes the limiter slow and Redis busy.
The key idea. Move the read, the maths and the write into Redis itself. Redis runs one script at a time on a shard, so nothing can happen between the read and the write.
How it works
The token bucket logic is a small Lua script, loaded into every shard once.
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
HMGET {key_alice}:r1G1 → Redis shard 7tokens 1Nothing is written in this step.
Swipe to see all columns
| DD1 side by side | |||
|---|---|---|---|
| Bad: read, then write | Good: watch and retry | Great: one script | |
| Requests that pass on 1 token | 2, or up to 200 | 1 | 1 |
| Round trips per check | 2 | 2, and 4 or more after a clash | 1 |
Check it against the scenario
| One token, two requests | |
|---|---|
| Situation | Outcome with the Great option |
| Both calls arrive in the same millisecond | Redis runs them in turn. The first is allowed, the second is denied with a wait of 500 ms |
| 50 gateways call for the same bucket at once | 50 scripts run in turn, each a few microseconds long. Exactly as many are allowed as tokens are there |
| A gateway dies after sending the call | The token is spent and no request used it. One token is lost. Nothing is counted twice |
| A rule changes while calls are on their way | Each call carries its own capacity and rate. Old and new calls mix for a moment, and both are valid |
The trade-off to name. While a script runs, the shard does nothing else. So the script must stay tiny: one bucket, a few lines, no loops. That is also why one shard does about 100,000 checks a second and not 200,000. And logic inside Redis is harder to test and to change than code in the gateway, so keep it to the token bucket and nothing more.
A lock is three round trips: take the lock, read and write, release the lock. And a gateway that dies while it holds the lock blocks that client until the lock times out. The script gives the same guarantee, one at a time, with one round trip and nothing to release.
"The check is read, compute, write. If the gateway does that in three steps, two gateways can both read one token and both allow: a classic check-then-act race. A Redis transaction does not fix it, because the decision is made outside of it. Optimistic locking with WATCH is correct but costs extra round trips and retries under load. So I put the whole token bucket into one Lua script. Redis runs a script atomically on a shard, so the decision is made where the count lives, in one round trip."
Follow-up: "Is Lua in Redis a bottleneck?" — The script touches one small hash and runs for microseconds. It lowers a shard to about 100,000 checks a second, which I planned for: 16 shards at about 60% load.
Scenario: the rule says 120 requests a minute. Alice's service sends 120 requests at 11:59:59 and 120 more at 12:00:01. What does the backend see?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Keep one counter per client and minute. Add 1 for each request. Reject when it passes 120. A new minute starts a new counter. This is called a fixed window.
Where it breaks. The 120 requests at 11:59:59 fill the counter of 11:59. Two seconds later a new minute has started and its counter is at 0, so the next 120 pass as well. That is 240 requests in 2 seconds, under a rule that was meant to hold the client to 2 a second. The backend gets 60 times the steady rate.
The idea. Keep the counters of the last minute and of this minute, and estimate the last 60 seconds from both: the old count times the part of the old minute that is still inside the 60 seconds, plus the new count. This is called a sliding window counter.
What it fixes. At 12:00:01, 59 of the last 60 seconds lie in the old minute. The estimate is 120 times 59/60, which is 118. Two more requests pass, then come 429s. The burst at the minute boundary is gone, and the state is still two numbers.
What it still misses. After a quiet minute, Alice can send all 120 requests in one second, and all pass. The largest burst always equals the whole limit. The rule cannot say "120 a minute, but never more than 20 at once". And the estimate assumes that the old minute's requests were spread evenly, which a burst is not.
The key idea. Split the rule into two numbers: how fast tokens come back (the steady rate) and how many can pile up (the burst).
How it works
"120 a minute" becomes 2 tokens a second. The capacity is set to 20.
tokens and last_refill. Nothing runs between requests.capacity is the burst, is the steady rate.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
INCR key_alice:r1:11:59G1 → Redis shard 7all 120 allowedkey_alice:r1:11:59updateSwipe to see all columns
| DD2 side by side | |||
|---|---|---|---|
| Bad: fixed window | Good: sliding window counter | Great: token bucket | |
| 120 at 11:59:59, 120 at 12:00:01 | All 240 pass | 122 pass | 24 pass |
| Largest burst | 240 | 120 | 20, set by the rule |
Check it against the scenario
| Two bursts around the minute | |
|---|---|
| Situation | Outcome with the Great option |
| 120 requests at 11:59:59, bucket full | 20 pass, 100 get a 429 with Retry-After: 1 |
| 120 more at 12:00:01 | 2 seconds have passed: 4 tokens are back. 4 pass, 116 get a 429 |
| Alice sends a steady 2 requests a second | Every request passes, all day |
| Alice is quiet for an hour, then sends 30 at once | 20 pass. The bucket never holds more than its capacity |
| A partner needs short bursts of 100 | |
The trade-off to name. A token bucket is not a strict "120 in any minute". Right after a full bucket, a client can send 20 plus 120: 140 in one minute. If the limit must be exact, for example a paid plan that sells exactly 1,000 calls, count every request (a sliding window log, in the follow-ups) and pay for the memory. For protecting a backend, the steady rate and the burst are the two numbers that matter.
Nobody. The bucket stores when it was last brought up to date. When the next request arrives, the script multiplies the time since then by the refill rate and adds that, up to the capacity. An idle bucket costs nothing, and after an hour it is deleted. A timer that adds tokens to 10 million buckets every second would be 10 million writes a second for nothing.
"I would use a token bucket. A fixed window is the simplest, but a client can spend a full quota at the end of one window and again at the start of the next: twice the limit in a couple of seconds. A sliding window counter blends two windows and fixes the boundary, but the largest burst is still the whole limit. A token bucket has two parameters that map to what the product wants: the refill rate is the sustained throughput and the capacity is the burst we tolerate. It needs two fields per client, and the refill is computed lazily on each request."
Follow-up: "And a sliding window log?" — It stores a timestamp per request and is exact. At a million checks a second that is a write and a trim for every request, and memory grows with the limit. I would use it only where the limit must be exact.
Scenario: at peak, the primary node of shard 7 dies. One sixteenth of all clients have their buckets there: 62,500 checks a second. What happens to their requests?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. There is none. The gateway calls Redis and waits for the answer, with whatever timeout the network library has. Say it is 1 second.
Where it breaks. Every request for a client on shard 7 now holds a gateway worker for 1 second. At 62,500 such requests a second, all workers of all gateways are busy waiting within moments. Requests of clients on the 15 healthy shards queue behind them. A dead cache node has become an outage of the whole API.
"Reject until Redis is back" sounds safer and ends in the same place for these clients: every request fails, and none of them did anything wrong.
The idea. Give every Redis call a timeout of 5 ms. When it passes, forward the request without a decision. This is called fail open.
What it fixes. The API stays up. A request for a client on shard 7 is 5 ms slower and otherwise normal.
What it still misses. There is no replica, so the limiter is off for these clients until someone restarts the node, and that takes minutes. All their buckets are lost. And "always open" covers every rule: the login rule, 5 attempts a minute per IP address, is off too. Password guessing is unlimited in the meantime.
The key idea. Decide in advance, per rule, what "no answer" means. Make the time without an answer as short as possible. And tell a human when it lasts.
How it works
fail_mode. The default is open: forward. A rule that guards something fragile says closed: answer 429 with Retry-After.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
node downRedis shard 7 (primary)Nothing is written in this step.
Swipe to see all columns
| DD3 side by side | |||
|---|---|---|---|
| Bad: no plan | Good: always open | Great: per rule, with a replica | |
| Requests of clients on shard 7 | Hang for 1 s, then fail | Pass, 5 ms slower | Pass with no delay after the first 5 timeouts |
| Clients on other shards | Stall too | Not affected | Not affected |
Check it against the scenario
| The primary of shard 7 dies at peak | |
|---|---|
| Situation | Outcome with the Great option |
Alice calls GET /v1/orders (rule r1, open) | Forwarded without a check for about 10 seconds |
| Someone tries passwords from one IP address (rule r2, closed) | 429 for about 10 seconds. Honest logins from addresses on shard 7 wait too: the price of closed |
| A client on shard 3 | Checked as always. It does not notice |
| The replica is promoted | Checks work again. A bucket may show a few tokens that were already spent |
The trade-off to name. Fail open has a real risk: Redis often fails when traffic is highest, and that is when the backend needs the limiter most. For about 10 seconds the backend must protect itself, with its own queue limits and load shedding. Fail closed has the opposite risk: the limiter's outage becomes the product's outage. Neither is right for every rule, which is why the rule carries the choice.
Then every check waits for two machines, and a slow replica slows down every request of every client on that shard. What we would save is a few tokens per client, once per failover. The question said a short overshoot is fine. Speed on every request is worth more than those tokens.
"The limiter is on the path of every request, so its failure mode is the most important decision. Every Redis call gets a short timeout, 5 milliseconds. On a timeout the default is fail open: we would rather over-admit for a few seconds than turn a Redis outage into an API outage. Rules that protect something fragile, like login attempts, can be marked fail closed. Each shard has a replica that the cluster promotes in seconds, and replication is asynchronous, so after a failover a few counts are stale and a client may get a few extra requests. I also track time in degraded mode and alert past 30 seconds, because then the backends are unprotected."
Follow-up: "What if Redis fails because of a traffic spike?" — Then fail open sends that spike to the backend. So the backend keeps its own last line of defence, and operators can switch on a coarse limit at the load balancer.
Scenario: the API key key_mallory is leaked, and a botnet sends 50,000 requests a second with it. Its rule allows 2 a second. Every one of those checks goes to shard 7, which already serves 62,500 checks a second.
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Nothing special. Every request runs the script, and the script says no.
Where it breaks. The answers are right, but each "no" costs a script run. Shard 7 now gets 62,500 plus 50,000: 112,500 calls a second. It can do about 100,000. Its calls slow down and time out, and the honest clients on shard 7 fall into fail open: the limiter is off for them. Adding shards does not help. All requests with one key go to one shard, however many shards there are.
The idea. When the script denies a bucket, it also says how long until the next token: 500 ms here. The gateway keeps that in memory and rejects the same bucket itself until then.
What it fixes. Each gateway sees 250 of these requests a second. It asks Redis at most twice a second and answers the rest from memory. Over 200 gateways that is at most 400 calls a second in place of 50,000. Shard 7 is fine again.
What it still misses. The flood never stops. Every half second a token still goes to the botnet. Every gateway finds out on its own. And nothing records that a key is being abused, so nobody can act on it.
The key idea. A client that is denied thousands of times in a few seconds is not impatient, it is abusive. Count the denials, and block the client in every gateway for a while.
How it works
blocked:key_mallory for 300 seconds and publishes the name on a channel.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
/v1/ordersBotnet → 200 gatewaysNothing is written in this step.
Swipe to see all columns
| DD4 side by side | |||
|---|---|---|---|
| Bad: ask Redis every time | Good: local deny memory | Great: shared blocklist | |
| Calls to shard 7 for this key | 50,000 a second | At most 400 a second | 0, plus 200 counter updates a second until the block |
| Shard 7 in total | 112,500 a second: overloaded | About 62,900 a second | 62,500 a second |
Check it against the scenario
| 50,000 requests a second with one key | |
|---|---|
| Situation | Outcome with the Great option |
| The first second of the flood | Each gateway asks Redis twice and rejects the rest from memory. 200 gateways report about 250 denials each: far over 1,000 |
| From the second second on | The key is on every gateway's blocklist. No Redis call, a 429 straight from memory |
| A new gateway starts during the block | It reads the blocked: flags when it starts, as it reads the rules |
| The owner of the key replaces it | The new key has its own bucket and no block. The old one stays blocked while the flood lasts |
The trade-off to name. Memory in the gateway is one more thing that can be stale. A "no" kept for 500 ms can never be wrong, because no token can appear sooner. A block of 300 seconds can be wrong: if the threshold is too low, a clumsy but honest client is locked out for five minutes. So the threshold sits far above anything a retry loop produces, the block expires by itself, and an operator can lift it by deleting one key.
It only keeps an entry for a bucket that was just denied, and the entry disappears when the wait is over. Clients that stay under their limit never get an entry. A flood of many different keys could still fill this memory, so it has a fixed size, for example the 10,000 most recent entries. To find heavy clients before they are denied, a gateway can use a Count-Min Sketch: a small table of counters that estimates how often each key was seen, in a fixed amount of memory.
"All requests for one client hash to one shard, so a single abusive key can overload that shard however many shards I have. My first line of defence is in the gateway: when Redis denies a bucket, the gateway remembers the denial until the next token is due and rejects locally. That cuts 50,000 calls a second to a few hundred. For sustained abuse I count denials per client, and past a threshold I put the client on a blocklist that is pushed to every gateway, so it is rejected before any Redis call. And good client SDKs that honour Retry-After with backoff keep honest clients from ever looking like this."
Follow-up: "Could you just give the hot key its own shard?" — Redis Cluster can move a slot, but one slot holds many clients and moving it takes time. It also rewards the abuser with dedicated hardware. Rejecting early is cheaper and faster.
| If the interviewer keeps going | |
|---|---|
| Question | Short answer |
| Why 16 shards and not 10? | 10 shards at 100,000 checks each is exactly the peak, with nothing left for a spike or a slow node. 16 shards run at 62.5%. When one shard is in trouble, the other 15 are not affected |
| How do you add a shard? | Redis Cluster moves hash slots to the new node, key by key, while it keeps serving. A gateway that asks the old node is told where the slot went. A bucket that gets lost on the way starts full: one extra burst |
| One request falls under two rules | For example the rule of the API key and the rule of the IP address. The gateway sends both script calls at the same time, to two shards, and allows only if both allow. The headers show the stricter answer. A token spent on the rule that allowed is not given back: simple, and slightly strict |
| Several regions | Each region runs its own cluster and enforces the limit by itself. A client that uses three regions gets up to three times the limit. One global count would need a call across regions on every request, far over 10 ms, or a background job that evens out the counts. Limits per region are the practical choice |
For the pattern on its own, see Rate Limiting.
Two gateways read the same last token and both allow. The three steps must be one script inside Redis.
A client spends the limit at the end of one minute and again at the start of the next. Use a token bucket: one number for the rate, one for the burst.
When Redis hangs, every request hangs with it. A 5 ms timeout turns "no answer" into a decision.
Always closed makes a Redis outage an API outage. Always open leaves the login unprotected. The rule carries the choice.
1,000,000 divided by 100,000 is 10, and 10 shards run at 100%. Plan each shard at about 60%: 16 shards.
All requests of one client go to one shard. Reject a flooding client in the gateway, before Redis.
That is a query on the path of a million requests a second. Keep rules in gateway memory, refresh them by a message and a 30-second check.
A client that does not know how long to wait retries at once, and makes the flood worse. Always send Retry-After.
The shape of a strong answer: start with a gateway and a counter in Redis. Pick the token bucket and say what its two numbers mean. Show the race between two gateways and close it with one script. Size the cluster by operations, not by memory, and leave room. Then spend your time on failure: a short timeout, a fail mode per rule, a replica. End with the client that floods, and stop it before Redis.
Decide in one place, in one step
The bucket lives in Redis, and one script reads, refills, checks and writes it. 200 gateways can ask in the same millisecond and exactly the right number of requests pass.
The limiter must never be the outage
5 ms, then a decision that the rule made in advance: open for most, closed for the fragile. A replica takes over in about 10 seconds, and an alert fires after 30.
Do not ask Redis what the gateway already knows
Rules, a "no" that is still valid, and blocked clients are answered from memory. Redis only sees the checks that need a shared count.
| What the interviewer expects at each level | |
|---|---|
| Level | A strong answer shows |
| Junior | Clients limited by user ID, API key or IP address. A gateway that checks a counter in Redis and returns 429. Why a token bucket suits bursty traffic, and why one node is not enough |
| Mid-level | Picks the token bucket quickly and explains the script for atomicity. Shards the counters, explains hash slots and why the client is in braces. Gives a clear answer to "Redis is down" with the trade-off |
| Senior | Raises the hard parts unasked: the race and why a transaction does not fix it, a hot key and rejecting in the gateway, stale counts after a failover, limits across regions. Sizes the system: 16 shards at about 60%, 1.5 GB of state |
These aren't toy problems — they reflect real infrastructure challenges at companies that run public APIs at scale. If you want to walk through this design in a mock interview or get feedback on your own approach, book a session with us. We're here to help you sharpen your thinking, build your confidence, and land your next offer.
Pick an answer for each question, and you see at once whether it is right. Show explanation opens the answer, why it is right, and why each of the other options fails.
Question 1 of 10
The peak is 1,000,000 checks a second. One Redis shard does about 100,000, and you plan each shard at 62.5% of that. How many shards?
Question 2 of 10
A bucket key is {key_alice}:r1. Which part does Redis Cluster use to pick the shard?
Question 3 of 10
Two gateways read the same bucket in the same millisecond, see 1 token, and both let their request through. Which change removes this?
Question 4 of 10
WATCH with a retry also gives the right count. Why is the script still the better choice?
Question 5 of 10
A rule of 120 requests a minute is built as one counter per clock minute. A client sends 120 requests at 11:59:59 and 120 at 12:00:01. How many pass?
Question 6 of 10
A token bucket has two settings, capacity and refill rate. What does each one control?
Question 7 of 10
A bucket is empty and gains 2 tokens a second. A request is denied. What does the client get told?
Question 8 of 10
Redis does not answer within 5 ms. What does the gateway do for a rule with the default fail mode?
Question 9 of 10
A replica is promoted after its primary died. Why might a client get a few extra requests through?
Question 10 of 10
A leaked key sends 50,000 requests a second, and all of them hash to one shard. What is the first line of defence?
| DD3 | The Redis shard is gone. What do the gateways do? | Reject until it is back, to be safe | Then a dead cache node takes the whole API down. Let requests through by default, and reject only where the rule says so |
| DD4 | One leaked key sends 50,000 requests a second. What now? | Add more Redis shards | One key lives on one shard. Stop the flood in the gateway, before it reaches Redis |
| Who is a client? | A user ID, an API key or an IP address. A request can fall under more than one rule | The bucket key holds the client and the rule |
| The count store is down? | Let requests through by default. Rules that guard something fragile may say: reject | Every rule carries a fail mode (DD3) |
| One region or many? | One region. Other regions run their own copy | A check never crosses regions (see the follow-ups) |
| The rule says 120 a minute | No more than 120 in any 60 seconds | It depends on how you count. A counter per clock minute lets 240 through in two seconds |
| Redis did not answer | The client is over its limit | No answer says nothing about the client. It says the limiter is in trouble |
| Redis has 16 shards | A flood is spread over 16 shards | All requests of one client go to one shard |
| The rule was saved | Every gateway uses it | 200 gateways each keep their own copy in memory |
| 1 replica per shard: 32 Redis nodes |
| Active buckets | 10 million at a time |
| One bucket | Two numbers. With its key and Redis overhead, about 150 bytes |
| Memory | 10 million times 150 bytes: 1.5 GB in total, under 100 MB a shard |
| One check | About 1 ms in the same region. Timeout: 5 ms |
| One number for the burst, one for the steady rate. Two numbers of state |
| One Lua script in Redis does read, check and write | Redis runs one script at a time, so two gateways cannot both spend the last token |
| Redis Cluster with 16 shards | 1,000,000 checks a second at 62.5% load per shard |
Bucket key {client_id}:rule_id | Redis picks the shard from the part in braces: all buckets of a client are on one shard |
| Rules in PostgreSQL, cached in every gateway | Rules must survive a restart, but no request waits for a database |
| A message on a channel, plus a check every 30 s | A rule change arrives in under a second, and a missed message is repaired |
| 5 ms timeout and a fail mode per rule | No answer from Redis becomes a quick decision, not a hanging request |
| A replica per shard | A dead node is replaced in about 10 seconds, not in minutes |
| Denials and blocked clients remembered in the gateway | A flood from one client stops before it reaches Redis |
ENUM |
What identifies the client: user, api_key or ip |
refill_per_sec | FLOAT | Tokens gained per second. 120 a minute is 2 |
capacity | INT | The most tokens a bucket can hold. This is the largest burst, for example 20 |
fail_mode | ENUM | open: let requests through when Redis does not answer. closed: reject them (DD3) |
version | INT | Goes up by one on every change. Gateways compare it |
updated_at | TIMESTAMP | When the rule was last changed |
last_refill |
TIMESTAMP |
When tokens was last brought up to date |
| Denials of one client in the last 10 s |
| Finds a client that keeps flooding (DD4) |
Key blocked:{client} | A flag that lasts 300 s | Gateways reject a blocked client without asking Redis (DD4) |
| Redis shard |
| Runs the token bucket script for one bucket with capacity 20 and 2 tokens a second. One round trip |
PUT /admin/rules/{rule_id} | Admin service | Changes a rule. POST /admin/rules adds one, DELETE removes one |
PUBLISH rules-changed "r1 v8" | Redis channel | Tells all gateways that rule r1 now has version 8 |
| Phase 3: Change a rule (FR4) |
| Green |
| An operator raises a capacity. All gateways use it within seconds |
| Rule r1 at version 8 in all 200 gateways |
| Phase 4: A shard dies (NFR3) | Purple | Redis shard 7 stops answering. Requests go through until its replica takes over | About 10 seconds without a limit for 1 in 16 clients. No failed request |
| 3 | G1 runs the token bucket script on Redis shard 7. The script finds 5 tokens, adds 2 for the second that has passed, and takes 1. It answers: allowed, 6 left. | Bucket: tokens 6, last_refill now |
| 4 | G1 forwards the request to the backend, unchanged. | Nothing |
| 5 | G1 returns the backend's answer with X-RateLimit-Remaining: 6 and X-RateLimit-Reset 7 seconds ahead. | Nothing |
| 3 | The script answers: denied, 0 left, and 300 ms until one full token is there. | Nothing |
| 4 | G1 answers the client itself: HTTP 429, X-RateLimit-Remaining: 0, Retry-After: 1. The backend never sees this request. | Nothing |
| 5 | Alice's service waits one second and tries again at 12:00:11.200. The script adds 2 tokens for that second and takes 1. Allowed, 1 left. | Bucket: tokens 1.4 |
| 3 | The admin service publishes "r1 v8" on the Redis channel rules-changed. All 200 gateways listen to it. | Nothing. A channel message is not stored |
| 4 | G1 reads rule r1 from the rule store and replaces it in its cache. Its next check for Alice passes capacity 40 to the script. | G1 rule cache: r1, capacity 40, version 8 |
| 5 | Every 30 seconds each gateway asks the rule store for the versions of all rules. A gateway that missed the message reloads r1 then. | Nothing when the versions match |
| G1 memory: shard 7 is skipped |
| 4 | After about 10 seconds the cluster promotes the replica of shard 7. It has every write except those of the last few milliseconds. | The replica now owns slots 6,144 to 7,167 |
| 5 | G1's next try reaches the new primary. The script runs again. A bucket may hold a few tokens too many, once. | Bucket {key_alice}:r1, now on the new primary |
| DD1 |
| Two gateways, one token |
| Two requests of Alice arrive in the same millisecond |
| NFR4, NFR1 — Close enough, fast |
| DD2 | "120 requests a minute": which counter? | 120 requests at 11:59:59, 120 more at 12:00:01 | NFR4 — Close enough |
| DD3 | The Redis shard is gone | The primary of shard 7 dies at peak | NFR3 — Never the outage |
| DD4 | One leaked key, 50,000 requests a second | A botnet floods with key_mallory | NFR5, NFR2 — Isolation, scale |
| Wrong more often |
| Slower and slower |
| No change |
| Where the decision is made | In each gateway | In each gateway, checked by Redis | In Redis |
refill_per_sec| 1 number |
| 2 numbers |
| 2 numbers |
| Knobs | The limit | The limit | The steady rate and the burst |
| Give that partner a rule with capacity 100 and the same refill rate |
| Time without a limit |
| Until someone steps in |
| Minutes |
| About 10 seconds |
| The login rule | Fails with everything else | Open: unlimited guessing | Closed: 429 for about 10 seconds |
| Who notices | The users | Nobody | The on-call engineer, after 30 s |
| Buckets start full: each client gets one extra burst of up to its capacity. The alert fires after 30 s |
| Requests the botnet gets through |
| 2 a second |
| 2 a second |
| None for 300 s at a time |
| Honest clients on shard 7 | Checks time out | Not affected | Not affected |
| An honest client retries too eagerly, 20 times in a second |
| Far below 1,000 denials in 10 s. It is rejected from memory until its next token, and never blocked |
| Sliding window log | Store the time of every request and count those of the last 60 seconds. Exact, but one write and one clean-up per request, and memory that grows with the limit. Use it only where the limit must be exact |
| Leaky bucket | Requests wait in a queue that drains at a fixed rate. The output is perfectly smooth, but a burst waits where a token bucket lets it through. Good in front of a backend that can take no burst at all |
| Some requests cost more than others | Let the script take more than one token: 1 for a read, 10 for a report. The rule stays the same |
| Where do you find heavy clients early? | Each gateway keeps a small top-N counter or a Count-Min Sketch of the keys it sees. It costs a fixed amount of memory and shows heavy clients before they are denied |
| What should a good client do? | Read X-RateLimit-Remaining and slow down before it reaches 0. After a 429, wait for Retry-After and add a little random delay, so that many clients do not come back at the same instant |
| Is this the same as a quota? | No. A rate limit refills by itself with time. A quota is an amount that is reserved and used up, such as 100 GB of storage. See [Quota Service](/learn/system-design/questions/quota-service) |
| Limiting bytes, not requests | The same token bucket, counting bytes, and enforced on the host where the traffic flows. See [VM Bandwidth Rate Limiter](/learn/system-design/questions/vm-bandwidth-rate-limiter) |