Skip to the page

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.

The 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

  1. Design a rate limiter for an API: which algorithm and why?
  2. Explain the token bucket. What do capacity and refill rate control?
  3. Fixed vs sliding window: what is the boundary problem?
  4. How do you make it work across 20 instances? What about Redis being down?
  5. Why is the check-and-consume safe inside one event loop, and what breaks that?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview