Distributed patterns and operations
Rate limiting algorithms
Compare token bucket, leaky bucket and the three window algorithms, and decide where a limit should be enforced and what the client should be told.
The problem
A team runs a public REST API. About 2,000 customers share one fleet of app servers and one PostgreSQL cluster, and normal traffic is around 800 requests per second. One afternoon a customer deploys a sync job with a bug: when a call fails it retries immediately, in a loop, from 40 worker threads. Within a minute that one customer is sending 6,000 requests per second. The database connection pool fills, latency climbs for everybody, and other customers’ timeouts set off their own retries. One client’s bug has become an outage for 2,000.
The first responses are the obvious ones. The team adds servers, which moves the bottleneck to the database. They block the customer’s IP address by hand, which takes twenty minutes and stops working when the job moves to another host.
What they need is a rule that the system applies by itself, on every request, before the expensive work starts: each caller gets a stated share of capacity, and requests beyond it are refused quickly and cheaply. That is a rate limiter. Teams use the same mechanism for fairness between tenants, for capping calls that cost money (SMS, third-party APIs), and for slowing brute-force attempts on login endpoints.
The hard part is deciding how to count. Five algorithms cover almost everything you will meet, and they differ in memory, burst behaviour and accuracy.
Token bucket
Each caller has a bucket that holds up to B tokens. Tokens are added at a steady rate of r per second, and a full bucket stays full. A request takes one token. If there is no token, the request is rejected.
The refill rate r is the long-run average you allow. The capacity B is the largest burst you accept at once. With r = 10 and B = 50, an idle client can send 50 requests at once and is then held to 10 per second.
Nothing has to run in the background. Store two values per key, the token count and the time of the last update, and on each request compute tokens = min(B, tokens + elapsed * r) before deciding. Expensive operations can cost several tokens. This mix of low cost and tolerance for honest bursts makes token bucket the common default: Amazon API Gateway documents its throttling as a token bucket, and Stripe has described using one for its API.
Leaky bucket
Picture a bucket with a hole in the bottom. Requests pour in at any rate and leave at a fixed rate. In the classic form the bucket is a bounded first-in, first-out queue: requests are taken off it at r per second, and a request that arrives when the queue is full is dropped.
The output is smooth, which is what you want in front of a fragile downstream that can take 100 writes per second and not 150. The price is delay: a burst waits in the queue, and old requests hold up fresh ones. NGINX’s limit_req module uses this method. With a burst setting, excess requests are queued and released at the configured rate, and rejected once the queue is full.
Send a burst larger than the bucket size through both limiters and compare them: the token bucket passes the burst at once and then throttles, while the leaky bucket releases requests at a steady drip.
Fixed window counter
Divide time into windows, say one per clock minute, and keep one counter per key per window. Increment it on each request and reject once it passes the limit. In Redis this is an INCR on a key such as rl:user42:12:01, plus an expiry.
It is the cheapest scheme, one integer per key. Its flaw is at the edges of the window.
Step 1 of 8
The rule is 100 requests per minute for each API key. A fixed window limiter keeps one counter per clock minute and starts again from zero when the minute changes.
Read the steps as text
- The rule is 100 requests per minute for each API key. A fixed window limiter keeps one counter per clock minute and starts again from zero when the minute changes.
- The client stays quiet for most of the minute. At 12:00:59 it sends 100 requests at once. The counter climbs from 0 to 100, every request is within the limit, and all of them reach the API.
- One second later the clock reads 12:01:00. That is a new window with a new counter at zero. Nothing in the limiter remembers what happened a second ago.
- The client sends another 100 requests. The new counter climbs from 0 to 100, and all of them are allowed too.
- The API has now taken 200 requests in about two seconds, twice what the rule was meant to allow. The limiter followed its rule exactly. The rule is the problem.
- A sliding window counter replays the same traffic differently. It keeps the previous window's count as well, weights it by how much of that window still overlaps the last 60 seconds, and adds the current count.
- At 12:01:00 almost all of the previous window still overlaps, so the estimate is already about 100. The second burst is rejected with status 429, and capacity returns gradually as the old window slides out of view.
- Fixed windows cost one counter per key but can let through twice the limit across a boundary. A sliding window counter closes that gap for the price of one extra number per key.
Fixed windows also synchronise clients: everyone who was blocked becomes unblocked at the same instant, and they all arrive together.
Sliding window log
Store the timestamp of every request, per key, in a sorted set. On each request, delete the timestamps older than the window, count what remains, and allow the request if the count is below the limit.
This is exact: “no more than 100 in any 60 seconds” means precisely that. The cost is memory in proportion to the limit. A limit of 1,000 per hour across a million active keys can mean a billion stored timestamps. Use it when limits are small and precision matters, such as five login attempts per fifteen minutes.
Sliding window counter
This is a compromise that keeps two counters per key, the current fixed window and the previous one, and estimates the rolling count as:
current + previous * (share of the previous window still inside the last 60 s)
Take a limit of 100 per minute, with 80 requests in the previous minute and 30 so far in this one. At 15 seconds into the current minute, 75% of the previous window still overlaps. The estimate is 30 + 80 x 0.75 = 90, so the request is allowed.
The estimate assumes that the previous window’s requests were evenly spread. That is not exactly true, but the error is small in practice and the boundary burst disappears. Cloudflare described building its rate limiting on this approach in 2017.
Choosing between them
| Algorithm | Memory per key | Bursts | Choose it when |
|---|---|---|---|
| Token bucket | Two numbers | Allowed, up to the bucket size | General API limits; the usual default |
| Leaky bucket (queue) | A queue, up to the burst size | Smoothed into a steady rate, with delay | A downstream needs a constant rate |
| Fixed window | One counter | Up to twice the limit at a boundary | Coarse quotas where simplicity wins |
| Sliding window log | One entry per request | None beyond the limit | Small, strict limits such as logins |
| Sliding window counter | Two counters | Close to none | Large-scale limits that need good accuracy |
When not to reach for a rate limiter at all: it enforces a policy per caller, and it does not help when the total of legitimate demand exceeds capacity. That case needs load shedding and backpressure, which react to the health of the server and not to who is calling.
Where to enforce it
- Client. A well-behaved SDK paces itself and backs off when told to. That saves round trips, but you cannot depend on it, because you do not control every client.
- Edge and gateway. The API gateway is the usual home for per-key and per-IP limits. Rejection happens before any business logic runs, and one implementation covers every service behind it.
- Service. Only the service knows that an export costs 500 times more than a read, or that a plan allows 50 invoices per day. Limits tied to business meaning live here.
Most real systems use more than one layer. Choose the key with care too. An API key or user id is fairer than an IP address, because many users can share one address behind a corporate NAT or a mobile carrier.
Telling the client
Reject with 429 Too Many Requests and a Retry-After header that says how long to wait. Many APIs also send X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset on every response so that clients can pace themselves.
A client that receives a 429 should back off with jitter, or its retries become the next wave. See retries and timeouts.
Counting across many servers
With one gateway, counters can live in its memory. With twenty, a client whose requests are spread across them gets up to twenty times its limit unless the counters are shared. The standard design keeps the counters in Redis and makes each check atomic, with a single INCR or a Lua script. A separate read followed by a write lets two gateways both read 99 and both allow request 100.
Sharing adds a network round trip to every request and a dependency that can fail, so you have to decide whether to fail open (allow traffic while the counter store is down) or fail closed. Most general API limits fail open, and limits that protect security, such as login attempts, are safer failing closed. The rate limiter case study works through the full design, including local approximations and limits that span regions.
In the interview
Raise rate limiting yourself whenever a design has a public API, several tenants on shared infrastructure, or an endpoint that is expensive to serve.
A strong answer names an algorithm and its parameters and says why: “a token bucket per API key, refilling at 100 per second with a burst of 200, enforced at the gateway, with counters in Redis, returning 429 with Retry-After”. Then state one trade-off, such as failing open when Redis is unreachable, and say what the limiter does not cover, which is overload from legitimate traffic. If the interviewer pushes, explain the fixed window boundary problem and how a sliding window counter removes it for the price of one more counter.
Key takeaways
- A rate limiter refuses excess requests cheaply, before expensive work starts, so that one caller cannot take capacity from everyone else.
- Token bucket allows bursts up to the bucket size and enforces an average rate with two numbers per key. It is the usual default.
- A leaky bucket used as a queue smooths bursts into a constant output rate and pays for that with delay.
- A fixed window is the cheapest scheme and can let through up to twice the limit across a window boundary.
- A sliding window log is exact and stores every request. A sliding window counter approximates it with two counters.
- Enforce per-key limits at the gateway and business limits in the service, and answer with 429 and Retry-After.
- With many gateways the counters must be shared and updated atomically, and you must decide what happens when the counter store is down.
Try it
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What do the two parameters of a token bucket control?
The refill rate sets the long-run average rate allowed. The capacity sets the largest burst that can pass at once.
Token bucket and leaky bucket (as a queue): what is the key difference?
A token bucket lets a burst through immediately if tokens are available. A leaky bucket queues the burst and releases it at a constant rate, so the output is smooth but delayed.
What is the boundary problem with fixed window counters?
A client can use a full quota at the end of one window and another at the start of the next, so up to twice the limit passes in a short span.
How does a sliding window counter estimate the rolling count?
Current window count plus the previous window count multiplied by the fraction of the previous window that still falls inside the rolling period.
Which status code and header should a rate limited response carry?
429 Too Many Requests, with a Retry-After header saying how long to wait. Many APIs also send remaining-quota headers on every response.
The counter store is down. Fail open or fail closed?
Fail open (allow traffic) when availability matters more than strict limits, which suits most general API limits. Fail closed for limits that protect security, such as login attempts.