Rate limiting
Overview
Without limits, one buggy client, scraper or attacker can consume all of a service’s capacity and degrade it for everyone. Rate limiting caps how many requests a client may make in a time period. It protects services, enforces fair use and implements pricing plans. Designing a rate limiter is also a classic interview question (you’ll do the full design in week 7).
What to limit by
- Per user or API key: the usual choice for authenticated APIs and plans.
- Per IP address: for anonymous traffic, with care, since many users can share one IP.
- Per endpoint: stricter for expensive or sensitive actions (login, password reset, search).
- Global or per service: to protect a dependency’s total capacity.
Several limits often apply at once: 1,000 requests per minute per key and 5 login attempts per minute per account.
Algorithms
Token bucket
Each client has a bucket holding up to capacity tokens, refilled at a steady rate. Each request takes a token; with no tokens left, the request is rejected. Bursts up to the capacity are allowed, while the long-run average can’t exceed the refill rate. Only two numbers are stored per client (tokens and last refill time), and refills are computed lazily on each request. Used by AWS, Stripe and many gateways.
Leaky bucket
Requests enter a queue that drains at a fixed rate; when the queue is full, new requests are dropped. It smooths output to a constant rate, which suits protecting a downstream system that needs steady load.
Fixed window counter
Count requests per calendar window (for example per minute) and reject above the limit. Very simple, but a client can send the full limit at 10:00:59 and again at 10:01:00, getting double the rate across the boundary.
Sliding window log and sliding window counter
The log stores every request timestamp and counts those in the last 60 seconds: exact but memory-hungry. The sliding window counter approximates it with two fixed-window counts weighted by how far into the current window you are. It’s smooth, cheap and close enough for most uses.
Distributed rate limiting
With 20 gateway instances, each must see the same counts:
- Central store: keep counters in Redis. Make the check-and-update atomic, using
INCRwith expiry for windows or a Lua script for token buckets, to avoid races between instances. - Local plus sync: each instance enforces a share of the limit locally and periodically syncs, trading accuracy for speed and resilience.
- Sticky routing: hash clients to instances so each client’s limit lives in one place.
Decide what happens if Redis is down: fail open (allow traffic, keep the service usable) or fail closed (reject, safest for abuse-sensitive endpoints), usually with a coarse local limit as a backstop.
Where to enforce
- At the edge (CDN, WAF, API gateway): stops abuse before it costs anything.
- In services: for business rules (“3 password resets per hour”) and to protect specific resources.
- Client side: well-behaved SDKs throttle themselves using the headers you return.
Responding to clients
Return HTTP 429 Too Many Requests with:
Retry-After: when to try again,X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset(or the newer standardRateLimitheaders) so clients can pace themselves.
For internal callers, rate limiting combines naturally with load shedding (next lesson).
Recap
Rate limiting caps request rates per user, key, IP or endpoint to protect services and enforce plans. Token buckets allow controlled bursts; leaky buckets smooth output; sliding windows avoid fixed-window edge bursts. Share counters atomically in a store like Redis across instances, choose fail-open or fail-closed behaviour, and tell clients clearly with 429 and rate-limit headers.
Limit the API
A public weather API has free and paid plans: free keys may make 60 requests per minute with short bursts allowed; paid keys 1,000 per minute. It runs on 20 gateway instances. (a) Which algorithm would you use and why? (b) Where are the counters stored, and how do you update them safely? (c) What does the API return when a client exceeds its limit? (d) What happens if the counter store (e.g. Redis) is unavailable?
(a)
(b)
(c)
(d)(a) Token bucket per API key: free keys get capacity ~10 (burst) refilling at 1 token/s
(60/min); paid keys capacity ~100 refilling at ~16.7/s. It allows short bursts but
enforces the average. (A sliding-window counter would also work.)
(b) In a shared Redis cluster, keyed by API key (e.g. rl:{key}). Update atomically with
a Lua script that refills based on elapsed time, checks and takes a token in one
step, and sets an expiry. All 20 gateways share the same counters.
(For extra speed, gateways can keep small local allowances synced periodically.)
(c) HTTP 429 Too Many Requests with Retry-After, plus X-RateLimit-Limit,
X-RateLimit-Remaining and X-RateLimit-Reset headers so clients can adapt.
(d) Decide fail-open vs fail-closed: for a weather API, fail open (allow requests) with
a conservative local per-instance limit as a fallback, and alert. For something
abuse-sensitive like login attempts, fail closed or use the local limiter.Summary
- Rate limiting caps how many requests a client can make in a period, protecting services and enforcing fair use and plans.
- Token bucket allows bursts up to the bucket size while enforcing an average refill rate; it's the most common choice.
- Fixed windows are simple but allow double bursts at boundaries; sliding windows smooth this out.
- Distributed limits need shared, atomic counters (for example Redis with a Lua script) or approximate local limits.
- Return 429 with Retry-After and rate-limit headers, and decide whether to fail open or closed if the limiter breaks.