The sweet jar
To get into the kitchen, you have to take a sweet from a jar. The jar holds a few sweets, and someone drops in a new one every minute. If you come in a rush, you can take the few that are there; after that, you wait for the next.
The token bucket
A token bucket has a capacity (the burst size) and a refill rate. Each request takes a token; with none left, the
request is rejected with 429 Too Many Requests and usually a Retry-After header.
You don't need a timer: store the token count and the last refill time, and on each request add
elapsed ร rate tokens (up to capacity) before taking one.
Other algorithms: fixed window (count per minute, simple but allows double bursts at window edges), sliding window (smoother), and leaky bucket (processes at a constant rate, queueing the rest).
A jar each
If everyone shared one jar, one greedy visitor could empty it and lock everyone else out. So everyone gets their own jar, and the kitchen also limits how many people get in overall.
What to limit by
Limits are kept per key: API key or user id for logged-in traffic, IP address for anonymous traffic, sometimes per endpoint (login attempts get a much tighter limit). A global limit protects total capacity.
Rate limits stop runaway scripts and scrapers, slow down password guessing, and keep one customer from starving
others. Tell clients their limits with headers like RateLimit-Remaining.
One jar, many doors
A big kitchen has several doors. If each door had its own jar, you could just use another door. So all the doors share one jar.
Distributed limits
With several servers, per-server counters let a client get N times the limit. Keep counters in a shared store such as
Redis, updated atomically: INCR plus EXPIRE for a fixed window, or a small Lua script for a token bucket. API
gateways (Kong, NGINX, Envoy, AWS API Gateway) provide this out of the box.
When the jar goes wrong
Sometimes the shared jar is out of reach, say it's stuck in a locked cupboard. The doorman at each door must pick: wave everyone through, or turn everyone away. Waving through keeps the kitchen busy, but the cook at the stove gets swamped. Turning away keeps the stove calm, but hungry visitors go home.
Other things go wrong too. If each door keeps its own jar of 100 sweets, ten doors hand out 1000. A turned-away visitor who knocks again at once, over and over, makes the crowd worse; a kind doorman says "come back in ten minutes", and visitors who wait a slightly different time each come back in a trickle. And a whole busy family sharing one house number looks like one greedy visitor, so they all get turned away together. So visitors with a membership card are counted by their card, not their house.
What can go wrong
- The shared store is down or slow. If the limiter's Redis (Redis and Valkey) times out, every request has to choose. Symptoms: limiter timeout or connection errors in logs, p99 latency rising on every endpoint, then either a traffic spike on the backend or a wall of 429s or 503s. Fix: set a short timeout on the limiter call, decide the policy on purpose (see the table), and fall back to a coarse per-node limit while the store is out.
- Per-node limits multiply. (see Distributed limits above) 10 nodes each allowing 100 requests/s let a client through at up to 1000/s if the load balancer spreads its requests. Symptom: the backend sees far more than the configured limit. Fix: divide the limit by the node count and accept the error when nodes scale or traffic is uneven.
- Retry storms. Clients that retry immediately after a
429add load exactly when the service is full. Symptom: request rate stays high after the limit trips, and 429s don't fall. Fix: sendRetry-After, and have clients back off exponentially with jitter (random delay) so they don't return in lockstep. - Limiting by IP. Many users behind one NAT or corporate proxy share an address and are limited together, while an
attacker can rotate addresses. Behind a proxy you see only the proxy's IP unless you read
X-Forwarded-For, but any client can set that header. Fix: trust only the entries your own proxies added (for example the address just before your trusted hops), and limit logged-in traffic by API key or user id. - Fixed-window edges and races. A fixed window of 100 per minute allows 100 requests at 12:00:59 and 100 more at
12:01:00, so 200 in two seconds. And a check-then-increment (
GET, compare, thenSET) lets two servers read the same count and both pass. Fix: a sliding window or token bucket, and one atomic step:INCRandEXPIREtogether in aMULTI/EXECtransaction, or a Lua script that increments, sets the expiry on the first hit and returns the count; a separateEXPIREcall can be lost in a crash and leave a counter that never resets.
1// Not atomic: two servers can both read 99 and both pass2long n = Long.parseLong(redis.get(key));3if (n < LIMIT) { redis.set(key, String.valueOf(n + 1)); }45// INCR is atomic, so no two servers read the same count;6// but set the expiry in the same step (MULTI/EXEC or Lua), or a crash here leaves a counter that never expires7long count = redis.incr(key);8if (count == 1) { redis.expire(key, 60); }9boolean allowed = count <= LIMIT;
| Choice | You gain | You pay |
|---|---|---|
| Fail open (allow when the store is down) | Users keep working, no outage caused by the limiter | No protection during the outage; the backend or a login endpoint can be overwhelmed |
| Fail closed (reject when the store is down) | The backend and sensitive endpoints stay protected | The limiter's outage becomes your outage; legitimate users get errors |
| Local counters per node | No network hop, no shared point of failure | The real limit is roughly the node count times the limit, and it shifts as you scale |
| Central counters (Redis) | One accurate limit across all nodes | An extra round trip per request and a dependency to run and keep fast |
| Fixed window | Simplest and cheapest: one counter per key | Up to double the limit around window edges |
| Token bucket or sliding window | Smooth limits (token bucket also allows a planned burst) | More state per key and a small script to keep atomic |