Design a rate limiter
A distributed rate limiter for a public API. Atomic counters shared by many gateways, what to do when the counter store fails, and limits that span regions.
The problem
A payments company exposes a public REST API. One afternoon a customer deploys a batch job with a bug: on any error it retries at once, in a loop, from 40 worker machines. Within a minute that one API key is sending 6,000 requests a second, about as much as every other customer combined. The shared database connection pool fills, p99 latency for everyone goes from 80 ms to several seconds, and the on-call engineer ends up blocking the key by hand.
The first fix most teams try is a counter in each API server’s memory. It stops working as soon as there is more than one server. With 20 servers behind a load balancer, “100 a second” per server is really 2,000 a second, and the number changes every time the fleet scales. The limit has to be checked against one shared count, on every request, without adding noticeable latency and without becoming a new way for the whole API to go down. This case study applies the algorithms from rate limiting to that distributed setting.
Requirements
Functional
- Limit requests per client (identified by API key, user ID or IP address) and per endpoint or group of endpoints.
- Apply several rules to one request, for example 100 a second for bursts and 100,000 a day as a quota.
- Reject over-limit requests with
429 Too Many Requestsand headers that tell the client when to retry. - Let operators change rules without a deploy, and run a new rule in shadow mode, where it logs what it would have blocked and rejects nothing.
Out of scope unless asked: billing-grade usage metering, network-layer DDoS protection (that belongs at the CDN or a scrubbing provider) and limits on concurrent requests.
Non-functional
- Latency: the check adds about 1 ms typically and under 5 ms at p99.
- Availability: a limiter failure must not become an API outage.
- Accuracy: overshooting a limit by a few percent under heavy concurrency is acceptable. Rejecting a client that is under its limit is not.
- Scale: 1 million active API keys, 50,000 requests a second on average, 200,000 at peak.
- A limit holds across every gateway instance in a region. Whether it must also hold globally is a question to ask the interviewer.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Checks at peak | one script call per request, covering all its rules | 200,000 per second |
| Redis shards | 200,000 / about 50,000 script calls per shard | 4 at least, run 8 |
| Counter state | 1M clients x 3 rules x about 150 bytes | about 450 MB |
| Sliding window log, for comparison | 1M clients x up to 1,000 timestamps x about 60 bytes | up to 60 GB |
| Time per check | one round trip to Redis in the same zone | about 0.5 ms |
The shard figure rests on an assumption: one Redis process runs commands on a single thread and handles on the order of 100,000 simple commands a second, and a script does the work of several commands, so I assume half that.
Three conclusions follow. Counter state is tiny, so it lives entirely in memory. Throughput, not memory, forces sharding, and the shard key is the client key. An algorithm that keeps one small record per client per rule is about a hundred times cheaper than one that stores every request.
API
Services never call the limiter directly. The gateway makes one internal call per request:
POST /internal/v1/check
{ "key": "acct_123", "route": "POST /v1/payments", "cost": 1 }
200 OK
{ "allowed": false, "rule": "payments-write-burst", "limit": 100, "remaining": 0, "retry_after_ms": 1200 }
What the API client sees when it is over the limit:
HTTP/1.1 429 Too Many Requests
Retry-After: 2
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1790000000
429 comes from RFC 6585 and Retry-After is a standard HTTP header, given in whole seconds or as a date. Send the limit headers on successful responses too, so well-behaved clients can slow down before they are rejected.
Data model
There are two kinds of data with very different lifetimes.
Rules change a few times a week and must never be lost. They live in a relational database or a Git repository, each with a version:
- id: payments-write-burst
match: { method: POST, path: "/v1/payments*" }
key: api_key # or user_id, ip
algorithm: token_bucket
capacity: 100 # burst size
refill_per_second: 50
mode: enforce # or shadow
on_store_failure: open # or closed
Counters change on every request and can be lost without harm: after a loss, every client simply starts with a full bucket. They live in Redis as one small hash per client per rule.
| Key | Fields | TTL |
|---|---|---|
rl:{acct_123}:payments-write-burst |
tokens, ts (last refill time) |
time to refill from empty, plus a margin |
The braces are a Redis Cluster hash tag. Only the text inside them is hashed, so every counter for one client lands on the same shard and one script can update all of that client’s rules together.
High-level architecture
Request path. The API gateway authenticates the request, which gives it the client key. Its limiter middleware matches the route against the rules it holds in memory, then calls one Redis script that checks and updates every matching counter. If all rules pass, the gateway forwards the request to the API service. If any fails, it returns 429 without touching the service.
Rule path. An operator changes a rule through the rules service, which validates it and writes a new version to the rules store. Gateways poll or receive a push, and swap the new rule set into memory. A gateway that cannot reach the rules service keeps using the last version it loaded.
Decision path. The gateway puts each rejection, and a sample of allowed requests, on a stream. Workers turn that into dashboards, alerts and the shadow-mode reports that show what a proposed rule would do.
Putting the limiter in the gateway means a rejected request costs almost nothing and every service is covered. The alternatives are a library in each service, which is hard to keep consistent across languages, or a separate rate limit service that the proxy calls, which is how Envoy’s global rate limiting works. The separate service costs one more network hop and lets the limiter scale on its own.
Deep dives
Choosing the algorithm
| Algorithm | State per key | Behaviour |
|---|---|---|
| Fixed window counter | one integer | Allows up to twice the limit across a window boundary |
| Sliding window log | one timestamp per request | Exact, but memory grows with the limit |
| Sliding window counter | two integers | Weights the previous window; a close approximation |
| Token bucket | tokens and a timestamp | Steady rate with a burst up to the bucket capacity |
A leaky bucket that queues requests and releases them at a fixed rate (the model behind NGINX’s limit_req) smooths traffic, but it adds delay, which clients of a request-response API rarely want.
I would choose token bucket for a public API. Real clients are bursty: a page load fires ten calls at once and then nothing. Capacity sets how large a burst is tolerated and the refill rate sets the sustained limit, and the two can be tuned separately. Stripe has described using token buckets in Redis for its API limits. For a long quota such as 100,000 a day, a fixed or sliding window counter is the natural fit, because customers think of a quota as a number that resets.
Send a burst of 10 and compare the two sides: the token bucket lets the burst through at once while it has tokens, and the leaky bucket queues it and releases it at a fixed rate.
Atomic counters and race conditions
The obvious implementation reads the counter, compares it with the limit and writes it back. Between the read and the write, another gateway can do the same.
Step 1 of 7
The limit is 100 requests a minute and this client has used 99. Two more requests arrive at the same instant, one at each gateway.
Read the steps as text
- The limit is 100 requests a minute and this client has used 99. Two more requests arrive at the same instant, one at each gateway.
- Each gateway reads the counter. Both are told 99, because neither has written anything yet.
- Both gateways decide that 99 is under the limit, allow their request and write back 100. The client has made 101 requests and the counter says 100. One update was lost.
- With INCR, Redis does the read and the write as one step and returns the new value. Gateway A gets 100 and allows. Gateway B gets 101 and rejects.
- A new gap appears at the start of a window. The gateway sends INCR, then crashes before it sends EXPIRE. The key now has no expiry, so the count never resets and the client stays blocked.
- The fix is a Lua script. Redis runs the whole script before any other command, so reading the bucket, refilling it, taking a token and setting the expiry happen as one atomic step.
- Any check that reads shared state, decides and then writes must be a single atomic operation in the store. One script per request does that in one round trip, with no locks.
The overshoot is not just one request. It grows with concurrency, and a client that is misbehaving is exactly the one sending many requests at the same instant.
INCR fixes the fixed window case, because Redis applies it atomically and returns the new value. It leaves a second gap: INCR then EXPIRE is two commands, and a crash between them leaves a counter with no expiry that blocks the client for ever. A token bucket needs a read, some arithmetic and a write, which no single command provides.
The answer to all three is a Lua script. Redis runs a script to completion before it runs any other command, so the whole check is atomic.
-- KEYS[1] bucket ARGV: capacity, refill per second, cost
local capacity, rate, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local t = redis.call('TIME')
local now = tonumber(t[1]) + tonumber(t[2]) / 1e6
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * rate)
local allowed = tokens >= cost
if allowed then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) + 1)
return { allowed and 1 or 0, math.floor(tokens) }
Three details matter. The script takes the time from Redis, so gateways with skewed clocks cannot mint tokens; calling TIME before a write needs Redis 5 or later, where scripts replicate their effects and not their text. The gateway loads the script once and calls it by hash with EVALSHA. And in Redis Cluster every key a script touches must be in one hash slot, which is what the hash tag guarantees.
For a handful of very hot keys, one round trip per request is still too much. A gateway can take, say, 50 tokens in one call and spend them locally. That cuts Redis traffic for that key by 50 times and lets the client overshoot by at most 50 tokens per gateway.
Regions, and failing open or closed
Limits across regions. With gateways in three regions there are three designs.
- Independent regional limits. Each region has its own Redis and enforces the full limit. A client that spreads traffic evenly can get three times the limit. Routing usually pins a client to one region, so few do.
- One global counter. Exact, but every request from the other regions pays a cross-region round trip of tens of milliseconds or more, and the home region becomes a single point of failure.
- Regional counters that share usage. Each region enforces locally and publishes per-key usage every second or so. Other regions subtract it from their local budget. Overshoot is bounded by roughly what the other regions can admit in one sync interval.
I would start with the first and move the largest customers to the third. A hard global quota that customers are billed against is a metering problem, solved with a durable usage pipeline, not with the inline limiter.
When Redis is slow or down. The gateway calls Redis with a strict timeout of a few milliseconds and a circuit breaker. When the call fails there are two choices. Fail open allows the request, so a limiter outage is invisible to customers but protection is gone. Fail closed rejects it, so the API is down whenever Redis is.
For rules that protect capacity, fail open, and fall back to a coarse in-memory limiter on each gateway (the limit divided by the number of gateways) so there is still a ceiling. For rules that are security or cost controls, such as login attempts, one-time code checks or SMS sends, fail closed. That is why on_store_failure is set per rule.
Bottlenecks and failure modes
- A Redis shard fails over. Replication is asynchronous, so the new primary may be missing the last few updates and some clients get a few extra requests. That is within the accuracy target.
- One enormous client. All of its counters sit on one shard by design. Local token batching keeps a single key from saturating it.
- A bad rule. A limit of 10 where 10,000 was meant blocks real customers within seconds. Validate on write, roll out in shadow mode first, and keep one-step rollback to the previous version.
- Clients that ignore 429. A rejection is cheap but not free. Persistent offenders get escalating blocks at the edge, and
Retry-Aftervalues should include some jitter so well-behaved clients do not all return in the same second. - Shared IP addresses. A per-IP limit punishes everyone behind one office or mobile carrier NAT. Prefer the API key or user ID and keep IP limits loose, for unauthenticated endpoints only.
- Gateway restarts. A new gateway has no rules until it loads them, so it must not accept traffic before the first load succeeds.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Placement | Gateway middleware | Library in each service | One implementation, and rejected requests never reach services |
| Algorithm | Token bucket | Sliding window counter | Burst and sustained rate tuned separately; quotas still use windows |
| Atomicity | Lua script per request | Separate GET and SET, or locks | One round trip, no race; logic lives inside Redis |
| Regions | Per-region limits, shared usage for large keys | One global counter | No cross-region call on the hot path; bounded overshoot |
| Store failure | Per rule, default open | Always closed | A limiter outage is not an API outage; security limits still hold |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Ask what is being protected and from whom. Pin down the key (API key, user, IP), whether limits are per endpoint, whether they must hold across regions, and how exact they must be. Say out loud that the limiter must not become an outage of its own.
- 5:00 to 8:00
Capacity estimates 3 min
One check per request at peak, state per client per rule, and the memory cost of a sliding window log for comparison. Conclude that memory is trivial and the hot path is one Redis round trip.
- 8:00 to 12:00
API 4 min
The internal check call and the public 429 response. Cover Retry-After and the rate limit headers, and note that header conventions differ between providers.
- 12:00 to 16:00
Data model 4 min
Rules as versioned configuration, counters as small keys with a TTL. Show one rule and one counter key.
- 16:00 to 24:00
High-level design 8 min
Draw the request path through the gateway to Redis and on to the services, then the rule distribution path, then the decision stream. Explain why the limiter sits in the gateway.
- 24:00 to 30:00
Deep dive: algorithm choice 6 min
Compare fixed window, sliding window counter, sliding window log and token bucket by state per key and behaviour at the boundary. Pick token bucket and say why.
- 30:00 to 37:00
Deep dive: atomic counters 7 min
Walk through the read-then-write race between two gateways, then the INCR and EXPIRE gap, then the Lua script that closes both. Mention hash tags for Redis Cluster and using the Redis clock.
- 37:00 to 43:00
Deep dive: regions and failure 6 min
Regional limits against a global count, and what the limiter does when Redis is slow or down. Tie fail-open or fail-closed to what each rule protects.
- 43:00 to 45:00
Wrap-up 2 min
Summarise in three sentences. Name what you would add next, such as per-customer concurrency limits or adaptive load shedding.
Key takeaways
- A limit kept in each server's memory multiplies by the number of servers, so the count has to be shared.
- Token bucket needs two numbers per key and allows a controlled burst, which is why it is the usual default for public APIs.
- Read-then-write on a shared counter is a race. Do the read, the arithmetic and the write in one atomic Redis script.
- Decide per rule whether to fail open or fail closed. General API protection fails open, security limits such as login attempts fail closed.
- A strict global limit costs a cross-region round trip on every request. Most systems enforce per region and accept bounded overshoot.
- Always return 429 with Retry-After, and expect some clients to ignore it.
Try it
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What state does a token bucket keep per key?
Two numbers, the tokens left and the time of the last refill. Each check adds elapsed time multiplied by the refill rate (capped at the capacity), then subtracts the cost if enough tokens remain.
Why is GET, compare, SET on a shared counter wrong?
Two gateways can both read 99, both decide the request is allowed and both write 100. The check and the update must be one atomic operation, such as INCR or a Lua script.
Fail open or fail closed?
Fail open (allow) when the rule protects capacity, so a limiter outage is not an API outage. Fail closed (reject) when the rule is a security or cost control, such as login attempts or SMS sends.
Which status code and header does an over-limit request get?
429 Too Many Requests with Retry-After. Most APIs also send limit, remaining and reset headers on every response, though the names and the meaning of reset vary by provider.
Three ways to handle a limit across regions?
Enforce per region and accept up to regions times the limit. Use one global counter and pay cross-region latency. Or count per region and share usage asynchronously for bounded overshoot.
What is shadow mode for a rate limit rule?
The rule is evaluated and its decisions are logged, but nothing is rejected. It shows who a new limit would have blocked before you enforce it.