Scope
Functional
- Limit requests per key (API key, user ID, IP) per rule, e.g. 100 requests/minute per user on /search, 5 OTPs/hour per phone.
- Rules configurable without deploys.
- Return 429 with retry information when limited.
Non-functional
- Adds < 2 ms at p99 to each request.
- Accurate within a few percent across a fleet of ~200 gateway instances.
- Highly available: the limiter must never become the outage.
Size
- 500k requests/s at peak across the gateway fleet, so 500k limit checks/s.
- 50M active keys × ~3 rules × ~50 B of state ≈ 7.5 GB, which fits in a Redis cluster.
- One Redis node does ~100k ops/s → 6–10 shards with headroom.
The algorithms
| Algorithm | Idea | Burst behaviour | Memory | Accuracy |
|---|---|---|---|---|
| Fixed window | Counter per minute window | 2× burst at window edges | 1 counter | Poor at edges |
| Sliding log | Store each request timestamp | Exact | One entry per request | Exact, expensive |
| Sliding window counter | Weighted mix of current and previous window counts | Smooth | 2 counters | Very good approximation |
| Token bucket | Tokens refill at rate r up to capacity b; each request takes one | Allows bursts up to b | 2 numbers | Good |
| Leaky bucket | Requests drain from a queue at a fixed rate | Smooths output | Queue | Good, adds delay |
Choice: token bucket for API limits (bursty clients are normal), sliding window counter for strict quotas like OTPs.
The architecture
The 30-second summary
Say it in the interview
"Rate limiting runs as gateway middleware. State is a token bucket per (key, rule) in a sharded Redis cluster, updated atomically with a Lua script in one round trip. Rules are pushed from a config service. It fails open for general APIs and closed for security limits, and very hot keys get local buckets to protect Redis."
Follow-up questions the interviewer may ask
- How do you rate-limit across regions?
- How do you avoid Redis becoming the bottleneck?
- Different limits for different endpoints and plans?
- How do you limit by cost instead of count?
Model answers to each of these are in the book.