Systemsfor Aravinda
0 / 78 core
Week 6 · Reliability

Rate limiting

2 hours · core path

Read first: Load balancing, Caching

In one sitting

A limit is a decision to reject work before a scarce dependency falls over. Token buckets allow a measured burst, leaky buckets smooth the output, and a fixed window double-admits at the minute boundary. Login guesses need a shared counter, while a flash sale needs a cap sized to the inventory path.

A rate limit is a polite way to drop work. You decide, before the expensive part runs, that this caller has had enough, or that this dependency cannot take another call. Without that decision the dependency makes it for you, by getting slow, then timing out, then taking the callers down with it.

The shape of the limiter has to match the thing you are protecting. A password guess and a checkout during a sale are both “too many requests.” They are not the same problem, and one shared rule will get one of them wrong.

Core concepts

Start from the scarce resource, then pick the algorithm. The resource might be a credential (this account’s password), a machine (CPU spent on password hashing), or a downstream system (one hot inventory row). The algorithm is how you count. The placement is where the count is allowed to say no.

Token bucket. Picture a bucket that holds at most B tokens, the burst. Tokens arrive at R per second and are thrown away once the bucket is full. Each admitted request spends one token. If the bucket is empty, you reject. After a quiet stretch the bucket is full, so the next B requests pass at once, and after that you are limited to R. The burst is a feature when a real spike is short and the dependency can absorb it. The burst is a bug if you set B to something the dependency cannot actually do.

Leaky bucket. Requests fall into a queue that drains at a fixed rate R. The dependency is served at R and never faster. If the queue has a bound and the bound is full, the new request is rejected instead of queued. Load shedding is what you are doing at that bound. The output has no spike. A leaky bucket is how you protect a dependency that falls over when the input is uneven, even if the average would have been fine. The cost is that a legitimate burst waits, or gets rejected, even though the next second would have had spare capacity.

Fixed window. A counter sits next to a clock bucket, often one minute. It starts at zero when the minute starts and resets when the minute ends. The rule is “N per window.” It is one integer, and it is wrong at the boundary. The counter does not remember the previous window, so a client can spend N in the last instant of minute one and N again in the first instant of minute two. You wrote down N per minute. You admitted 2N in a fraction of a second. That double burst lands on the dependency at the worst moment, which is any moment you are already near the cap.

Sliding window. Count the requests whose timestamps fall in the last T, not in the current clock bucket. The burst at the end of the minute is still inside the window when the next burst arrives, so the second burst is rejected. You can keep every timestamp, which is exact and costs memory, or you can approximate it with two counters. Call the previous window’s count P and the current window’s count C. If you are a fraction f of the way through the current window, the weight still overlapping a lookback of one window is (1 - f). The estimate is C + P × (1 - f). That is a derivation of a common approximation, not a law. At the boundary f is near zero, so the estimate is about C + P, and a client who already spent the budget cannot spend it again. A token bucket is the other honest version. Both remember the recent past. A fixed window does not.

Where you enforce it. Say no where the “no” is cheap and where you still know what is scarce. At the edge, an API gateway can refuse an obvious flood before it consumes an application thread. The edge is the right place for abuse: a single address hammering login, a key that is already over its daily quota, a route that should never see more than a trickle. The edge is the wrong place to pretend it understands every dependency. A checkout and a product-page read are not the same cost, and the gateway does not know that unless the service told it.

Inside the service, put the limit in front of the scarce call. The inventory write, the password verifier, the payment provider. The service is the code that knows this call is the expensive one. Many systems do both. The edge sheds abuse. The service sheds work its own dependency cannot take. A single global number at the edge is not a substitute for the second limit.

Shared counter or local counter. A distributed limiter keeps one counter in a shared store. Every instance reads and updates it, so the fleet agrees on the cap. The price is a round trip on the decision. Jeff Dean’s teaching number for a round trip in the same datacenter is 0.5 ms, and a real store will add its own work on top. Budget a fraction of a millisecond to around a millisecond inside one region, and measure the store you have. That hop is noise on a login. It is a design question on a path you were trying to keep under a few milliseconds.

A local limiter keeps the bucket in the process. The decision is a memory read. It is also approximate. Ten instances each allowing 10 per second allow about 100 per second, and the approximation gets worse as you autoscale, because the cap grew when you added machines. The usual pattern is both: a local bucket absorbs bursts and stops a single process from over-granting, and a shared bucket holds the cap you actually mean. You must write down how wrong the local view is allowed to be. That error is the overshoot.

flowchart LR
  client[Client]
  edge[Edge abuse limit]
  login[Login service]
  account[Shared account counter]
  checkout[Checkout service]
  bucket[Checkout token bucket]
  stock[Inventory database]
  client --> edge
  edge --> login
  login --> account
  edge --> checkout
  checkout --> bucket
  bucket --> stock

