Difficulty: Intermediate
How would you rate limit an API? Explain the token bucket algorithm and what the responses should look like.
Rate limiting is the bouncer at the club door. Without it, one buggy client in an infinite retry loop, or one abusive scraper, can consume all capacity and hurt everyone else. It protects availability, controls cost, enforces fair use across tenants, and slows down brute force and credential stuffing attacks. It is also often a product feature, since pricing plans have different quotas.
There are several algorithms. Fixed window counter: allow N requests per calendar window, such as 100 per minute. It is simple and cheap, but suffers from a boundary burst where a client sends 100 at 12:00:59 and another 100 at 12:01:00, getting 200 in two seconds. Sliding window log: store timestamps of each request and count those in the last window. It is precise but memory hungry. Sliding window counter: blend the current and previous fixed window counts to approximate a sliding window with little memory. Leaky bucket: requests enter a queue that drains at a constant rate, smoothing bursts into a steady output, good for protecting a downstream.
Token bucket is the most popular in APIs because it permits controlled bursts. Imagine a bucket holding up to B tokens. Tokens are added at rate R per second, up to the capacity. Each request consumes one token; if the bucket is empty the request is rejected. So the client can burst up to B requests at once, but the long term average is capped at R. Stripe and AWS use variants. Implementation only needs two values per key: the current token count and the last refill timestamp. On each request compute elapsed time, add elapsed times R tokens capped at B, then try to consume one.
In a distributed deployment the counters must be shared, typically in Redis. Use an atomic Lua script or a single command such as INCR with EXPIRE to avoid race conditions between read and write. Alternatively, rate limit at the API gateway or a sidecar, so the application code stays clean. Trade-offs to mention: a central Redis adds latency and a failure mode, so decide fail-open versus fail-closed; some systems keep small local buckets and sync periodically for speed.
Keys: limit per API key or user for authenticated traffic, per IP for anonymous traffic (careful with NAT, where many users share one IP), and optionally per endpoint, because a login route deserves a much tighter limit than a read route. Tiered limits per plan are common.
Response design: return 429 Too Many Requests with a Retry-After header stating seconds to wait, and a problem+json body. Also advertise limits on every response so well-behaved clients can self-throttle. The widely used headers are X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset; the IETF draft standardises them as RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset.
Client side: respond to 429 with exponential backoff and jitter, honouring Retry-After, instead of immediate retries which amplify the problem. Mention that rate limiting is different from load shedding: limits enforce per-client fairness, while load shedding drops requests when the whole system is overloaded, returning 503.
Finally, be careful with cost: expensive endpoints should consume more than one token, which gives you weighted limits, and GraphQL needs query cost analysis instead of request counting.
-- KEYS[1]=bucket key, ARGV: capacity, refill_per_sec, now_ms
local data = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local cap, rate, now = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local tokens = tonumber(data[1]) or cap
local ts = tonumber(data[2]) or now
tokens = math.min(cap, tokens + (now - ts) / 1000 * rate)
local allowed = 0
if tokens >= 1 then tokens = tokens - 1; allowed = 1 end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000) * 2)
return { allowed, math.floor(tokens) }
Refill, check and consume happen atomically inside Redis, avoiding race conditions across app servers.
HTTP/1.1 429 Too Many Requests
Retry-After: 12
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 12
Content-Type: application/problem+json
{ "type": "https://api.example.com/problems/rate-limited", "title": "Too many requests", "status": 429 }
Tells the client exactly when to try again and what the quota is.
rate limiting, token bucket, 429, Retry-After