Rate Limiting Algorithms
Capping how fast one client can hit a service, before that client (accidentally or not) degrades it for everyone else.
Intermediate
| Threat | How rate limiting helps |
|---|---|
| Scraping / competitive data harvesting | A competitor programmatically pulling every restaurant's menu and prices can be capped per-IP or per-account before it becomes meaningful load. |
| DoS / DDoS traffic spikes | Capping requests per source keeps a flood from a small set of origins from starving out legitimate users. |
| Runaway retry loops | A buggy client that retries aggressively on every failure gets throttled instead of amplifying an existing incident. |
| Cost control | Fewer wasted requests directly means fewer servers needed to absorb them. |
bucket_capacity = 10
leak_rate = 2 requests/sec
# the bucket leaks continuously, so output is a steady 2 req/sec no matter
# how bursty the input is -- there are no windows here, and no boundary effect.
# the trade-off is the opposite one: a legitimate burst waits in the bucket
# (added latency) or is dropped once the bucket is full, even if the client
# has been quiet for the last hour
limit = 4 requests / hour
# problem: 4 requests at 8:59, then 4 more at 9:00 -> 8 requests in 2 minutes,
# even though each hour individually stayed within the stated limit
limit = 4 requests / hour, sliding
# a request is allowed only if fewer than 4 requests occurred
# in the preceding 60 minutes, measured from right now