Systemsfor Aravinda
0 / 78 core
Week 9 · Case studies

Design a rate limiter

1.5 hours · core path

Read first: Rate limiting

In one sitting

Enforce a token bucket where you can afford to say no, locally for a coarse abuse cap and in a shared store for a billed quota. The store must update that bucket atomically, or two requests will both see one token and both pass. If the store is down, failing open means the limit quietly disappears.

A rate limit is a bucket of tokens with a home. The home decides whether the number is true across the fleet or only a local guess. The bucket decides whether a short burst is allowed. The bug that reaches production is a read-modify-write on the counter: two requests both observe one token and both pass. After that, the design is where you put the check, and what you do when the store behind the counter is down.

Requirements

The user of this system is another service, and behind it a customer with an API key. The human in the story only sees a fast success or a clear “slow down.”

Functional requirements:

  • Given a key and a rule, decide allow or deny before the request spends the scarce thing you are protecting.
  • A rule is a sustained rate plus a burst. A page load that fires twenty calls at once should succeed if the customer is otherwise idle. A tight loop should not.
  • The deny tells the caller to wait. It includes a retry-after hint. It does not look like a server error.
  • You can change a customer’s limit without a deploy. The next check observes the new rule.
  • You can run a coarse per-address cap and a billed per-key cap at the same time. They are different limits.

Non-goals:

  • A global perfectly fair queue across every customer. You are saying no, not scheduling their work.
  • Exact limits across regions. This design is one region. A cross-region check on every request spends a fiber round trip to save a counter.
  • Stopping a determined attacker who can steal many API keys. That is abuse response. The limiter is the cheap no.
  • Billing. The limiter does not compute an invoice. It stops a key from exceeding the plan you already sold.

Product assumption: the allow-or-deny decision has a budget of 2 ms at p99 inside the region. A check that costs 20 ms has already become a bigger problem than the traffic it refuses.

Estimation

Assumptions you say out loud:

  • 40 million API requests per day across all keys.
  • The peak is 5 times the average, for the busy part of the business day. That multiplier is an assumption.
  • 100,000 keys have a configured limit. Most of them are idle most of the time. Assumption.
  • A bucket’s state is two integers and a rule id, on the order of 32 bytes. Assumption.
  • One partner key is allowed to send hard. You will use that as a second case, not as the average.

A day is 86,400 seconds. Use 1e5 in the sketch, then show the exact division.

40,000,000 / 86400 = 463 requests per second average
40,000,000 / 1e5   = 400 requests per second shortcut
peak, 5x assumption = about 2,300 requests per second
100,000 keys * 32 bytes = about 3 MB of bucket state

The shortcut is about 14 percent under the exact average, since you divided by a round 100,000 instead of 86,400. Four hundred per second and 463 per second are the same design. One million requests a day would be about 12 per second. You are bigger than that and still tiny as a dataset.

3 MB fits in one process with room to spare. Bandwidth of the check is a few hundred bytes in each direction, so at 2,300 per second you are moving under a megabyte per second. Disk is not in this story if the store keeps the live buckets in memory and only snapshots rules. The estimate’s conclusion is the point: you are not sizing a cluster. You are placing an atomic update and deciding what a miss of that update means.

Second case, still an assumption the interviewer is allowed to hand you. One partner key is permitted 5,000 requests per second and actually sends them. Average math hid that key. Your 2,300 per second fleet number is not the ceiling that matters anymore. The ceiling is how fast one counter can be updated, because every one of those 5,000 requests has to touch the same key.

High-level design

flowchart LR
  client[Client] --> edge[Edge gateway]
  edge --> abuse[Local abuse bucket]
  edge --> quota[Shared token bucket]
  quota --> api[API service]
  api --> dep[Dependency bucket]
  dep --> scarce[Scarce dependency]

Three checks, three homes. They are not one box you clone.

The edge gateway sees the request first. Before it spends application CPU, a local token bucket caps an obvious flood from one address. That bucket lives in the gateway process. It is approximate and it is supposed to be.

After the key is authenticated, the billed limit is a token bucket in a shared store, one record per API key. Every gateway and every API process consults that record. This is the number the contract means.

Inside the API process, in front of a scarce dependency such as a search cluster or a paid third party, a third bucket caps what you are willing to send downstream. The edge does not know that this particular route costs a hundred times more than a health check. The service does. Rate limiting belongs at the edge for abuse and in the service for the scarce thing. Doing both is normal. Doing only the edge one and calling it the design leaves the dependency naked.

The shared store is an in-memory table with an atomic update per key. The name of the product is not the design. The design is “one key, one atomic refill-and-take, in the same region as the gateway.” A same-datacenter round trip on Dean’s list is 0.5 ms. One of those fits in a 2 ms budget. A check that hops to another region does not. Keep the buckets next to the gateways.

Rules live in a small table the store reads: key, rate per second, burst capacity, and a version. Changing a customer’s plan updates that row. The next atomic check uses the new rate. You do not roll the gateways.

Deep dive

The token bucket

A bucket has a capacity, the burst, and a refill rate. Each allow spends one token. If the bucket is empty, you deny. Time puts tokens back, up to the capacity, whether or not anyone is asking.

