Rate Limiting
Overview
A rate limiter caps how many requests a client may make in a period of time, for example 100 requests per minute per user. Requests over the limit are rejected quickly with HTTP status 429 Too Many Requests.
It protects a service from abusive clients, buggy retry loops and traffic floods, keeps one noisy customer from starving everyone else, and controls cost. This lesson explains the four classic algorithms with worked numbers, and how to make a limiter work across many servers. (The full rate limiter design appears later in the course.)
Detailed Notes
What is it?
A rate limiter sits in front of a resource, usually at the API gateway or in a middleware, and decides for each request: allow or reject. The decision needs three things:
- A key: who is being limited (user ID, API key, IP address, or a combination such as user + endpoint).
- A rule: how much is allowed (100 requests per minute; 10 login attempts per hour).
- A counter or state that remembers recent usage for that key.
Related words: throttling means slowing down or delaying excess requests instead of rejecting them; a quota is a longer-term allowance such as 1 million calls per month; load shedding is dropping traffic when the server is overloaded regardless of who sent it.
Why do we need it?
- Protection: a bug or an attacker sending 50,000 requests per second can take down a service built for 5,000.
- Fairness: without limits, one heavy tenant consumes shared capacity and everyone else slows down.
- Security: limits on password attempts slow brute-force attacks (guessing passwords until one works) to a crawl.
- Cost control: calling a paid downstream service (an SMS provider, an AI model) without limits can produce a surprise bill.
- Tiers: free users get 60 requests/minute, paid users 6,000.
How does it work?
Where to put it
Common choices: at the API gateway or load balancer (one place, protects everything, cheapest because rejected requests never reach your code), as middleware in the service (can use business context such as the user's plan), or on the client side (polite, but never trustworthy). In practice you use the gateway for coarse limits and the service for fine ones.
Algorithm 1: Token bucket
Picture a bucket holding up to capacity tokens. Tokens are added at a steady refill rate. Each request removes one token; with no token, the request is rejected. The bucket allows short bursts (up to the capacity) while keeping the long-run average at the refill rate.
Instead of running a timer, compute the refill lazily when a request arrives:
tokens = min(capacity, tokens + elapsed_seconds x refill_rate)
if tokens >= 1: tokens = tokens - 1, allow
else: reject
Worked example: capacity 10, refill 5 tokens per second.
t = 0.0 s bucket full: 10 tokens. A burst of 10 requests arrives -> all allowed, tokens = 0
t = 0.0 s an 11th request -> rejected (429)
t = 1.0 s tokens = 0 + 1 x 5 = 5. 5 requests arrive -> all allowed, tokens = 0
t = 1.2 s tokens = 0 + 0.2 x 5 = 1. 1 request allowed, a second is rejected
t = 5.0 s idle for 3.8 s: 0 + 3.8 x 5 = 19, capped at capacity -> 10 tokens
The state per key is just two numbers (tokens and last-refill time), about 16 bytes. Used by Stripe and Amazon APIs; the best general choice because bursts are natural for real users.
Request load
Burst allowed
10 requests
instantly, from a full bucket
Sustained rate
5 per second
long-run average = refill rate
State per user
16 bytes
tokens + last refill time
Tokens are computed lazily on each request: tokens = min(capacity, tokens + elapsed x rate).
Algorithm 2: Leaky bucket
Requests enter a queue (the bucket) and are processed at a constant rate, like water dripping out of a hole. If the queue is full, new requests are dropped. The output is perfectly smooth, which protects fragile downstream systems, but bursts get delayed, and a burst of old requests can crowd out fresh ones. Pick it when the downstream needs a steady flow (for example, calling a payment processor limited to 50 calls/s).
Algorithm 3: Fixed window counter
Divide time into windows (each minute). Keep a counter per key per window; reject when it exceeds the limit; reset at the next window. Very cheap: one counter. Its flaw is the boundary problem: with a limit of 100 per minute, a client sends 100 requests at 12:00:59 and 100 more at 12:01:00. Both windows are within the limit, yet 200 requests arrived in two seconds, double the intended rate.
Algorithm 4: Sliding window
Fixes the boundary problem by looking at the last 60 seconds from now, not the current calendar minute.
- Sliding window log: store the timestamp of every request and count those in the last 60 s. Exact but costs memory: 100 timestamps x 8 bytes per user, for millions of users.
- Sliding window counter: keep the counts for the current and previous fixed windows and weight them. If the current window is 30% elapsed, the estimate is
current_count + previous_count x 0.7. With previous = 80 and current = 30: 30 + 80 x 0.7 = 86, under 100, allow. Two counters per key and accurate to within a few percent. A great practical compromise.
Fixed window
one counter per minute
- 1
Count requests in this minute
- 2
Reject when count > 100
- 3
Reset to 0 at the next minute
- Simplest and cheapest
- 200 requests possible across a boundary
Fine for coarse, low-stakes limits
Sliding window counter
weighted two windows
- 1
Keep current and previous counts
- 2
Estimate = cur + prev x overlap
30 + 80 x 0.7 = 86
- 3
Reject when estimate > 100
- Smooth rolling limit
- Two counters per key
- Approximate (a few percent)
Strict limits at low memory cost
Token bucket
refill and spend tokens
- 1
Refill by elapsed x rate
- 2
Cap at capacity
- 3
Spend 1 token or reject
- Allows bursts
- Two numbers per key
- Two parameters to tune
Best general-purpose default
Limit of 100 requests per minute in each case.
Making it work across many servers
One gateway server can keep counters in its own memory. With 20 gateway servers, each seeing a fraction of the traffic, a user could send 20x the limit. Options:
- Shared store (most common): all gateways keep counters in a fast central store such as Redis. Reading and then updating the counter must be atomic (one indivisible step), otherwise two concurrent requests both read 99, both allow, and the count ends at 100 instead of 101. Redis supports this with
INCRor a small Lua script that runs as a unit. - Sticky routing: route each user to the same gateway by consistent hashing so local counters suffice. Cheaper per request but fails when a node dies and loses counters.
- Approximate local counters that sync periodically: tiny overshoot, no network call per request.
Decide what happens if the limiter store is down: fail open (allow everything; the service stays up but unprotected) or fail closed (reject everything; safe but a full outage). For most APIs fail open is chosen; for login brute-force protection fail closed may be appropriate.
Telling the client
HTTP/1.1 429 Too Many Requests
Retry-After: 12
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1718000412
A good client reads Retry-After and backs off instead of retrying immediately (see the retries lesson).
Interview tip. Name the key, the algorithm and the storage. "I'd use a token bucket keyed by API key, held in Redis with an atomic update" is a complete answer. Candidates often forget the multi-server problem or the race condition in read-then-write.
Real-world example
A public API gives free keys 60 requests per minute with a burst of 10, and paid keys 6,000 per minute. The gateway applies a token bucket per API key in Redis. Over-limit calls get 429 with Retry-After. A separate stricter rule allows 5 login attempts per IP per 15 minutes, enforced fail-closed.
System design example
You must limit 10 million users to 100 requests per minute each across 30 gateway nodes at 200,000 requests/s total.
State per user (token bucket): 2 numbers x 8 bytes = 16 bytes + key overhead = about 100 bytes
Active users at once: say 2 million -> 200 MB in Redis (fits easily)
Redis calls: 200,000 requests/s -> 200,000 operations/s
One Redis node handles about 100,000 ops/s -> shard across 3 to 4 nodes by hashed user ID
Each gateway runs an atomic Lua script on the node owning the user key. Replicate each Redis shard for failover, and set keys to expire after the window so idle users cost no memory. Monitor the 429 rate per customer: a sudden jump means an abusive client or a limit set too low.
Interview discussion. "I'd rate limit at the gateway with a token bucket per API key. State lives in Redis, sharded by key, updated by an atomic script so concurrent requests can't both slip through. Over-limit requests get a 429 with Retry-After. If Redis is unreachable I'd fail open for normal APIs and fail closed for login."
Trade-off thinking. Token bucket allows bursts (good for users, more risk for a fragile backend); leaky bucket smooths output but delays; fixed window is cheapest but allows 2x at boundaries; sliding window log is exact but costs memory; sliding counter is the practical middle. Stricter limits protect the system but may reject legitimate spikes.
Key interview takeaway
Choose a key, a rule and an algorithm (token bucket by default), store state in a shared atomic store, return 429 with Retry-After, and state your fail-open or fail-closed choice. Be able to do the refill arithmetic on a whiteboard.
Real World Example
A public API gives free keys 60 requests per minute with a burst of 10, and paid keys 6,000 per minute, enforced by a token bucket per API key in Redis. Login attempts are limited separately to 5 per IP per 15 minutes, failing closed.
Common Interview Questions
Finished this lesson?
0 of 44 lessons done · 0% of the course

