Rate Limiting & Quotas
Why and where to rate limit, the five classic algorithms (fixed window, sliding log, sliding window counter, token bucket, leaky bucket/GCRA) with code, distributed rate limiting with Redis and Lua, response headers, client behaviour, quotas and fairness.
Why rate limit?
- Protect availability — stop one client (buggy loop, scraper, attacker) from starving everyone.
- Fairness — share capacity across tenants.
- Security — slow brute force, credential stuffing, enumeration, OTP guessing.
- Cost control — expensive downstreams (LLM calls, SMS, third-party APIs).
- Monetisation — plans with different quotas.
Where to limit
The algorithms
| Algorithm | Memory per key | Accuracy | Bursts | Notes |
|---|---|---|---|---|
| Fixed window counter | O(1) | boundary spikes up to 2× | uncontrolled | INCR + EXPIRE; simplest |
| Sliding window log | O(requests in window) | exact | none beyond limit | sorted set of timestamps |
| Sliding window counter | O(1) | ~exact (assumes even spread) | smoothed | Cloudflare's approach |
| Token bucket | O(1) | exact | controlled (capacity) | most popular |
| Leaky bucket / GCRA | O(1) | exact | none (smooth output) | GCRA = token bucket expressed as a "theoretical arrival time" |
Token bucket (in-process)
import time, threading
class TokenBucket:
def __init__(self, rate: float, capacity: int):
self.rate, self.capacity = rate, capacity
self.tokens = float(capacity)
self.updated = time.monotonic()
self.lock = threading.Lock()
def allow(self, cost: float = 1.0) -> bool:
with self.lock:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= cost:
self.tokens -= cost
return True
return False
limiter = TokenBucket(rate=10, capacity=20) # 10 req/s sustained, bursts of 20
class TokenBucket {
private tokens: number;
private updated = performance.now();
constructor(private rate: number, private capacity: number) { this.tokens = capacity; }
allow(cost = 1): boolean {
const now = performance.now();
this.tokens = Math.min(this.capacity, this.tokens + ((now - this.updated) / 1000) * this.rate);
this.updated = now;
if (this.tokens < cost) return false;
this.tokens -= cost;
return true;
}
}
Sliding window counter
estimate = count(current window) + count(previous window) × (1 − elapsed_fraction_of_current_window)
limit 100/min, at 12:01:15 (25% into the window):
previous window (12:00) = 80, current (12:01) = 30
estimate = 30 + 80 × 0.75 = 90 → allowed (< 100)
Sliding window log
# Redis sorted set: one member per request
def allow(r, key, limit, window_s, now_ms, req_id):
pipe = r.pipeline()
pipe.zremrangebyscore(key, 0, now_ms - window_s * 1000) # drop old entries
pipe.zadd(key, {req_id: now_ms})
pipe.zcard(key)
pipe.pexpire(key, window_s * 1000)
_, _, count, _ = pipe.execute()
return count <= limit # (a rejected request still counted — fine for abuse limits)
Distributed token bucket in Redis (atomic Lua)
-- KEYS[1] = bucket key; ARGV = rate (tokens/s), capacity, cost
local rate, capacity, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local t = redis.call('TIME') -- server clock: no app clock skew
local now = tonumber(t[1]) + tonumber(t[2]) / 1e6
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * rate)
local allowed = 0
if tokens >= cost then tokens = tokens - cost; allowed = 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) * 2)
return {allowed, tokens}
import redis
r = redis.Redis()
bucket = r.register_script(open("token_bucket.lua").read())
def check(api_key: str, endpoint_class: str) -> bool:
allowed, remaining = bucket(keys=[f"rl:{api_key}:{endpoint_class}"], args=[10, 20, 1])
return allowed == 1
Responses and client behaviour
HTTP/1.1 429 Too Many Requests
Retry-After: 12
RateLimit-Policy: "default";q=100;w=60
RateLimit: "default";r=0;t=12
Content-Type: application/problem+json
{"type":"https://api.example.com/errors/rate-limited","title":"Too many requests","status":429,
"detail":"Limit of 100 requests per 60 s for key sk_live_51Hc… exceeded."}
Well-behaved clients: honour Retry-After, back off exponentially with jitter, spread scheduled jobs (no cron at :00 for everyone), and cap concurrency.
Choosing keys and limits
| Key | Use |
|---|---|
| API key / OAuth client | public APIs, plans |
| User ID | per-user fairness |
| Tenant | noisy-neighbour protection |
| IP / subnet / ASN | unauthenticated endpoints, bots (beware NAT/CGNAT sharing IPs) |
| Endpoint class / cost | expensive operations get stricter limits or higher token cost |
| Composite | tenant + endpoint, user + action |
Cost-based limiting: charge more tokens for expensive operations (search, exports, LLM tokens) instead of counting requests equally — GitHub's GraphQL API and LLM APIs (tokens per minute) do this.
Operational concerns
- Failure mode when the limiter store is down: fail open (most APIs) or closed (auth/SMS).
- Latency: keep the check sub-millisecond; local caches for hot keys; pipeline/batch.
- Observability: metrics of allowed/denied per key; alert on sudden spikes; dashboards for customers.
- Exemptions and overrides: internal traffic, enterprise plans, temporary increases.
- Test with load tests, including boundary bursts and clock skew.
See the rate limiter case study for a full system design answer.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.