Login traffic and sale traffic can share an edge and still need different counters. The account counter is there so guesses do not scale with the number of login servers. The checkout bucket is there so the sale stops at the inventory rate, not at whatever the edge happened to allow.

A worked example

Three numbers, three different mistakes. Assumptions are marked as assumptions.

The boundary. You publish “60 requests per minute” and implement it as a fixed window. A client sends 60 requests at t = 59.5 s and 60 more at t = 60.5 s.

window = 60 s, limit = 60
t = 59.5 s    60 allowed, window 1 counter hits 60
t = 60.0 s    counter resets
t = 60.5 s    60 allowed, window 2 counter hits 60
elapsed       1.0 s
admitted      120
rate in that second = 120 per second
the rate you described = 60 per minute = 1 per second

A token bucket with the same average and the same burst does not do this. Set R = 1 token per second and B = 60. The first burst spends the bucket down to zero. One second later the refill is 1 token.

R = 1 token/s, B = 60
after the first burst, tokens = 0
refill during 1 s = 1
second burst allowed = 1
second burst rejected = 59

The sliding-window approximation tells the same story. Previous window P = 60, current window C = 60, and at t = 60.5 s you are f = 0.5/60 of the way into the new window.

weight of the previous window = 1 - f = 1 - 0.5/60 = 0.9917
estimate = 60 + 60 * 0.9917 = 119.5
limit = 60
119.5 is over the limit, so the second burst is rejected

Login attempts. Assume a steady day of 1,000,000 login requests. A day is 86,400 seconds, so the average is 1e6 / 86400 ≈ 11.6 per second, about 12. The attack is not the average. Assume 50,000 guesses arrive in one minute, spread across many source addresses and aimed at a small set of accounts.

1 day = 86,400 s
1e6 / 86400 ≈ 11.6 rps average
50,000 guesses / 60 s ≈ 833 rps during the minute
833 / 12 ≈ 69 times the average

A cap tuned to 12 per second does not describe this minute, and a cap tuned to 833 per second does not protect an account. The key has to be the account. Assume 20 login servers and a local limit of 5 attempts per account per 15 minutes, which is a policy assumption for “a human can mistype a password.”

local limit per instance = 5
instances = 20
guesses that actually land = 20 * 5 = 100
shared limit = 5
guesses that land = 5

The local limiter did not fail open. It failed multiplied. Each process told the truth about its own memory and lied about the account. Password verification is intentionally expensive CPU, so you also want the counter checked before you do that work. A limit that runs after the hash has already spent the resource it was meant to save. And the counter has to be the shared one. Paying about a millisecond for the store is cheap next to a hash, and it is cheap next to an extra 95 guesses.

If the shared store is down, fail closed on login. You will refuse legitimate users for the outage, which is a real cost. The alternative is unlimited guesses for the same outage. That is the wrong side to be wrong on for a credential.

A flash sale. Assume the inventory path stays healthy at 400 successful checkouts per second, and that this is a load-test result you are treating as the cap. If you have not measured it, say it is an assumption. At the open, 2,000 checkout attempts per second arrive for 30 seconds. Most of them are real customers. A tight per-address limit is the wrong tool: a lot of those customers share a carrier-grade address, and the attackers you do have will show up with many addresses anyway. The product page can be served from a cache. The checkout cannot. The bucket belongs on checkout.

Use a token bucket with R = 400 per second and B = 400, one second of slack so the opening instant is not a cliff.

offered = 2,000 rps for 30 s
R = 400 per second, B = 400
first second admits the burst, then the bucket is empty
steady admission = 400 rps
steady rejection = 1,600 rps
admitted over 30 s = 400 * 30 = 12,000
rejected over 30 s = 1,600 * 30 = 48,000

A leaky bucket with the same R and no burst would also admit 400 per second, but the opening second would queue or drop the spike instead of letting 400 through immediately. If the dependency can take a one-second lump and cannot take a sustained 2,000, the token bucket matches the dependency and the leaky bucket is stricter than you need. If the dependency falls over on any lump, even a short one, smooth it.

The rejection has to be cheap, and it has to be a distinct answer, not a crash. Clients that treat it as “try again immediately” recreate the load you just removed. Three immediate retries of each rejection, with the new arrivals still coming, is a different offered rate. Retries, backoff, and circuit breakers is the rest of that failure.

rejected = 1,600 rps
immediate retries = 3
retry load = 4,800 rps
next second if new arrivals hold = 2,000 + 4,800 = 6,800 rps

The limiter was right. The client policy undid it. Return a clear rejection and make the client wait.

Tradeoffs

