25. Rate Limiting
1
The picture to keep in your head2
25.1 Why limit?3
25.2 What are the algorithms?4
25.3 How do the algorithms compare?5
25.4 How does distributed rate limiting with Redis work?6
25.5 Where should the limiter go?7
25.6 What do 429 and rate-limit headers look like?8
25.7 How do you handle bots and abuse?9
Memory card and where the analogy breaks10
Practice: five levels11
Interview questions12
Solutions13
Sources14
Code lab25. Rate Limiting
25.5 Where should the limiter go?
3 min read+10 XP
At the club: There's a bouncer at the street gate (keeps out obvious trouble), one at the inner door (checks your ticket type), and the bar has its own rule (two drinks per round). Each knows different things.
In the system: Requests pass through several layers, and each knows something different:
Figure: put each limit where the information it needs is available.
- Client: well-behaved clients limit themselves, back off on 429 and spread retries (Chapter 24). You can't rely on it, but your own apps should do it.
- Edge (CDN, WAF, load balancer): the cheapest place to drop floods, by IP or path, before they reach your servers. It doesn't know users or plans.
- API gateway: knows the API key, user and plan. The usual home for "100 a minute on the free plan, 1,000 on paid". Managed gateways offer this built in.
- Inside the service: knows the business meaning: 5 login attempts per account, 3 OTP sends per phone number per hour, 10 reviews per user per day.
- Outbound: limit your own calls to partners with strict limits (the SMS gateway's 500 a second in Chapter 22), usually with a token or leaky bucket in front of the client.
Most systems combine several: a generous per-IP limit at the edge, per-key limits at the gateway, and specific per-action limits in services.
Memory code: "Gate for floods, door for tickets, bar for drinks."