A rate limiter caps how many requests a client may make in a period of time and rejects (or delays) the excess, usually with HTTP 429 Too Many Requests. It protects services from abuse and accidental overload, keeps one noisy customer from starving the rest, and enforces pricing tiers. The interesting parts are the algorithm (token bucket, leaky bucket, fixed or sliding windows) and doing it correctly across many servers.
Think of it like
An arcade token machine
Each player gets a cup that holds at most 10 tokens, and an attendant drops one new token into every cup every 30 seconds. Each game costs a token. A player who saved up can play 10 games in a row (a burst), but over an hour nobody plays more than 120 games. That cup is a token bucket, and it is exactly how most API rate limiters work.
Why rate limit?
- Stop abuse: brute-force logins, credential stuffing, scraping and spam.
- Protect capacity: a runaway script or retry loop in one client should not degrade the service for everyone else (the noisy neighbor problem).
- Control cost: each call may cost money downstream (SMS, payment APIs, GPU inference).
- Enforce product tiers: free plans get 100 requests per minute, paid plans 10,000.
- Smooth bursts: turn spiky traffic into a rate your databases can sustain.
Where to rate limit
| Layer | Typical key | Strengths | Limitations |
|---|---|---|---|
| Client / SDK | Per process | Cooperative: avoids wasted calls, backs off politely | Cannot be trusted; attackers ignore it |
| Edge / CDN / WAF | IP address, country, bot score | Absorbs floods and DDoS before they reach you | Coarse; knows little about users or plans |
| API gateway | API key, user ID, route | One central place for every service; plan-aware | Needs shared state across gateway instances |
| Service | Tenant, endpoint, operation cost | Closest to the protected resource; most context | Every service reimplements it unless shared |
Whatever the layer, choose the key carefully. User ID or API key is the fairest. IP addresses are a fallback for anonymous traffic, but many users can share one IP behind a corporate NAT or mobile carrier, and one attacker can rotate through many IPv6 addresses (limit by /64 prefix instead). Keys are often composite, such as user:42:POST:/orders.
Algorithms
Token bucket
A bucket holds up to B tokens and is refilled at r tokens per second. Each request removes one token (or more for expensive calls); if the bucket is empty, the request is rejected. Bursts up to B are allowed, and the long-run average can never exceed r. The refill does not need a timer: compute it lazily on each request from the time elapsed. AWS API Gateway and Stripe both use token buckets.
Example with B = 10 and r = 2 per second: a client fires 12 requests at t = 0. The first 10 succeed and empty the bucket; requests 11 and 12 get 429. At t = 1.5 s the bucket has refilled 3 tokens, so the next 3 requests succeed. Try different burst sizes and refill rates in the simulation above.
Leaky bucket
Requests enter a FIFO queue of capacity B and "leak" out to the service at a constant rate r. If the queue is full, new requests are dropped. The output is perfectly smooth, which suits traffic shaping for a fragile downstream, but bursts wait in the queue (adding latency) instead of being served immediately. NGINX's limit_req uses the leaky bucket method; its burst and nodelay options let you tune queueing.
Fixed window counter
Keep one counter per client per window, such as rl:user42:10:15 for the minute 10:15. Increment it on each request and reject once it exceeds the limit; the key expires with the window. It is the simplest and cheapest approach, but it allows bursts at window boundaries: with a limit of 100 per minute, a client can send 100 requests at 10:15:59 and 100 more at 10:16:00, which is 200 in two seconds.
Sliding window log
Store the timestamp of every accepted request (for example in a Redis sorted set). On each request, drop timestamps older than the window, count the rest and accept if the count is below the limit. It is exact, with no boundary problem, but stores one entry per request: a limit of 10,000 per hour means up to 10,000 timestamps per client.
Sliding window counter
A cheap approximation of the sliding log: keep the counts for the current and previous fixed windows, and weight the previous one by how much of it still overlaps the sliding window.
| Algorithm | Bursts | Memory per client | Accuracy | Notes |
|---|---|---|---|---|
| Token bucket | Allows bursts up to B | O(1): tokens + timestamp | Exact average rate | Most popular for APIs; supports weighted costs |
| Leaky bucket (queue) | Queued, output is smooth | O(B) queue | Exact output rate | Adds latency; good for traffic shaping |
| Fixed window | Up to 2× at boundaries | O(1): one counter | Approximate | Simplest; one INCR per request |
| Sliding window log | None beyond the limit | O(limit) timestamps | Exact | Memory heavy for large limits |
| Sliding window counter | Small, smoothed | O(1): two counters | Very close | Great default for high-volume limits |
Distributed rate limiting with Redis
With 20 gateway instances behind a load balancer, per-instance counters undercount: each one sees roughly a twentieth of a client's traffic, so the effective limit becomes 20× too high (and changes whenever you scale). The usual fix is a shared, fast store such as Redis, where every instance reads and updates the same counters.
The naive version and its race
import time
import redis
r = redis.Redis()
def allow(client_id: str, limit: int = 100, window: int = 60) -> bool:
key = f"rl:{client_id}:{int(time.time()) // window}"
count = r.incr(key) # atomic: concurrent gateways never lose increments
if count == 1:
r.expire(key, window) # BUG RISK: if the process dies right here,
# the key never expires and the client is blocked forever
return count <= limitINCRitself is atomic, so concurrent increments are never lost. The gap is betweenINCRandEXPIRE: a crash in between leaves an immortal key. Send both in aMULTI/EXECtransaction, or use a Lua script.- A read-modify-write in application code (
GETtokens, compute,SETtokens) is a real race: two gateways readtokens = 1at the same moment, both allow, and both write0. The client got two requests for one token. - Lua scripts run atomically in Redis: no other command interleaves while the script executes, so the whole refill, check and take sequence is one indivisible step and one network round trip.
- In Redis Cluster all keys a script touches must live in the same hash slot; using one key per client (or a
{hash tag}) satisfies this.
Operating it at scale
- Latency budget: one Redis round trip (about 0.2 to 1 ms in-region) per request. Keep Redis close to the gateways.
- Fail open or closed? If Redis is down, most public APIs fail open (allow traffic, maybe with a local fallback limit) rather than turning a cache outage into a full outage. Security-critical limits such as login attempts may fail closed.
- Hot keys: one huge customer hammers one Redis key. Shard by key across a Redis Cluster, or let each gateway take tokens in batches (lease 10 at a time) and serve them locally.
- Approximate local limiting: for very high volumes, give each of N instances a local bucket of limit ÷ N and reconcile periodically. Less exact, no network hop.
- Clock skew: compute time inside Redis (the
TIMEcommand) instead of trusting each gateway's clock.
HTTP 429 and rate-limit headers
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 12
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 12
{"error": "rate_limited", "message": "Limit of 100 requests per minute exceeded. Retry in 12 seconds."}- 429 Too Many Requests
- Defined in RFC 6585: this client has sent too many requests. Use
503 Service Unavailablewhen the whole service is overloaded regardless of who is calling. - Retry-After
- Standard HTTP header (RFC 9110): seconds to wait, or an HTTP date. Clients and SDKs should honor it.
- RateLimit-Limit / -Remaining / -Reset
- From early revisions of the IETF
RateLimitheader fields draft: the quota, what is left, and seconds until reset. Current revisions (still a draft) replace them withRateLimit-PolicyandRateLimitfields. X-RateLimit-*- The older de facto convention (GitHub, Twitter/X). Watch the units: GitHub's
x-ratelimit-resetis a Unix timestamp, while the IETF draft uses seconds remaining.
Multi-tier limits
Production systems stack several limits and a request must pass all of them. Short windows stop bursts, long windows enforce quotas, and different scopes protect different resources.
| Scope | Example limit | Purpose |
|---|---|---|
| Per user, burst | 20 requests per second | Absorb spikes, stop runaway loops |
| Per user, sustained | 1,000 per hour (free), 50,000 per hour (pro) | Enforce the pricing plan |
| Per user, daily quota | 10,000 per day | Cost control on expensive features |
| Per endpoint | POST /login: 5 attempts per 15 min per account and per IP | Brute-force protection |
| Per tenant, weighted | Export costs 50 tokens, read costs 1 | Fairness for uneven operations |
| Global | Shed non-critical traffic above 80% fleet utilization | Protect the system as a whole |
Implementation
Lazy refill on each call; `retryAfter` gives the value for the `Retry-After` header. Keep one bucket per client key.
import threading
import time
class TokenBucket:
"""Bursts up to capacity; long-run average of rate requests per second."""
def __init__(self, capacity: float, rate: float):
self.capacity = capacity
self.rate = rate # tokens added per second
self.tokens = capacity # start full
self.last = time.monotonic() # monotonic: immune to wall-clock jumps
self.lock = threading.Lock()
def _refill(self) -> None:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
def allow(self, cost: float = 1.0) -> bool:
with self.lock:
self._refill()
if self.tokens >= cost:
self.tokens -= cost
return True
return False
def retry_after(self, cost: float = 1.0) -> float:
"""Seconds until cost tokens are available."""
with self.lock:
self._refill()
return max(0.0, (cost - self.tokens) / self.rate)
buckets: dict[str, TokenBucket] = {} # evict idle buckets in production
def allow(client_id: str) -> bool:
bucket = buckets.setdefault(client_id, TokenBucket(capacity=10, rate=2))
return bucket.allow()Key takeaways
- Rate limiting protects capacity, stops abuse, controls cost and enforces plans; apply it at the edge, gateway and service layers.
- Token bucket allows bursts up to B with an average rate r using O(1) state; it is the default choice for APIs.
- Fixed windows are cheap but allow 2× bursts at boundaries; sliding window counters fix that with two counters.
- In a distributed system keep counters in a shared store and make updates atomic with
INCRor a Lua script. - Reject with
429,Retry-Afterand rate-limit headers, and have clients back off with jitter. - Decide explicitly whether the limiter fails open or closed when its store is unavailable.
Common pitfalls
- Counting per gateway instance, so the real limit silently scales with the number of instances.
- Non-atomic read-modify-write updates in application code that let concurrent requests overspend.
- Separate
INCRandEXPIREcalls that can leave keys without a TTL. - Limiting only by IP, which punishes users behind shared NATs and barely slows attackers with many IPs.
- Returning 429 without
Retry-After, so clients hammer the API with immediate retries.
Interview tips
- Start with requirements: what is the key, what are the limits, how strict must they be, and where does the limiter run.
- Compare at least token bucket, fixed window and sliding window counter, then pick one and justify it.
- Show the race condition in a naive Redis implementation and fix it with Lua or a transaction.
- Mention fail-open behavior, hot keys and multi-tier limits to show production experience.
Real-world applications
- Public APIs (GitHub, Stripe, OpenAI) enforcing per-key quotas.
- Login and OTP endpoints limiting attempts per account and per IP.
- API gateways and service meshes (Kong, Envoy, AWS API Gateway).
- Protecting downstream dependencies such as payment providers or SMS gateways.
- Crawlers limiting their own request rate per domain. See Design a Web Crawler.
Test yourself
A token bucket has capacity 10 and refills at 2 tokens per second. It is full at t = 0 and a client sends 15 requests instantly. How many succeed immediately?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.