Design an API Rate Limiter
medium 45 minDecide, in about a millisecond and on every request, whether this caller may go on.
See it run
One request at a time: a bucket check, a sliding window, two gateways that race, and a lease.
Operations
Token bucket check
Every request makes one trip to a script that refills, compares and takes a token.
Step 1 of 11
A request arrives
caller
user 12345
It carries an API key or a signed token. Why: we need to know whose bucket to use.
Step 1: A request arrives
def handle(request): key = rate_key(request) # user and endpoint ok, left, retry = redis.evalsha(BUCKET, key, size, rate, 1) if not ok: return 429, {"Retry-After": retry} response = backend.call(request) response.headers["X-RateLimit-Remaining"] = left return response- Latency
- about 0.5 ms
- Store calls
- 1
Nothing refills in the background. The script works out the refill when a request arrives.
In the real world
The same design an api rate limiter doing real jobs. Pick one and step through it.
The limiter must not become the outage.
Step 1 of 5
No answer
timeout
2 ms
After 2 ms the gateway stops waiting.
Step 1: No answer
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Reading, deciding and writing in three steps
criticalTwo gateways can decide from the same old value.
Wrongtokens = redis.get(key)if tokens > 0: redis.set(key, tokens - 1)Rightok = redis.evalsha(BUCKET, key, size, rate, 1)Deciding from a cached count
criticalEvery gateway spends the same remaining tokens.
Wrongleft = local_cache.get(key)return left > 0Right# lease: tokens are taken before useok = redis.evalsha(BUCKET, key, size, rate, 10)Using each gateway's clock
majorGateways disagree, so refill jumps back and forth.
Wrongnow = time.time() # in the gatewayRightlocal t = redis.call('TIME') -- in the scriptA long timeout to the store
criticalWaiting requests fill the gateway and stop unrelated callers.
Wrongredis.timeout = 5.0Rightredis.timeout = 0.002# then the local bucketForgetting the burst in the promise
minor100 a minute with a burst of 20 admits 120 in the best minute.
Wrongsize = 20; rate = 100 / 60Rightsize = 20; rate = 80 / 60 # 100 in any minute
Interview tips
Lead with numbers
- 10M checks a second, 30M at peak.
- 100 primaries a region, from operations.
- State is only 15 GB.
Show the trade-off
- Token bucket for bursts, sliding window for per-minute promises.
- Leases save calls and strand tokens.
- Shares respect the total and may refuse early.
Plan the failure
- 2 ms, circuit, local 2%.
- Login refuses.
- Watch refusal rate and p99 of the check.
Think of the client
- Headers on every response.
- Retry-After on 429.
- An endpoint that explains a refusal.