TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท distributed systems ยท apis ยท security

Rate limiting

Capping how many requests a client can make in a period, to protect a service from overload and abuse. The token bucket allows short bursts while enforcing a steady average rate.

8 min4 animations

๐Ÿ“š Builds on๐Ÿ“ฎ HTTP

๐Ÿ–จ๏ธ Cheat sheet

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).

The sweet jar4 steps
๐Ÿง’Visitor๐Ÿฌ Sweet jar๐ŸณKitchen
Press play and watch it happen!

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.

A jar for everyone3 steps
๐Ÿ‘งAna๐Ÿค–Greedy visitor๐Ÿซ™Jar shelf๐ŸณKitchen
Press play and watch it happen!

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.

One jar, many doors3 steps
๐Ÿง’Visitor๐ŸšชFront door๐ŸšชBack door๐Ÿซ™ The shared jar
Press play and watch it happen!

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 429 add load exactly when the service is full. Symptom: request rate stays high after the limit trips, and 429s don't fall. Fix: send Retry-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, then SET) lets two servers read the same count and both pass. Fix: a sliding window or token bucket, and one atomic step: INCR and EXPIRE together in a MULTI/EXEC transaction, or a Lua script that increments, sets the expiry on the first hit and returns the count; a separate EXPIRE call 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)); }4 5// 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;
ChoiceYou gainYou pay
Fail open (allow when the store is down)Users keep working, no outage caused by the limiterNo 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 protectedThe limiter's outage becomes your outage; legitimate users get errors
Local counters per nodeNo network hop, no shared point of failureThe real limit is roughly the node count times the limit, and it shifts as you scale
Central counters (Redis)One accurate limit across all nodesAn extra round trip per request and a dependency to run and keep fast
Fixed windowSimplest and cheapest: one counter per keyUp to double the limit around window edges
Token bucket or sliding windowSmooth limits (token bucket also allows a planned burst)More state per key and a small script to keep atomic
The shared jar goes missing4 steps
๐Ÿง’Crowd of visitors๐ŸšชDoorman๐Ÿซ™ The shared jar๐Ÿง‘โ€๐ŸณThe cook at the stove
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐ŸšฆDesign a distributed rate limiterCap requests per client across hundreds of servers.practice problem

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Rate limiting, told the same way as the story.
  1. You arrive in a rush and the jar has three sweets. What can you do?
  2. Why does everyone get their own jar?
  3. The kitchen has several doors. Why do they share one jar?
  4. The shared jar is stuck in a locked cupboard. The doorman waves everyone through. What is the risk?
Answer every question to check.Passing marks Rate limiting as done.
Got the hang of Rate limiting? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐ŸŽฏ Backend interview prepStep 4 of 9

โ† Previous on the path๐Ÿ”˜ IdempotencyNext on the path โ†’๐ŸŽก Load balancing

๐Ÿš€ Shipping to productionStep 9 of 10

โ† Previous on the pathโšก Circuit breakers and retriesNext on the path โ†’๐Ÿฅ Observability: logs, metrics and traces

๐Ÿ‘‰ Read next

  • ๐ŸŽกLoad balancingA theme-park host sending each family to the ride with the shortest queue, skipping rides that are broken.
  • ๐Ÿ›Ž๏ธAmazon API GatewayThe service counter of a big store: it checks each shopper's card, keeps the queue moving and points them on.