On each check you need the tokens left and the last time you refilled. Elapsed time times the rate is the number of new tokens, capped at capacity. Then, if at least one token is present, you subtract one and allow. If not, you deny and you leave the bucket empty. A customer who was idle is allowed to spend the whole burst at once, which is what a page load needs. A customer who keeps going is then limited to the refill rate.

Do that math in the store, on the store’s clock. If each gateway computes elapsed time on its own clock and writes the result back, a gateway whose clock is ahead refills early and over-admits. The gateway should send “take one token for this key, and here is the rule version I believe.” The store applies the rule it has, refills from its own clock, and returns allow or deny plus a wait hint.

A fixed window is the version you should be able to reject. A counter that resets every minute allows 100 requests at the last second of minute one and 100 more at the first second of minute two. The caller sent 200 in about two seconds, and the window said both batches were legal. A token bucket with a rate of 100 per minute and a burst of 100 allows the first batch and then refills slowly. The second batch waits. A sliding window is the other honest fix. A counter that resets on the minute is the easy wrong one.

A leaky bucket is a different tool. Requests queue and drain at a fixed rate, so the thing behind it sees a smooth stream and no burst. That is what you want in front of a dependency that hates spikes. It is a poor customer-facing API limit, because a legitimate burst of twenty calls would either queue or fail. Use a token bucket for the customer’s plan. Use a leaky bucket, or a token bucket with a small burst, in front of the scarce dependency. Bound that queue. An unbounded queue in front of a slow dependency is a memory leak.

The deny is a 429 with a retry-after, not a 500. Clients that treat 500 as “try again immediately” will hammer you. Clients that honor retry-after wait. Your own retries must not immediately replay a deny. A retry of a deny is more load, at the moment you asked for less.

Where it sits, shared versus local

A shared bucket is correct across the fleet and costs a round trip. At a few thousand checks per second, one store in the region is enough. Partition the store by key only when one store’s CPU is actually the limit. Most keys are idle, so the hotness is uneven, but the dataset is megabytes.

A local bucket is a few instructions and no network. Each gateway allows rate / N if you split the limit evenly, or the full rate if you are only trying to catch a broken client that stuck to one machine. Both readings are approximate. A client that spreads across ten gateways and a local full-rate bucket gets about ten times the limit. A client that sticks to one gateway and a split bucket is limited to rate / N, which is stricter than the contract. A deploy that starts a new gateway also starts a full bucket, so a rolling restart grants a burst.

That approximation is acceptable for the per-address abuse cap. It is not acceptable for the billed quota. Customers notice when the documented limit is a suggestion. The abuse cap can fail slightly open. The quota should not.

Many systems run both on purpose. The local abuse bucket sheds a flood before it touches the shared store, which keeps the store’s CPU for real keys. The shared bucket enforces the plan. The dependency bucket protects one downstream system and can be local if there is a single process, or shared if many API processes all call the same dependency. Write those three sentences on the diagram so the boxes are not decorative.

The race on the counter

Start with one token in the bucket. Request A and request B both read it. Both compute “one token available.” Both write zero. Both are allowed. You admitted two requests on a limit that had room for one. With higher concurrency the over-admit is the concurrency, not a rounding error. An attacker who sends a wide parallel burst gets a multiple of the limit equal to how many reads overlap.

The fix is that refill and subtract happen as one atomic update. A compare-and-set is enough. Read the version, the token count, and the timestamp. Compute the refilled count. If it is at least one, write the decremented count with a new version only if the version is still the one you read. If the version changed, someone else took a token. Retry the operation. If the refilled count is below one, deny. No gateway does this read-modify-write in its own memory and then writes the result back.

A lost response is the subtle case. The store applied the decrement and the reply died. The client retries the request, and a naive retry takes a second token. If the API call itself is idempotent, retrying it is fine and taking a second token is the wrong charge against the budget. If you can, key the take by a request id for a short window so a retry of the same request does not spend a second token. If you cannot, say that a timed-out allow may have spent a token and the retry may spend another. Do not hide that. It is a small over-admit on the failure path, which is much smaller than the race on the success path.

One key is still a single serialized update inside the store, even when the update is atomic. Clients wait in parallel, so the round trip is not the throughput ceiling. The ceiling is how fast the store can apply updates to that one key. If an apply takes 0.2 ms of time on the key’s lock, that key does about 5,000 takes per second. That number is a derivation from the apply time, and the apply time is something you measure, not something you memorize. The partner key at 5,000 per second sits on that ceiling. If they need more, you split the bucket into K sub-buckets, each with rate / K and burst / K, and you hash the request onto one. You just reintroduced approximation, on purpose, for one key. Say so. Do not split every key because one partner is large.

Tradeoffs

Choice What you gain What you spend
Shared atomic bucket The billed limit is true across every gateway A round trip, and a store you must operate
Local bucket Microseconds, and it works when the store is down A client can get about N times the limit, or a deploy grants a fresh burst
Token bucket A defined burst, then a steady rate, with no minute-boundary cheat You store a timestamp and a level, not just a counter
Fixed window Trivial to explain and to code Two bursts, one on each side of the boundary, both legal
Fail closed when the store is down A dead counter cannot mean unlimited traffic You refuse good requests during a store outage
Fail open Availability of the API survives a limiter outage The outage deletes the limit, including for a key that was already over