Choice What you gain What you spend
Fixed window One counter and a clock bucket A 2x burst at every boundary, which is the moment you are most full
Token bucket A true average rate plus a burst you chose A bad B either clips real users or knocks over the dependency
Leaky bucket Output that never spikes past R Legitimate bursts wait or die even when the next second was free
Sliding window No boundary double-admit More state than an integer, or an approximation you must explain
Local bucket A decision with no network hop The real cap is about N times the limit you wrote down
Shared counter The fleet agrees on one cap A round trip, and a hot key if every request hits one counter
Edge limit Abuse dies before an app thread The edge does not know which dependency is scarce
Limit before the expensive work The protected CPU or database does not do the rejected work You need a key you can read before that work, such as account id
Fail closed when the counter store is down Login guesses stay capped during the outage Real users are locked out for the same outage
Fail toward a small local cap The sale stays up if the store blips You accept the overshoot above, and you must alarm on it

Pitfalls

  • Implementing “N per minute” as a fixed window and discovering the dependency dies at the top of the minute. The symptom is a latency spike that lines up with the clock, twice the allowed rate, lasting a few hundred milliseconds.
  • A per-process login limit. The symptom is a credential-stuffing run that succeeds as you scale out, because scale-out raised the number of guesses.
  • Checking the password before the limit. CPU saturates, the limiter’s graphs look calm, and the accounts are still being guessed.
  • Keying a flash sale only by client address. Real buyers behind one address get rejected, and a botnet with a million addresses does not.
  • One global edge number for every route. The cheap cached read consumes the budget and the checkout is rejected, or the reverse, and the scarce database is unprotected either way.
  • Returning a generic failure for a limit. Clients and on-call both treat it as a bug and retry harder. A distinct rejection is part of the mechanism.
  • A shared counter with no story for store failure. Login that fails open has no limit. A sale that fails closed turns a counter outage into a full outage.
  • An approximate local grant on a security limit. The overshoot math that is fine for inventory is extra guesses for an account.

In the interview

Say the scarce resource in the first sentence. “Login is a shared per-account token bucket, checked before the password work, and it fails closed. Checkout is a token bucket at 400 per second in front of inventory, and the edge only handles abuse.” That is a path, a number, and a tradeoff.

Name the boundary bug before they do. “I would not use a fixed window, because 60 at the end of the minute and 60 at the start are 120 in one second.” Interviewers who ask about rate limits are often checking whether you know that.

Say whether the counter is shared. If you forget, the follow-up is “you have 20 servers, what is the real limit?” The answer is the local limit times 20, unless the counter is shared.

Skip the brand of the store and the exact command. Skip a lecture on every algorithm. Token bucket, why not a fixed window, where it runs, shared or local. If they push, give the leaky bucket as the version you use when the dependency cannot take a burst, and give the overshoot arithmetic for the approximate shared limiter.

The question that usually follows is the sale and the login in the same design. Do not give them one limiter. The keys are different, the fail-open choice is different, and the cost of a wrong “yes” is different.

Check yourself

A fixed window allows 100 requests per minute. A client sends 100 at 1 second before the reset and 100 at 1 second after. How many land, and in what interval?

All 200 land, and they land within about 2 seconds. The counter resets with the window, so it has forgotten the first 100. A limit you described as 100 per minute just admitted 200 at the boundary. A token bucket with a rate of 100 per minute and a burst of 100 would admit the first burst and then only the refill, which over those 2 seconds is a handful of tokens, not another 100.

Login is limited to 5 attempts per account per 15 minutes, enforced in process. There are 30 instances. How many guesses can one account receive, and what would you change?

About 150. Each instance keeps its own 5, and the attacker is free to spread guesses across the fleet. Move the counter to a shared store keyed by account, and check it before the password verification. Fail closed if that store is unreachable. The extra round trip is the cost of the limit meaning what you wrote down.

The inventory path handles 400 checkouts per second. The sale opens at 2,000 per second. Why is a token bucket a better fit than a leaky bucket here, and what did you assume?

The assumption is that 400 at once for a short burst is survivable and 2,000 sustained is not. A token bucket with rate 400 and a burst on the order of 400 admits the opening lump and then holds the line. A leaky bucket holds the line too, but it also refuses the lump, which adds delay or rejections the dependency had spare capacity for. If a lump of any size knocks the database over, the assumption is false and you want the leaky bucket instead.

The shared limiter store fails during a password-stuffing run and during a flash sale. Which path fails closed, which degrades to a local cap, and why?

Login fails closed. A store outage that fails open is unlimited guesses, and that is worse than a temporary lockout. The sale can degrade to a small per-instance cap so you do not turn a counter blip into a down checkout, as long as you know the overshoot is instances times the local grant and you can absorb it. The difference is what a wrong yes costs: a stolen account, or a few hundred extra checkouts.

Based on: Marc Brooker, AWS Builders' Library; Google SRE book; Jeff Dean, Numbers Everyone Should Know.