A rate limiter caps how many requests a client can make in a period of time. It protects you from abuse (scrapers, credential stuffing, a buggy client stuck in a retry loop), keeps one tenant from starving the others, and controls costs when each request calls something expensive. It's also load shedding: turning away excess work cheaply at the door instead of letting it overload the database.
A rejected request gets HTTP 429 Too Many Requests, ideally with a Retry-After header so well-behaved clients know when to come back.
Where it runs and what it counts
- At the edge or API gateway (NGINX, Envoy, a CDN, a managed gateway): cheapest, and it stops abuse before it reaches your servers.
- In the service: needed when the limit depends on business data, such as a plan tier or how many orders a user has placed today.
- The key is what you count per: API key or user ID for logged-in traffic, IP address for anonymous traffic (careful: many users can share one IP behind a NAT), or a combination. Real systems layer several limits, for example 10 per second and 1,000 per hour per user, plus a global cap.
The algorithms
| Algorithm | How it works | Memory per key | Trade-off |
|---|---|---|---|
| Fixed window | Count requests per clock window (e.g. per minute). Reset at the boundary. | 1 counter | Simple, but allows 2× the limit across a boundary: 100 at 0:59 and 100 at 1:00. |
| Sliding window log | Store a timestamp per request. Count those in the last N seconds. | 1 entry per request | Exact, but memory grows with traffic. |
| Sliding window counter | Weight the previous window's count by how much of it still overlaps. | 2 counters | Close to exact, very cheap. A common production choice. |
| Token bucket | A bucket holds up to B tokens and refills at R per second. Each request spends one. | tokens + timestamp | Allows bursts up to B while holding the average to R. |
| Leaky bucket | Requests join a queue that drains at a fixed rate R. | a queue | Perfectly smooth output, but bursts wait or get dropped. |
Sliding window counter
Token bucket
A token bucket answers "how big a burst is acceptable?" separately from "what's the long-run rate?". You don't need a timer to add tokens. Store the token count and the time of the last update, and top it up lazily on each request:
With B = 20 and R = 5 per second, a client can fire 20 requests at once, then gets 5 per second after that. In a multi-threaded server, wrap the read-modify-write in a lock per bucket, or use an atomic compare-and-swap.
Token vs leaky bucket: a token bucket lets bursts through immediately if tokens are saved up. A leaky bucket used as a queue smooths every burst into a steady stream, which suits protecting a downstream system that can only take a fixed rate.
Per-user limits without unbounded memory
One bucket per user, kept forever, grows without limit as new users and IPs appear. Two fixes:
- Evict idle buckets. A bucket untouched for longer than B ÷ R seconds would be full anyway, so deleting it loses nothing: a new full bucket behaves the same. Keep buckets in an LRU map with a size cap, or set a TTL.
- Store them in Redis with a TTL, so expiry is automatic.
Distributed rate limiting
With N app servers behind a load balancer, a counter in each server's memory lets a client get N times the limit. The options:
- Divide the limit by N per server. No coordination, but it's only accurate if the load balancer spreads each client evenly, and it changes whenever N does.
- A shared store, usually Redis. Every server checks the same counter. For a fixed window,
INCR keyfollowed byEXPIRE key 60on the first increment is enough. For a token bucket, the read-modify-write must be atomic, so run it as a Lua script inside Redis. A plain GET then SET from two servers at once lets both through. - Sliding log in Redis with a sorted set:
ZREMRANGEBYSCOREto drop old entries,ZADDthe new one,ZCARDto count, all in one transaction. - Local counters synced periodically: each server counts locally and pushes to the shared store every few hundred milliseconds. It's slightly inaccurate, but it removes a network hop from every request.
Decide what happens when Redis is down. Fail open (allow everything) keeps the product working but drops protection. Fail closed (reject everything) is safer for expensive or security-sensitive endpoints such as login. Many systems fail open with a local in-memory limiter as a backstop.
Telling clients
Client libraries should back off with jitter when they see 429. Otherwise every rejected client retries at the same moment and the spike repeats.
In the game: in Bot Swarm, 70% of the traffic is bots and a third of real users share office IPs. Limiting by IP blocks those users; limiting by API key doesn't. A fixed window lets the bots double up at every reset, which shows as an error spike every 10 seconds. A sliding window or token bucket removes it.
Interview checklist
- Say what you're protecting, the key you limit on, and the limits.
- Pick an algorithm and give a reason: token bucket for bursts, sliding window counter for cheap accuracy.
- Share counters across servers with atomic operations (Redis plus Lua).
- Bound memory with TTLs or eviction.
- Choose fail-open or fail-closed, and return 429 with
Retry-After.
Level 8: Bot Swarm
Put this into practice against live traffic. Your progress in the game is saved in your browser.
Play level 8Do it by hand
Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.
Further reading
- Martin Kleppmann, Designing Data-Intensive Applications (O'Reilly). The standard book on replication, partitioning and consistency.
- Site Reliability Engineering, Google's free book on running reliable systems.
- The Amazon Builders' Library: practical articles on timeouts, retries, caching and load shedding.
- The System Design Primer: a broad, community-maintained overview.