05. Reliability / Lesson 2 of 4
Rate Limiting
Say no to some requests so everyone else can get a yes.
- 10 min
- Intermediate
- 10 steps
- Allowed2,400/s (bad)
- Rejected0 (bad)
- Tokens left—
- Request
- Abuse
- Failed request
Step 1 of 10: One client can use up the whole server
Read every step as text
Step 1: One client can use up the whole server
Say the server can handle 1,000 requests a second. Normal users send about 400. Then one buggy script, or one scraper, starts sending 2,000 a second.
The total is
400 + 2,000 = 2,400a second, about 2.4 times what the server can do. Everyone's requests slow down or fail, including the people who did nothing wrong.A rate limiter protects a shared service from any one caller, by accident or on purpose.
Step 2: Fixed window: a counter that resets every minute
The simplest limiter keeps one counter per client per minute. Each request adds 1; if the counter is already at 100, the request is rejected. At the next minute a new counter starts at 0.
A client that sends 150 requests in one minute gets 100 through and 50 rejected. It needs one small number per client, so it is fast and cheap.
In Redis this is two commands: INCR the key, and EXPIRE it after 60 seconds.
Step 3: The edge of the window lets twice the limit through
A client sends 100 requests at 12:00:59. The minute ends, the counter resets, and at 12:01:00 it sends 100 more. Both windows are within the limit, so all 200 are allowed.
That is 200 requests in about 2 seconds, twice the limit the rule was meant to give, arriving as one spike.
Any fixed window can be gamed at its edge. If bursts matter, use one of the next three ideas.
Step 4: Sliding window: always look at the last 60 seconds
Instead of a clock minute, count the requests in the last 60 seconds from now. A sliding window log stores each request's time. At 12:01:00 it still sees the 100 requests from 12:00:59, so the second burst is rejected.
Storing 100 timestamps per client is costly. A sliding window counter keeps only two counts and weights the old one: 25% into a minute, with 100 in the last window and 20 in this one, it estimates
100 × 0.75 + 20 = 95.The counter version is a close estimate that uses almost no memory. Most big systems use it.
Step 5: Token bucket: spend a token for each request
A bucket holds up to 20 tokens and gets 5 new tokens every second. Each request takes one token; with none left, it is rejected. A quiet client saves up tokens and can burst 20 at once.
A client that tries 50 requests a second for 10 seconds sends 500. It gets
20 + 5 × 10 = 70through and 430 rejected. In the long run it gets 5 a second.Two numbers set the behaviour: the refill rate is the long-run speed, the bucket size is the biggest burst. Many APIs use this.
Step 6: Leaky bucket: a queue that drains at a steady speed
Requests join a queue of size 10, and the app takes them out at a fixed 5 a second, like water through a hole. When the queue is full, new requests are dropped.
A burst of 30 at one moment gives 10 queued and 20 dropped. The 10 queued leave over 2 seconds, so the app always sees a smooth stream.
Token bucket allows bursts; leaky bucket smooths them. Use leaky when the service behind it cannot take spikes, at the cost of added waiting.
Step 7: Put the limiter at the front door
Limit at the API gateway, before requests reach the app, so rejected requests cost almost nothing. With a limit of 50 requests a second per API key, the flood from step 1 is cut to 50.
The server now sees
400 + 50 = 450a second, well under 1,000, and 1,950 of the flood is rejected. Choose the key with care: per user or API key, per IP address for logged-out traffic, and stricter rules for costly routes such as login.Limits can stack: a loose limit for the whole API, and a tight one for login (say 5 tries a minute) to slow password guessing.
Step 8: With many gateways, the counter must be shared
A real gateway runs on several machines. If each keeps its own counter and a client's requests spread over 3 of them, each allows 100, so the client really gets 3 × 100 = 300.
Keep the counters in one shared place such as Redis, where the increment is atomic: two gateways cannot both read 99 and both allow the 100th. The cost is about a millisecond per request, and you must decide what happens if Redis is down: let requests in (fail open) or block them (fail closed).
Most public APIs fail open, because blocking every user is worse than a short period without limits. Login limits often fail closed.
Step 9: Tell the client: 429 Too Many Requests
A rejected request should get HTTP status 429, not a silent drop. Add a
Retry-Afterheader with the seconds to wait, so a polite client knows when to try again.Many APIs also send the limit and what is left in headers, so clients can slow down before they hit the wall. The names
X-RateLimit-LimitandX-RateLimit-Remainingare a common habit, not an official standard.A good client reads Retry-After and waits. A bad one retries at once, which is where the next lesson, retries and backoff, comes in.
Step 10: Rate limiting in one picture
A rate limiter turns "everyone shares the server" into "everyone gets a fair share". Fixed windows are simple but have an edge burst; sliding windows fix it; a token bucket allows bursts; a leaky bucket smooths them.
Put it at the gateway, count in a shared store, and answer rejected requests with 429 and Retry-After.