RATE LIMITING
Token bucket, sliding window, and the burst that gets through anyway
A fixed-window limiter counts each client’s requests per clock second, resets the count at each new second, and allows 10 per second. A client sends 10 requests at t=900–990 ms and 10 more at t=1000–1090 ms. How many are accepted?
A fixed-window counter resets at each boundary. A client that sends its limit at the end of one window and again at the start of the next gets twice the limit in a span shorter than a window. A token bucket has no boundary: it holds up to capacity tokens, refills at rate per second, and each request spends one. Capacity is the biggest burst you allow; rate is what you sustain. In any window of W seconds it admits at most capacity + rate × W, wherever the window starts.
// fixed window: resets on the boundary, so 2x limit fits in one second
const win = Math.floor(now / 1000);
if (win !== cur) { cur = win; count = 0; }
if (count < limit) { count++; return true; }
return false;// token bucket: lazy refill, capped at capacity
tokens = Math.min(capacity, tokens + (now - last) * rate / 1000);
last = now;
if (tokens >= 1) { tokens -= 1; return true; }
return false; Watch the invariant strip: each limiter is held to what it promises in any 1 s window, the limit for the fixed window and rate + burst for the bucket. The fixed window breaks it on the second batch and then rejects the steady traffic that follows. The token bucket, under the same stream, spends its 5 tokens and admits the rest at the refill rate, so the steady traffic gets through.
A page load legitimately fires 8 API calls at once. A flood sends 30 in 300 ms. Set BURST (and RATE if you like) so the bucket admits all 8 legitimate calls but lets at most 14 of the 30 flood requests through.
GOAL: legit burst 8/8 admitted and flood <= 14/30 admitted
Finish TokenBucket.allow(now). Refill lazily from the time since the last call, never above capacity, and spend one token per accepted request. The grader drives timestamps and compares every decision to a reference.
API gateways and per-client quotas, login and OTP endpoints, outbound calls to a third party with its own quota, worker pools pulling from a queue. The symptom of a bad limiter is a spike that the dashboards say was within limits.
“Design a rate limiter.” Name the two numbers, explain the fixed-window boundary problem, describe the token bucket with lazy refill, and say how you would store one bucket per client (a timestamp and a token count, in memory or in Redis with a Lua script).
USED IN
Chapters that build on this lesson.
- Growth and product-led motionsProduct Manager
- Platform, API and technical PMProduct Manager
- Fraud and abuse: where security meets the productSecurity
- Kubernetes and edge security: clusters, containers, CDN and WAFSecurity
- Threat modellingSecurity