Design a rate limiter
medium 45 minProtect services against overload, abuse and surprise bills.
Video lesson · Chapter 1 of 5
Admit one request and spend one token
Token bucket rate limiter
1:17Reel

Theory
Read or listen first. About 1 min.
What it is
A rate limiter decides whether a request may go ahead, based on how many the same caller has made recently. Over the limit, it refuses politely or makes the caller wait.
The rule has three parts: who is counted (a user, a key, an address), how many are allowed, and over what time.
As a design problem the algorithm is the easy part. The hard part is that twenty gateways must agree on one count, within a millisecond or two, even while parts of the system fail.
Why it exists
Without limits, one broken script or one attacker can use up a service that thousands share. Limits keep it fair, protect the systems behind it and control cost.
A limiter also has to be fast, because it runs on every request, and correct when many servers count at once.
A short history
1980s
Network engineers shape traffic with leaky bucket and token bucket schemes, still the basis of many limiters.
1997
HTTP/1.1 (RFC 2068) includes the Retry-After header, which tells a client when to come back.
2000s
Public web APIs publish limits per key, and limits become part of API design.
2012
RFC 6585 adds status code 429 Too Many Requests.
Words to know
- Token bucket
- Tokens drip in; each request takes one. Allows short bursts.
- Leaky bucket
- Requests leave at a steady rate.
- Fixed window
- A counter for each minute, with a weak point at the boundary.
- Sliding window
- Counts the last 60 seconds, not the current minute.
- 429
- The status that says too many requests.
- Fail open
- If the limiter breaks, let requests through.
- Fail closed
- If the limiter breaks, refuse.
- Atomic
- Read, decide and write as one step that nothing can interrupt.
- Hot key
- One caller whose counter gets far more traffic than others.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3NumbersWork out a number when the answer changes what you build.
- 4API and dataThe contract first, then the data that serves it.
- 5DesignStart with the smallest system that works. Change it only when something breaks.
- 6Deep divesCompare the options before you open them, then say which you would pick.
- 7Explain your choicesAnswer first. Then compare your reasoning.
- 8By levelThe same question is judged differently for mid, senior and staff.
- 9MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Intercept. An API gateway or middleware inspects the request and extracts the client identifier.
Understand it
Start here
One ticket, many doors
A school has a group ticket for ten pupils. The stadium has several doors, and the pupils may use any of them.
The tally is the design problem. The turnstile is easy.
A rate limiter caps the number of requests an entity can make within a specified time window. It prevents backend exhaustion from rogue clients, stabilizes shared resources against noisy neighbours, and helps defend against brute-force attacks.
Four pages, four views
This page
Build the limiter: many gateways, one count.
Requirements
Which rules to agree on first: rate limiter requirements.
Algorithms
Buckets and windows with arithmetic: rate limiter algorithms.
API view
Plans, headers and polite clients: rate limits in APIs.
Step 1
Core algorithms compared
Four common rate-limiting algorithms
- 1
Token bucket
A bucket holds up to N tokens. Tokens replenish at a constant rate. Each incoming request consumes one token. If tokens remain, the request passes; otherwise, it is dropped. Allows short bursts up to bucket capacity and requires O(1) memory.
- 2
Leaky bucket
Requests enter a FIFO queue of fixed capacity and drain out at a strictly uniform rate. If the queue overflows, new requests drop. This shapes traffic into a perfectly steady output but adds latency to queued requests.
- 3
Fixed window counter
Time is divided into fixed intervals like 60-second windows. A single counter increments on every call. It is cheap to store, but traffic concentrated right at window boundaries can deliver twice the allowed limit within a brief span.
- 4
Sliding window counter
A hybrid approach that estimates request density using a weighted sum of the previous and current window counts. It all but removes the boundary spike while using only O(1) memory per client.
Step 2
High-level architecture
One request through the limiter
Place rate limiting in an API gateway or reverse proxy rather than embedding it deep within individual business services. This stops excess traffic at the perimeter before it consumes application threads, database connections, or compute instances.
The parts
| Part | Does |
|---|---|
| Limiter in the gateway | Reads the caller, finds the rules, asks the store, passes or refuses, adds headers |
| Redis | Holds the counts, runs the atomic script, forgets idle callers by expiry |
| Rules | Which limit for which caller and route, changed while running |
| Monitoring | Share refused per rule, errors, extra time, health of the store, patterns of abuse |
Step 3
Atomic sliding window with Redis
Distributed rate limiters rely on a shared store such as Redis. Checking the count and updating it in two separate network calls introduces a race condition where concurrent requests both read an outdated counter and pass through.
The race
local key = KEYS[1]local now = tonumber(ARGV[1])local window = tonumber(ARGV[2])local limit = tonumber(ARGV[3])-- Drop timestamps older than current windowredis.call('ZREMRANGEBYSCORE', key, 0, now - window)local current = redis.call('ZCARD', key)if current < limit then redis.call('ZADD', key, now, now .. '-' .. ARGV[4]) redis.call('PEXPIRE', key, window) return {1, limit - current - 1}else return {0, 0}endThis script is exact, and stores one entry for each passed call. Use it for small limits. For large ones, keep a token bucket in the same kind of script: see Deep dives under Interviews.
Step 4
HTTP headers and client feedback
When rejecting traffic, return HTTP status 429 Too Many Requests. Include explicit headers so well-behaved clients can throttle their own retry cycles instead of hammering the endpoint.
HTTP/1.1 429 Too Many RequestsContent-Type: application/jsonRetry-After: 30RateLimit-Policy: "default";q=100;w=60RateLimit: "default";a=0;w=30{ "error": "rate_limit_exceeded", "message": "Rate limit exceeded. Try again in 30 seconds."}Step 5
Resilience and distributed trade-offs
Centralized Redis Cluster
- Exact counts across all gateways of a region.
- Simple policy enforcement without local node synchronization.
- Native TTL support cleans up idle client keys automatically.
Pure Local In-Memory Counters
- Traffic imbalances across nodes can lead to unpredictable limits.
- Each caller may get the limit once per gateway.
- Requires state sharing protocols like gossip to stay consistent.
Why local counts are not enough
Ways to share a count
| Way | Extra time | Exactness | Use |
|---|---|---|---|
| Central Redis in the region | about 1 ms | Exact while it is healthy | Default |
| Gossip between gateways | none | Late by the exchange interval | Very high volume, rough limits |
| Same caller to the same gateway | none | Exact until gateways change | When the balancer can hash by key |
| Leased tokens from Redis | none for most calls | Never over, sometimes refuses early | Hot callers |
Step 6
Rules engine and identification keys
Rate limits must not be applied uniformly. Structure rules to match different dimensions: client identity, client tier, and requested endpoint.
Key generation dimensions
- 1
By IP address
Useful for unauthenticated endpoints. However, multiple users behind a corporate NAT share an IP, and malicious actors can rotate IP addresses easily.
- 2
By user or API key
The preferred choice for authenticated systems. Ensures users receive their contracted tier limits regardless of which network or device they connect from.
- 3
By endpoint cost
Resource-intensive operations like report generation or checkout should have stricter limits than lightweight cache reads.
{ "id": "api-free-tier", "name": "Free Tier API Limit", "priority": 10, "match": { "path": "/api/*", "methods": ["GET", "POST"], "userTiers": ["free"], "headers": { "x-api-version": "v1" } }, "subject": "account", "limit": 60, "window": "1m", "onStoreFailure": "local", "action": "reject", "response": { "status": 429, "message": "Upgrade to Pro for higher limits" }}Rules by priority, example numbers
| Priority | Rule | Limit a minute | If the store fails |
|---|---|---|---|
| 100 | POST /api/login, per address and per account name | 5 | Strict local limit |
| 50 | POST, PUT and DELETE, per account | 100 | Local limit |
| 10 | Plan: free, pro, enterprise | 60; 1,000; by contract, 10,000 and more | Local limit |
| 1 | Everything else, per address | 300 | Local limit |
Finding the rule
Step 7
One request, start to end
The whole path
And when Redis is slow
Step 8
Before it goes live
Checklist
- Redis shards with replicas
- One script for check and count
- Local fallback for each rule
- Headers, and Retry-After on 429
- Metrics and alerts
- Rules changed while running
- Timeout and circuit breaker to Redis
- Refusals logged with the rule
- Limits by plan
- Connection pool
Common mistakes
- No expiry: memory grows for ever
- GET then SET
- Blocking everything when Redis is down
- One limit for all endpoints
- Only by address
- No headers for clients
- Redis as the only defence
Summary
The whole topic in one minute.
A rate limiter keeps one caller from using more than a fair share.
Token bucket suits bursts; a sliding window is smoother than a fixed one. Count in one shared place with an atomic step, tell the client when to retry, and decide in advance what happens when the limiter itself fails.
Grow it step by step: one gateway, one shared Redis, rules as data, shards and replicas, a local memory of refused callers, then a share of the limit for each region.
- Token bucket allows short bursts; a sliding window counter is smooth with O(1) memory.
- Use atomic Redis operations with Lua scripts to eliminate race conditions.
- Always return HTTP 429 alongside Retry-After, and show limits on every answer.
- Place rate limiting at the gateway to drop excess load early.
- Fail open with a local limit for standard traffic; stay strict for logins and money.
- Remember refused callers locally, and give each region its share.
Sources
- RFC 6585: Additional HTTP Status Codes (Section 4: 429 Too Many Requests)
- IETF Draft: RateLimit Fields for HTTP
- Redis: scripting with Lua
- Redis: INCR and the rate limiter pattern
- Redis Cluster specification: hash tags
- Stripe: scaling your API with rate limiters
- GitHub: rate limits for the REST API
- Wikipedia: Token Bucket