Fail closed versus fail open is the tradeoff interviewers remember. Pick it per limit, not once for the system.

Failure modes

  • Shared store down. If the billed quota fails open, every key is unlimited until the store returns, which is how a dependency dies during a counter outage. Fail closed for the quota, or fall back to a local bucket at rate / N and accept a rough limit for the duration. The abuse cap is already local, so it keeps working. A limiter outage should not be a worse incident than the abuse it was there to stop, and it should not be a silent removal of every contract.
  • Store restart with empty buckets. Every key is suddenly full and the whole fleet spends a burst together. Persist the levels, or accept one burst on restart and make the capacity small enough that the burst is survivable. A capacity of “an hour of traffic” granted all at once is a self-inflicted stampede. Keep the burst at the size of a real page load, not at the size of a billing period.
  • The race you thought you fixed, left in one path. Symptom: a customer exceeds the limit only when their client is highly parallel, and a single-threaded test passes. The atomic update is missing on one route, often the one added later. The same test should send a parallel burst of size equal to the burst plus a handful and expect the handful to be denied.
  • Hot key. One partner’s takes queue on one record. Latency of the check climbs only for that key, then for everyone if the store’s threads are stuck on it. Split that key, or give it a local limiter and a higher budget, on purpose.
  • Retry storm. Clients treat a 429 like a 500 and retry immediately. Your QPS rises when you tried to cut it. Retry-after, and your own client library has to honor it. A load shed at the gateway, a cheap deny when the process is past a concurrency cap, is the backstop if the limiter itself is the thing getting slow.
  • Clock steps on the store. A backward step stops refill until real time catches the stored timestamp. A forward step grants a lump of tokens. Run the store on a clock you do not step by minutes, and clamp a single refill to the burst capacity, which you already do. The clamp is what keeps a bad timestamp from issuing a huge grant.
  • Rule and level disagree. You tightened the rate but the stored level is still a large number, so the customer keeps the old burst. On a rule-version change, cap the stored level at the new capacity inside the same atomic update.

In the interview

In the first five minutes, ask what you are protecting and whose number must be exact. An abuse cap at the edge can be local. A billed API key has to be a shared token bucket with an atomic update. Put a third bucket in front of the expensive dependency and say why the edge cannot see that cost. Give the QPS: about 400 per second with the shortcut, a few thousand at a 5 times peak, a few megabytes of state. The bottleneck is not disk. It is the race, and then one hot key.

Skip a worldwide consistent limit and any product pitch about dashboards. Name the fixed-window bug in one sentence so they know you picked the token bucket for a reason.

The question that follows is usually “the store is down” or “two requests read the same token.” For the race, walk the compare-and-set. For the outage, fail closed on the quota and keep the local abuse cap. The tradeoff you admit is that a local fallback during an outage is approximate, and a hard fail closed turns a limiter bug into an API outage. You chose, for the billed number, not to fail open.

Check yourself

A bucket has one token left. Two gateways both read it and both allow the request. What did they fail to do?

They treated the counter as a value you can read, change, and write back from the application. Those reads overlapped, so each one saw the last token and each one spent it. Refill and subtract have to be one atomic update on that key, with a compare-and-set or a single store command. The loser retries the update and then gets a deny.

Why is a local bucket acceptable for a per-address abuse cap and a poor fit for a billed API quota?

The abuse cap is a coarse cheap no. If a client spreads across ten gateways and gets about ten times a small cap, you still stopped an unbounded flood, and you spent no round trip. A billed quota is a contract. The same spread turns 100 requests per second into about 1,000, and a deploy that starts empty local buckets grants a fresh burst. That number has to live in one shared record.

What is 40 million checks a day at peak if you assume a 5 times peak, and why is storage not the sizing problem?

40 million divided by 86,400 is about 463 per second. The 1e5 shortcut gives 400. Five times the exact average is about 2,300 per second. One hundred thousand buckets at a few dozen bytes is a handful of megabytes. The data fits in memory. The design is the atomic update and the hot key, not a disk layout.

A limit is 100 requests per minute using a counter that resets at the top of each minute. How does a client send about 200 in two seconds without ever being denied?

It sends 100 at the end of one minute and 100 at the start of the next. Each window is legal on its own. The two windows together are a burst the limit was supposed to describe. A token bucket with a burst of 100 and a rate of 100 per minute allows the first batch and then has to refill before it allows more.

The shared quota store is unreachable. Why is failing open the dangerous default?

Failing open means every key is unlimited for the length of the outage, so the thing the limiter was protecting gets the full unbound traffic at the moment your control plane is already sick. Fail closed refuses work you cannot account for. A local fallback at roughly rate divided by the number of gateways is the middle path, and you should call it approximate.

Based on: Marc Brooker and the AWS Builders' Library; Google SRE book and SRE workbook; Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.