Answer
Requirements: limit how many requests a client (identified by user ID, API key or IP) can make in a time window, return HTTP 429 when the limit is exceeded, add minimal latency, and work across many servers.
- Algorithms: token bucket allows controlled bursts and is the most common; leaky bucket smooths output to a fixed rate; fixed window counters are simple but allow double bursts at window edges; sliding window log is exact but stores every timestamp; sliding window counter approximates it cheaply.
- Placement: in an API gateway or middleware in front of the application servers.
- Distributed counting: keep counters in Redis and update them atomically with
INCRplus expiry, or with a Lua script. - Trade-off: a central store gives accurate global limits but adds a network hop; local counters are faster but only approximate.
More in Web Services
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | Design a URL shortener | Concept | Medium | Read the answer to Design a URL shortener | |||
| 2 | Design a pastebin service | Concept | Medium | Read the answer to Design a pastebin service | |||
| 3 | Design a rate limiter | Concept | Medium | Read the answer to Design a rate limiter | |||
| 4 | Design a notification system | Concept | Hard | Read the answer to Design a notification system |