Scaling and running in production · senior
Rate limiting algorithms: token bucket and sliding window
A token bucket gives each client a bucket of tokens that refills at a steady rate (allowing short bursts up to its size), while window algorithms count requests per time window; across many servers the counters live in Redis and are updated atomically.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Fixed window: count per clock window (e.g. per minute). Simple, but allows 2x the limit around the boundary (end of one window + start of the next).
- Sliding window log: keep request timestamps, drop those older than the window. Exact, but memory grows with the limit.
- Sliding window counter: weight the previous window's count by how much of it overlaps. Close to exact with two counters.
- Token bucket: capacity C, refill rate R per second; each request takes a token; refill lazily from elapsed time (tokens = min(C, tokens + elapsed x R)). Allows bursts up to C and an average of R. Leaky bucket smooths output at a constant rate.
- Distributed: store state in Redis and update atomically (INCR + EXPIRE for fixed windows; a Lua script for token bucket). Per-instance memory is not shared.
- Respond 429 with Retry-After (and RateLimit headers); choose the key (user, API key, IP, endpoint); bound memory for idle keys (TTL or LRU).
- Within one Node process, check-and-update is safe because no other JavaScript runs in between (single thread); that breaks once state is shared across processes without atomic operations.
The red pen
Common traps: mistake → fix
Mistake: Fixed window is accurate
Fix: it allows bursts of up to twice the limit across a window boundary.
Mistake: A per-process limiter limits the whole API
Fix: each process counts separately; clients get N times the limit.
Mistake: Read the count from Redis, then write count + 1
Fix: two servers can read the same value; use atomic INCR or a Lua script.
Easy to hard
Questions interviewers ask, easy to hard
- Design a rate limiter for an API: which algorithm and why?
- Explain the token bucket. What do capacity and refill rate control?
- Fixed vs sliding window: what is the boundary problem?
- How do you make it work across 20 instances? What about Redis being down?
- Why is the check-and-consume safe inside one event loop, and what breaks that?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.