System Design · 05. Reliability · 10 min · Intermediate

Rate Limiting

Say no to some requests so everyone else can get a yes.

In short

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.

Key ideas

  • A rate limiter protects a shared service from any one caller, by accident or on purpose. (step 1)
  • 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 5)

Good to know

  • In Redis this is two commands: INCR the key, and EXPIRE it after 60 seconds. (step 2)
  • The counter version is a close estimate that uses almost no memory. Most big systems use it. (step 4)
  • 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 7)
  • 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 9)

Watch out

  • Any fixed window can be gamed at its edge. If bursts matter, use one of the next three ideas. (step 3)
  • 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 6)
  • Most public APIs fail open, because blocking every user is worse than a short period without limits. Login limits often fail closed. (step 8)
ClientNormal usersRate limiter50/s per keyApp server

Key numbers

Allowed
450/s
Rejected
1,950/s

Terms

Rate limiting
Capping how many requests a client may send in a period, so one caller cannot overload a shared service.
Fixed window
A counter per client that resets at the start of every minute (or other period).
Boundary burst
A client sends a full limit at the end of one window and again at the start of the next, doubling the limit.
Sliding window
Counting requests over the last N seconds from now, so there is no reset edge to exploit.
Token bucket
A bucket that refills at a steady rate; each request spends a token, and a full bucket allows a burst.
Leaky bucket
A queue that drains at a fixed speed, turning bursts into a smooth stream and dropping the overflow.
API gateway
The front door that checks limits before requests reach the app.
Shared counter
A limit counter kept in one store, such as Redis, so all gateways count together.
429 Too Many Requests
The HTTP status for a rejected request, sent with Retry-After to say when to try again.