Rate Limiter: Deep Dives and Curveballs
You picked a token bucket in the first design and asked the interviewer to wait for the reason. Minutes thirty to forty-five give it, then settle how exact the shared count has to be and which routes fail open, before four curveballs ask for things this limiter may not be the right place to do.
The Algorithm, Where Each One Is Wrong
This is the counting rule you parked. Describe each algorithm by the exact way it goes wrong, because that is what the interviewer is checking. A fixed window is one counter for each key for each minute. At the boundary, 100 calls in one minute's last second and 100 in the next one's first make 200 in two seconds, and everyone refused during a minute returns together when it turns.
A sliding log keeps a timestamp for every request. It is exact, and its memory is traffic times window. Assume 100 bytes an entry. One minute at 80,000 a second is 480 MB. One hour is about 29 GB. A daily quota is 4 billion entries, which is 400 GB, against 200 MB of buckets. Two weighted window counters, this minute's and the last one's, weighted by how far into the minute you are, cost what a bucket costs and estimate where the log counts.
The token bucket's flaw is its refill. Starting full, a bucket of 100 refilling at 100 a minute admits up to 200 in the first minute, so a plan has to publish both numbers. Refill also needs one clock, which the store now supplies. Choose the token bucket while clients burst for good reasons and the limit protects capacity. The trigger to leave it is a limit promised over an exact window, which takes a log for small limits and metering for large ones.
How Exact the Shared Count Has to Be
Here is the heavy key you set aside. Assume one key limited to 10,000 a second, a fifth of a node's 50,000. An atomic step per request stays exact, and it costs a hop per call, which is 10,000 store calls a second from one customer.
Leased tokens cut that down. A server takes a batch of tokens from the store and spends them locally, using the cost in Scope's call. Spread evenly, twenty servers each spend 500 a second. Taking 50 at a time, each calls the store 10 times a second. That is 200 calls a second, fifty times fewer. Up to 1,000 tokens can sit unused in the servers' hands, so the error is under-admission: the client gets less than it paid for.
Local counts summed every 100 milliseconds take the hop off the path altogether. Each server admits on what it last heard and adds its own count in the background, which is also 200 store calls a second. No server hears anything for up to 100 milliseconds. Take a client sending 20,000 a second, twice its limit: 2,000 requests pass in that time against 1,000 tokens earned, so about 1,000 are past the limit. The error is over-admission, and a client sending faster gets more.
So: atomic by default, leases for keys that load a node, and summed counts only where the hop cannot be paid. A flood on one key is a smaller case with a cheaper answer. A key on the default 100 a minute that is refused can have "denied until" cached in each server for the next token's 0.6 seconds. Twenty servers then ask about 33 times a second, however fast the flood comes. That is When the Cache Hurts again, a local tier with a short expiry, and its cost is up to 0.6 seconds of refusals that may be out of date if the limit has just been raised.
Failing Open or Closed
What decides is the worst an uncounted request can do. On a read route, that is load the API survives. On sign-in, it is extra password guesses: the local buckets keep the rate near the limit, but each failure hands a guesser a fresh burst, and a limit of a few guesses a minute cannot be split over twenty servers at all. On a paid downstream call, it is a bill. An ordinary write takes the same test: if the worst is load you survive, it fails open. Asked for the rule, you can give it in a breath: "On sign-in I fail closed, and on the read routes I fail open onto a local bucket. What decides it is what the limit protects on that route."
A refusal must carry a true wait, or the failure breeds a retry storm, the pattern in Chapter 6's Failure Across Many Services. On a closed route no bucket knows the answer, so send your best estimate: the failover's assumed 10 seconds, less what has passed. With the fallback in place, a request on an open route no longer needs the store to be up, so there the limiter stops being a part in series, in the terms of Regions and the Arithmetic of Nines. On those routes its downtime no longer adds to the API's, which is why you build the fallback at all.
Failing open admits what the limiter cannot count, so the API stays up and a caller can exceed its limit for a while. Use it where the limit guards fairness or capacity you can lose for seconds.
Failing closed refuses it, so nothing uncounted passes and honest callers see errors. Use it where one caller could do real damage: a password check, a paid call.
Curveballs
"Pricing plans change, and a new limit must apply without a deploy." Rules loaded at startup would take a restart to change, so they move to a coordination service that servers watch, as Chapter 5's Leader Election and Consensus describes, beside the path and never on it. The server already passes capacity and refill with each check, so the store holds no rules and nothing there changes. No bucket is reset, and lowering a limit clamps the tokens down to the new capacity. Servers can disagree for the seconds the news takes to reach them, and you say so.
"We're being flooded from a hundred thousand addresses." This limiter counts API keys, and a botnet has none or many. It is the wrong layer, and it sits behind work already spent. Refuse the flood at the edge by address and pattern, which Networking Deep Dive's lesson on DDoS covers, and give traffic with no key no bucket here, so that a request with no key never costs the store a call. A sign-in route that takes no key keeps its own guess limit, by address and account, which is Backend Deep Dive's lesson on rate limiting and backpressure.
"One customer buys a single limit across two regions." A check in a home region in US east is about 85 milliseconds from western Europe, seventeen times the budget. So split the limit into a share for each region, set from recent traffic, say 700 and 300 of 1,000 a second, and reset every 10 seconds. The cost is under-admission for up to 10 seconds after traffic shifts: one region refuses while the other leaves tokens unused. A summed counter per region, from Chapter 4's Concurrent Writes and Conflicts, reports the total but cannot refuse on time, because the total arrives after the requests have gone through.
"Clients keep hammering after a 429. What do you tell them?" A true wait, in Retry-After, worked out from the bucket: the tokens short, over the refill rate, in whole seconds. A true wait spreads clients out, where a fixed window lines them up on the minute. A client's own parallel calls all get the same wait, so its retry adds jitter, a small random delay, and it can still be refused. Keep the two statuses apart as well. A 429 says the caller was the reason and a 503 says the service was, the two refusals Chapter 6's Backpressure and Load Shedding sends at the door. A client on the default limit that ignores the wait anyway meets the cached "denied until", which costs the store almost nothing.
How Each Level Answers
At mid level, a candidate reaches a shared store from a local bucket with some prompting, does the arithmetic to 80,000 checks, and fixes the race once it is pointed out. They need a question before they say what happens when the store dies.
A senior candidate asks what the limit protects before counting anything. They raise the race and the store's failure unprompted, give the hop against the budget, state the overshoot as a number, and set the failure policy route by route.
At staff, the limit becomes a product promise: which plan buys what, and how a change rolls out without surprising a customer. They ask whether the limiter protects capacity or stands in for planning it, and they keep metering off its path.
- Reciting algorithms with no agreed requirement to choose between them. The interviewer hears a list and asks which one, and why.
- Taking the flood as a bigger limiter, and adding store nodes for traffic that has no key. The bill grows and the flood is untouched.
- Solving the global limit with one global counter, then being asked for the round trip. The answer is seventeen times the budget.
- Saying "accurate enough" without the number and the direction of the error. The interviewer cannot tell whether customers lose out or the API does.
- Each algorithm described by the exact way it is wrong, with a number.
- An error with a direction: over-admitting or under-admitting, and by how much.
- A curveball the limiter should not solve, handed to the layer that should.
Knowledge Check
"We're being flooded from a hundred thousand addresses." What is your best move?
- Add store nodes until the limiter can count every request in the flood
- Lower every plan's limit until the flood falls under what the API can take
- Refuse it at the edge by address, and give traffic with no key no bucket
- Key the buckets by address instead, so that each gets 100 a minute from now on
"Pricing plans change, and a new limit must apply without a deploy." What do you do?
- Keep rules in a watched coordination service, and send them with each check
- Keep each rule beside its bucket, and rewrite the buckets when a plan changes
- Reset every bucket on the plan, so that the new limit starts clean for each key
- Ask the coordination service for the rule on every check that any server runs
"One customer buys a single limit across two regions." What does splitting it into shares give up?
- About 85 ms on every check made from the region far from home
- A hard ceiling, since the regions can admit more than the limit in total
- Up to 10 seconds of needless refusals after traffic shifts between regions
- Any refusal on time, because the counts are only summed after the fact
"Clients keep hammering after a 429. What do you tell them?"
- A fixed wait of one minute for everyone, so that they all stay away
- The same refusal as a 503, so that polite clients wait for longer
- The tokens they have left, so that each works out its own retries
- A Retry-After from the bucket: tokens short over refill, in whole seconds
You got correct