Why Redis for Rate Limiting
You are not learning five algorithms — you are learning three bugs and their cures. Each algorithm below fixes the previous one's failure mode and introduces its own trade-off.
What is rate limiting, in one breath?
A rate limiter answers one yes/no question on every incoming request: "Has this caller done too much, too fast?" If yes, you reject the request (usually with HTTP 429 Too Many Requests) instead of doing the work.
| Reason | Concrete example |
|---|---|
| Protect your system | One buggy client in a retry loop sends 10,000 req/sec and melts your database. The limiter caps them at 100. |
| Fairness | A free-tier user shouldn't be able to starve paying users of capacity. Everyone gets their slice. |
| Cost / abuse control | Each API call costs money (an LLM token, an SMS, a DB query). A limit caps the bill and blocks scrapers. |
| Need | Why it's hard | Redis answer |
|---|---|---|
| Shared state | 10 app servers each see a fraction of requests; per-process counters lie | A single Redis instance sees every request |
| Atomic read-modify-write | GET then INCR in two trips creates a race | INCR + EXPIRE are atomic; Lua scripts batch anything else |
| Automatic cleanup | Counters for inactive users accumulate forever | EXPIRE/TTL — Redis deletes the key for you |
The alternative — a relational row with UPDATE counters SET n = n+1 WHERE user=? — works, but adds milliseconds of latency and lock contention at high QPS. Redis does it in ~100 µs.