Distributed rate limiter
Design a rate limiter shared across many API servers with low latency.
By Invicly Tech, , in System Design Deep Dive. About 13 minutes to read.
In short
A distributed rate limiter enforces limits like 100 requests per minute per user across many API servers. Counters live in a shared low-latency store such as Redis, updated atomically so concurrent requests cannot slip past the limit.
Explained simply
A rate limiter is a bouncer for your API. It counts how many requests each client makes and turns away the extra ones once they pass a limit, such as 100 requests per minute. This protects your servers from overload, stops abuse like password guessing, and keeps one heavy customer from slowing everyone else.
On one server, counting is easy: keep a number in memory. But real APIs run on many servers behind a load balancer, and one client's requests land on different servers. If each server counts alone, a client could get 100 requests per server. So the counters must be shared.
The usual answer is a fast shared store, most often Redis, which keeps data in memory and answers in well under a millisecond. Every API server asks Redis: may this client make one more request? Redis updates the count and answers yes or no in one step, so two servers cannot both sneak in the last allowed request.
When a client is over the limit, the API replies with status 429 Too Many Requests and tells the client when to try again. A well-built limiter adds less than a millisecond or two to each request and keeps working sensibly even when Redis itself has trouble.
Press Play on a diagram to walk through it one step at a time.
- 1Clients
Identified by API key, user ID or IP
- 2API gateway or middleware
Checks limit before forwarding
- 3Rules config
Limits per endpoint and tier, cached locally
- 4Redis cluster
Shared counters, sharded by client key
- 5Backend services
Only receive allowed requests
- Client to Gateway: GET /api/orders1GET /api/orders
- Gateway to Redis: Run Lua: refill and take token2Run Lua: refill and take token
- Redis to Gateway: Allowed, 42 tokens left3Allowed, 42 tokens left
- Gateway to Service: Forward request4Forward request
- Service to Gateway: 200 OK5200 OK
- Gateway to Client: 200 plus X-RateLimit-Remaining6200 plus X-RateLimit-Remaining
- 1Identify client
API key, user ID or IP
- 2Match rules
From config cached in memory
- 3Atomic check in Redis
Lua script, 5 ms timeout
- 4Allowed?
Forward and add remaining-count headers
- 5Denied?
429 with Retry-After
- 6Redis down?
Fail open or closed per rule
In depth
Requirements and limit rules
Start by asking who is limited and by what key: API key, user ID, IP address, or a combination. Then which limits: per endpoint (login is stricter than reads), per plan (free 60 per minute, paid 1,000), and sometimes several at once (10 per second and 1,000 per hour). Non-functional needs: added latency under about 1 to 2 ms, high availability, and accuracy that is close but not necessarily exact.
Store rules as configuration, not code, for example a YAML list of key type, endpoint pattern, limit and window. Each limiter instance loads the rules at startup and refreshes them every few seconds, so changing a limit needs no deploy.
Also agree on the response: HTTP 429 with a Retry-After header, plus headers that show the limit, the remaining requests and when the window resets, so good clients can slow down before they hit the wall.
- Key: API key, user, IP, or tenant
- Several limits can apply to one request
- Rules in config, refreshed without deploys
- 429 plus Retry-After and remaining-count headers
Choosing the algorithm
Fixed window counts requests per calendar minute. It is one INCR per request, but a client can send 100 at 12:00:59 and 100 more at 12:01:00, so 200 pass in two seconds. Sliding window log stores a timestamp per request (a Redis sorted set) and counts those in the last 60 seconds. It is exact but uses memory for every request. Sliding window counter blends the current and previous fixed windows by how far into the current window you are. It is nearly exact, cheap, and the usual choice for per-minute quotas. Token bucket refills tokens at a steady rate up to a capacity and spends one per request. It allows short bursts while enforcing an average rate, which suits APIs with spiky but legitimate clients.
A good interview answer names the trade-off: token bucket for burst-friendly limits, sliding window counter for smooth quotas, and the log only for low-volume, strict limits.
- 1 counter per window
- Very cheap
- 2x burst at window edges
- Simple quotas
- 2 counters, weighted
- Nearly exact
- Smooth limits
- Per-minute API quotas
- Tokens plus last refill time
- Allows bursts up to capacity
- Enforces average rate
- Spiky but fair clients
Shared counters in Redis without races
The naive version reads the count, checks it in the app, then writes the new value. Two servers can both read 99, both decide it is fine, and both write 100: the limit is exceeded. The fix is to make check and update one atomic step inside Redis.
For a fixed window, INCR is atomic: it returns the new count, and the app compares that. For anything more complex, such as a token bucket that reads tokens, refills based on time, and decrements, use a Lua script. Redis runs each script to completion without interleaving other commands, so the whole decision is atomic. Load the script once with SCRIPT LOAD and call it by hash with EVALSHA.
In Redis Cluster, all keys used in one script must be in the same hash slot, so keep each client's bucket in one key, or use a hash tag such as rl:{user42}.
- Server 1 to Redis: GET count: 991GET count: 99
- Server 2 to Redis: GET count: 992GET count: 99
- Server 1 to Redis: SET 100 (allowed)3SET 100 (allowed)
- Server 2 to Redis: SET 100 (also allowed: 101st request slips in)4SET 100 (also allowed: 101st request slips in)
- Server 1 to Redis: Fix: one EVALSHA does check and update5Fix: one EVALSHA does check and update
Failures, hot keys and multiple regions
Decide in advance what happens when Redis is slow or down. Fail open (allow requests) protects availability and suits most APIs. Fail closed (reject) suits abuse-sensitive endpoints such as login or SMS sending, where letting everything through would be costly. Either way, give the Redis call a short timeout, around 5 to 20 ms, and wrap it in a circuit breaker so a sick Redis does not slow every request.
One very busy client puts all its load on one Redis key and therefore one shard. Spread hot clients by giving them a small local allowance per server, or split their bucket across a few sub-keys.
Across regions, a global counter would add a cross-region round trip to every request. Usually each region enforces its own share of the limit (for example half each in two regions), or regions sync counts asynchronously and accept a small overshoot.
Latency and accuracy trade-offs
Calling Redis on every request costs a network round trip, often 0.3 to 1 ms in the same zone. At very high traffic, or when that is too slow, limiters trade accuracy for speed.
Local pre-check: each server keeps an in-memory token bucket set to its share of the limit, for example the global limit divided by the number of servers, and only syncs with Redis periodically. This adds no network hop, but the global limit can be exceeded briefly when traffic is uneven.
Batching: a server takes a batch of tokens from Redis at once (say 10) and spends them locally, cutting Redis calls by ten times at the cost of a little unfairness.
Where to enforce matters too. An API gateway or edge (Envoy's global rate limit service, NGINX limit_req, a CDN rule) stops bad traffic before it costs you anything; per-service limits protect individual backends. Many systems use both: coarse limits at the edge, precise ones in the service.
- Exact: one Redis call per request
- Faster: local buckets synced periodically
- Fewer calls: reserve tokens in batches
- Edge limits for abuse, service limits for fairness
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Gather requirements and limit rules~35m
- 2Choose a limiting algorithm~35m
- 3Store counters in a shared Redis~35m
- 4Handle race conditions and failures~35m
- 5Discuss latency and accuracy trade-offs~35m
Key points
- Shared counters are needed so the limit holds across all servers.
- Use a Lua script or atomic INCR to avoid read-then-write races.
- Token bucket allows bursts; sliding window counter is smooth and cheap.
- Decide fail-open or fail-closed when Redis is unavailable.
- Local in-memory pre-checks cut Redis latency at the cost of accuracy.
Key terms
Tap a card to flip it. 0/5 known
Examples
Fixed-window counter in Redis (per user, per minute):
key = "rl:{userId}:{epochMinute}"
count = INCR key
if count == 1: EXPIRE key 60
if count > 100: return 429 Too Many Requests
else: forward request
Sliding window approximation:
rate = prev_count * (1 - elapsed/60) + curr_countAtomic INCR avoids races; sliding window smooths edges.
A token bucket as a Redis Lua script
Each client has a hash with its current tokens and the last refill time. Step 1: read both fields. Step 2: add tokens for the time elapsed, up to the capacity. Step 3: if at least one token remains, take it and allow the request. Step 4: save the state and set an expiry so idle clients disappear. Using Redis's own clock (TIME) avoids clock differences between app servers; Redis 7 replicates scripts by their effects, so this is safe. Call it with EVALSHA sha 1 rl:{user42} 10 100 for 10 tokens per second and a burst of 100.
local rate, cap = tonumber(ARGV[1]), tonumber(ARGV[2])
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local s = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(s[1]) or cap
local ts = tonumber(s[2]) or now
tokens = math.min(cap, tokens + (now - ts) / 1000 * rate)
local allowed = 0
if tokens >= 1 then tokens = tokens - 1; allowed = 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000))
return {allowed, math.floor(tokens)}Sizing the Redis tier
Assume 50,000 API requests per second at peak and 5 million active API keys. Step 1: each request is one EVALSHA, so Redis must handle 50,000 script calls per second; a single Redis node can typically do roughly 50,000 to 100,000 simple script calls per second, so use a cluster of 3 to 6 primaries for headroom. Step 2: memory: each bucket is a small hash of about 100 bytes, so 5 million keys need about 500 MB, tiny for Redis. Step 3: add one replica per primary so a node failure does not reset everyone's counters. Step 4: latency budget: about 0.5 ms per check in the same zone, within the 2 ms target.
Quick reference
- Return 429 Too Many Requests with Retry-After; expose remaining and reset in headers
- Fixed window: INCR plus EXPIRE; allows up to 2x the limit at window edges
- Sliding window counter: prev x (1 - elapsed/window) + current
- Token bucket: refill at rate r up to capacity b; allows bursts of b
- Check and update atomically: INCR or one Lua script, never GET then SET
- In Redis Cluster, keep each script's keys in one slot with a {hash tag}
- Short Redis timeout plus fail open (most APIs) or fail closed (login, SMS)
Common mistakes
- GET then SET in two calls, letting concurrent requests exceed the limit.
- Hot keys for one heavy client overloading a single Redis shard.
- Adding a cross-region Redis round trip to every request.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
A sliding window counter has a limit of 100 per minute. The previous minute had 80 requests, and 20 seconds into the current minute there have been 50. Is the next request allowed?
- Exercise 2medium
Write a Python function using redis-py that enforces a fixed-window limit of 100 per minute per user, safe under concurrency, and returns (allowed, remaining).
- Exercise 3hard
Design rate limiting for a public API running in 3 regions with a global limit of 3,000 requests per minute per API key. Explain how you keep latency low and how much overshoot you allow.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between rate limiting and throttling?
- People often use them as synonyms. Strictly, rate limiting rejects requests over the limit, while throttling slows them down, for example by queuing or delaying them.
- Which HTTP headers should a rate limiter return?
- Return 429 with Retry-After when rejecting. Many APIs also send X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset; an IETF draft standardises similar RateLimit headers.
- Should I rate limit by IP address?
- Only as a fallback for unauthenticated traffic. Many users can share one IP behind a corporate or mobile network, and attackers can rotate IPs, so limit by API key or user when you can.