Case study: Distributed rate limiter
Overview
A rate limiter decides, for each request, whether the client is within its allowed rate. Week 6 covered the algorithms; this case study designs the full distributed system: where it runs, where counters live, how rules are configured and what happens when parts fail.
Try the exercise first: 45 minutes, then compare.
1. Requirements
Functional
- Limit requests per client identity (API key, user ID or IP) and optionally per endpoint, according to configurable rules (for example 100 per minute for free plans, 5,000 per minute for paid ones).
- Reject excess requests with a clear error and information on when to retry.
- Rules can change without redeploying gateways.
Non-functional
- Low added latency (a few milliseconds at most).
- Accurate enough: small overshoot is acceptable, large overshoot is not.
- Highly available: the limiter must not take the API down.
- Scale: 500,000 requests per second across 50 gateway instances.
2. Estimates
checks : 500,000 / s (one per request)
active keys : say 10M API keys/users; each counter ~100 bytes → ~1 GB in memory
Redis : ~100k simple ops/s per node → ~5–10 shards, plus replicas3. Interface
Most often the limiter is a library or middleware inside the gateway:
allow(identity, route) → {allowed: bool, remaining: int, reset_at: time}Rejected responses:
HTTP/1.1 429 Too Many Requests
Retry-After: 12
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 17648502124. Data model
rules (config DB, cached in gateways):
plan | route pattern | limit | window | burst
counters (Redis):
key "rl:{api_key}:{rule_id}" → {tokens, last_refill} (TTL = idle timeout)5. High-level design
For each request, the gateway identifies the client, finds the matching rules in its local cache, runs one atomic Redis operation per rule, and either forwards the request or returns 429.
6. Deep dives
Choosing the algorithm
- Token bucket: two numbers per key, allows short bursts, enforces the average. Good default for APIs.
- Sliding-window counter: two counters per key, smooth, close to exact per-window limits. Good when the contract says “N per minute”.
- Fixed window: simplest, but allows double bursts at window edges.
- Sliding log: exact but stores every timestamp; too much memory at this scale.
Atomic updates
Fifty gateways may update the same key simultaneously. Reading the value, deciding and writing it back in separate steps lets two requests both take the last token. Make it atomic:
- Lua script in Redis: compute refill from elapsed time, check, decrement and save in one step on the server.
- For fixed windows,
INCRplusEXPIREis atomic enough.
Use Redis server time (or pass the gateway’s time consistently) to avoid clock-skew effects.
Latency and hot keys
One Redis round trip is about a millisecond inside a data centre. To cut further:
- shard counters by key across a Redis cluster (keys for one client land on one node),
- pipeline checks for multiple rules into one round trip,
- for extremely high-volume keys, give each gateway a small local allowance (a slice of the limit) and sync with Redis periodically, trading a little accuracy for speed.
Failure behaviour
If Redis is slow or down:
- Fail open: allow requests (protects availability), applying a coarse per-instance local limit so abuse is still bounded. Usual choice for general API traffic.
- Fail closed: reject (protects backends and security), appropriate for login attempts or expensive operations.
Set a tight timeout on the limiter call so a slow Redis can’t slow every request. Replicate Redis shards with automatic failover; counters lost in a failover simply restart, a minor inaccuracy.
Rules management
Store rules in a database with an admin UI or config files in Git. Gateways cache them and refresh every few seconds (or subscribe to change notifications). Validate rules before rollout; a bad rule can reject all traffic.
Multiple regions
A global limit needs coordination across regions, which costs latency. Common approaches: split the limit per region (each region allows its share), or count locally and sync asynchronously, accepting brief overshoot.
7. Trade-offs and bottlenecks
- Accuracy vs latency: local allowances and regional splits are faster but less exact.
- Fail open vs closed: availability vs protection.
- Redis memory is bounded by active keys; idle counters must expire.
8. Follow-up questions
- Rate-limit by IP for anonymous traffic? Same design, but beware shared IPs (offices, mobile carriers) and spoofed headers.
- Different costs per endpoint? Use weighted tokens (an export costs 10 tokens).
- Quotas per month? A separate, durable counter in a database, updated asynchronously, alongside the short-window limiter.
Recap
A distributed rate limiter runs in the gateway path, looks up cached rules, and performs one atomic check-and-update per rule against counters in a sharded Redis cluster, returning 429 with helpful headers when limits are exceeded. Token buckets or sliding windows provide the algorithm; Lua scripts provide atomicity; local fallbacks and a fail-open or fail-closed policy keep the limiter from becoming a single point of failure.
Design it yourself (45 minutes)
Set a 45-minute timer and design a rate-limiting service for a public API platform: limits per API key and per endpoint (e.g. 100 requests/minute for free keys, 5,000 for paid), configurable rules, 50 gateway instances handling 500,000 requests per second in total, and less than 5 ms added latency. Use the framework, then compare.
1. Clarifying questions:
2. Functional requirements:
3. Non-functional requirements:
4. Estimates:
5. API / interface:
6. Data model (counters, rules):
7. High-level design:
8. Deep dives (algorithm, atomicity, failures):
9. Trade-offs and bottlenecks:A strong answer covers:
- Where: middleware in the API gateway (not a separate network hop per request,
or a sidecar/library calling a shared store).
- Rules: per key + route + plan, stored in a config DB, cached in each gateway,
refreshed every few seconds.
- Algorithm: token bucket (allows bursts) or sliding-window counter; justify.
- State: Redis cluster keyed by rl:{key}:{rule}; atomic check-and-update via Lua
script or INCR+EXPIRE; keys expire when idle.
- Scale: 500k checks/s → shard Redis by key (~5-10 nodes with replicas); one round
trip ~1 ms; optional local pre-checks / batching for very hot keys.
- Response: 429 + Retry-After + rate-limit headers.
- Failure: Redis down → fail open with conservative local limits (or fail closed for
sensitive endpoints); alert.
- Multi-region: per-region limits (limit/regions) or async sync; accept small overshoot.Summary
- Enforce limits in the gateway path with a shared, fast store so all instances agree.
- Token bucket allows bursts and is cheap to store; sliding-window counters give smooth per-window limits.
- Make check-and-update atomic (Redis Lua scripts) to avoid races between gateway instances.
- Cache rules locally, return 429 with Retry-After and rate-limit headers, and expire idle counters.
- Decide fail-open vs fail-closed, and accept small inaccuracy across regions in exchange for latency.