Rate Limiter: Scaling It
You handed the interviewer the number yourself, twenty times the plan, and minutes twenty to thirty are what they do with it. Four pushes come, in this order:
- A limit of a hundred a minute is being enforced twenty times over, so something has to hold one count.
- Whatever holds that count is a network call in front of every request, and that call needs a price.
- Two servers can see the same last token at the same moment, and both can spend it.
- The thing holding the count can die at peak, with every request waiting on an answer.
Whose Bucket
"A client on a hundred a minute just made nineteen hundred calls and nobody stopped it. Why?" Because nobody ever saw nineteen hundred. Each of the twenty servers saw about 95 calls, and 95 is under 100. There is no count of that client anywhere, only twenty counts of pieces of it.
A limit means one count that every server reads. So the buckets move into one shared in-memory store, keyed by API key, and all twenty servers ask it. That also ends the restart problem, because a server that restarts no longer has buckets of its own to hand out again.
Two cheaper answers get rejected out loud. A twentieth of the limit on each server holds only while traffic is even, and a client pinned to one server by a long-lived connection gets 5 a minute of the 100 it paid for. Routing by key at the load balancer does give one count, but a heavy client can no longer be spread across servers, and a lost server takes its clients' counts with it.
The price is one more system on call and a hop on every request, and the interviewer has already noticed the hop.
The Hop
"You've put a network call in front of every request in the fleet. Is that affordable?" Yes, on one condition: the store stays in the region. Split it over the two nodes Scope sized, by a hash of the key, and give each a replica in another zone. That makes four machines. A round trip between zones is 1 to 2 milliseconds, so budget 2 against the agreed 5, which leaves 3 for the node's own work and a bad moment. A check names one key, so it goes to one node and nothing crosses partitions.
A store shared across regions fails the same sum. About 70 milliseconds from US east to US west is fourteen times the budget, on every request, before the handler has started. So the count stays in the region, and a limit across regions comes back later as a question of its own.
If the rate outgrows two nodes, reach for a pipeline before more nodes. A pipeline sends many commands down one connection without waiting for each reply, and it takes a node from about 100,000 simple operations a second to about a million. A check is a small script, so expect less than that, and measure it before you promise it.
So you pay 2 milliseconds on every request, and you now owe a timeout, because a call that usually takes 2 milliseconds can also never come back. That debt comes due in the fourth push.
The Hundredth Request
"Two servers read one token left at the same moment. Who gets it?" As drawn, both. Each reads one, each writes zero, and the hundredth request gets in twice. The gap between the read and the write is the whole problem, so close it. The read, the refill and the take, the spending of the token, become one atomic step on the node that owns the key. That node runs one key's operations one at a time, so the call that reaches it first gets the token, and the other finds none and gets a 429.
The alternatives each lose something you can name. A lock on the key adds two trips to the read and the write, one to take it and one to release it. At 2 milliseconds a trip, those four trips are 8 milliseconds, past the budget, and a holder can die with the lock in hand. Last writer wins, from Chapter 4's Concurrent Writes and Conflicts, drops one of the two takes, so the count loses the very request it was meant to catch.
The node also supplies the time. Elapsed time now comes from one clock, so servers whose clocks disagree cannot mint tokens. That clock can still jump, and a failover brings the replica's. So a negative gap counts as zero, and the capacity limits what a forward jump can grant to one full bucket. Each server sends the key, the cost, and the capacity and refill rate from the key's rule, and the node sends back what Scope's call returns. The few lines that do this are close to Backend Deep Dive's script, in its lesson on rate limiting and backpressure, except that its script takes the time from the caller. You name it and keep moving.
take(key, cost, capacity, refill_rate) -> allowed, tokens_left, retry_after_seconds
This costs you logic in the store, and it does not make the count exact. The replicas are asynchronous, so they forget on failover, as Chapter 4's Leaders, Followers and Everyone warns. Assume 100 milliseconds of lag. At peak a node takes about 40,000 checks a second, so about 4,000 takes are forgotten when it fails over. That hands a token or so back to each of a few thousand keys, and it is the stated overshoot Scope promised.
A synchronous replica would close that gap for another 2 milliseconds on every request, out of the 3 you have left, and 4,000 tokens on a rare failover are not worth that. In the terms of CAP and PACELC, Precisely, this data gives up consistency in a failure, and gives it up for latency on a normal day. One case still strains this shape, and you say so first: "One very heavy key on one node, and how far I'd relax the exact count for it: I'll take that in the deep dive."
When the Store Is Down
"The store just died, at peak. Walk me through the next ten seconds." Start with the debt from the hop. Every call to the store has a 5-millisecond timeout, so the first requests wait the whole budget and no more. Then a circuit breaker, from Chapter 6's Failure Across Many Services, stops calling. Assume each server keeps one breaker per node, and each opens after 100 timeouts in a row to its node. A server makes 4,000 checks a second, half of them to each node, so that takes about 50 milliseconds, whether one node died or both.
From there each server decides alone, with a local bucket set at the limit divided by the servers. A hundred a minute over twenty is 5 a minute each. That is the first design's map, back on every server at a twentieth of its old limit. The whole move fits in a sentence: "I'll give the store a five-millisecond timeout and a breaker, so a dead store costs five milliseconds for a moment, not an outage."
Then comes a policy per route, because routes do not all protect the same thing. Read routes fail open onto the local bucket, and so does an ordinary write whose worst case is load you survive. A route guarding a password check or a paid call fails closed with a 503, since the caller is not the reason for the refusal.
Now the ten seconds. Assume a failover takes 10 seconds, with a replica promoted at the end of them. If one node died, half the keys are judged locally: 40,000 a second for 10 seconds is 400,000 requests. If the whole store is out for those seconds, all 80,000 a second are, and that is 800,000 requests. The breaker lets a few calls through to test the store, and when they succeed the servers go back to it. A key that lost its bucket starts full, which is one extra burst at most.
The cost lasts as long as the failure does. A client spread across the servers keeps about its 100 a minute. One pinned to a single server sees 5 a minute, a twentieth of its limit, for those seconds. Callers on the closed routes see errors for those seconds. And someone has to keep the list of routes and what each one does.
One Count, With a Fallback
A request reaches the load balancer, then any of twenty API servers, each with the library, the timeout, a breaker per node and a fallback bucket. The check goes to the counter store: two partitions by key, each with a replica in another zone. If the store answers, the request is admitted or refused on its one count. If it does not, the fallback decides, and the route's policy says how.
All three of the first design's limits are gone: twenty servers share one count, a restart hands out nothing, and one clock sets the refill, with a jump worth one bucket at most. The buckets did not vanish. They moved to the store, and a smaller copy of them stayed behind on each server as the fallback.
- Quoting a round trip with no budget to compare it to. The interviewer asks whether 2 milliseconds is a lot, and you have no way to say.
- Fixing the race with a lock, two more trips to solve what one atomic step removes. The sum goes past the budget while you are explaining it.
- Calling the count exact over asynchronous replicas. The interviewer asks what a failover does, and the answer is about 4,000 takes.
- One failure policy for the whole API, as if every route protected the same thing. Sign-in then fails open, and the interviewer asks about guessing passwords.
- The store justified by the fleet's two thousand a minute, and the hop priced as soon as it appears.
- The overshoot given as a number: about 4,000 takes, a token each.
- The failure policy set per route, with what each limit protects as the reason.
Knowledge Check
What does the shared store add to a request on a normal day?
- About 2 ms of round trip, which leaves 3 of the agreed 5
- About 5 ms of round trip, which spends the whole budget
- About 4 ms in all, with one trip to read and one to write
- About 100 ns of memory on the node, which nobody will notice
Why does one store shared by every region fail here?
- It cannot hold 2 million buckets in one place
- It cannot take 80,000 checks a second at one site
- About 70 ms on every check, fourteen times the budget
- Replicas in far regions cannot be kept in sync at all
A node fails over with 100 ms of replica lag, at 40,000 checks a second. What do clients get back?
- About 40,000 takes forgotten, a whole second of its traffic
- A full bucket for each of the 1 million keys on that node
- Nothing, because the atomic step is repeated on the replica
- About 4,000 takes forgotten, a token or so for a few thousand keys
During the fallback, what does a client on 100 a minute get on a read route, if a long-lived connection pins it to one server?
- About 100 a minute, as its own server now holds all of its bucket
- About 5 a minute, a twentieth of its limit, for those seconds
- About 2,000 a minute, since each server gives it a fresh 100
- Nothing at all, as a 503 goes to every call until the store is back
You got correct