Backend Case Studies

Topic B7

Rate limiters

Capping requests per user: fixed windows, sliding windows and token buckets.

9 min · intermediate

Watch: the limit is 3 requests per 10 seconds. Watch seconds 7 to 12: the first method lets too many through.

0s5s10s15s20swindow 1window 217891011121518
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 11

The limit: 3 requests per 10 seconds. Fixed window: count per fixed block of the clock, 0 to 10, 10 to 20. The counter resets at the start of each block.

Both use the same limit. The difference is which window gets counted.

Three ways to count

  • Fixed window: one counter per block of time (say per wall-clock minute), reset to 0 at the start of each block. Cheapest: one number per user. The figure shows its flaw: a user can send the full limit at the end of one block and the full limit again at the start of the next, so double the rate in a short burst.
  • Sliding window: count the requests in the last N seconds from now. Accurate, but the full version (a sliding log) stores the time of every request. The cheap version estimates it from two weighted fixed windows.
  • Token bucket: a bucket of tokens that refills at a fixed rate (say 1 token per second, up to 10). Each request takes a token; an empty bucket means refused. It allows short bursts up to the bucket size, then holds the average. AWS API Gateway and many others use it.
Code, for programmersA fixed window in Redis
async function allow(userId, limit = 100, windowSec = 60) {
  const window = Math.floor(Date.now() / 1000 / windowSec);
  const key = `rl:${userId}:${window}`;
  const count = await redis.incr(key);            // atomic: safe across many servers
  if (count === 1) await redis.expire(key, windowSec);
  return count <= limit;
}

// in the handler
if (!(await allow(user.id))) {
  res.set("Retry-After", "60").status(429).json({ error: "Too many requests" });
  return;
}

Where to put it

  • A shared counter: with 10 servers, an in-memory counter on each makes the real limit 10 times higher. Keep it in Redis or use a gateway.
  • The right key: per user for logged-in APIs; per IP for login and sign-up; per API key for API customers. One IP can be shared by hundreds of people in an office or on a mobile network.
  • Different limits per endpoint: login at 5 per minute, reading data at 1,000 per minute.

Quiz

  1. A limit of 100 per minute with a fixed window. At most how many requests can get through in 2 seconds?

  2. The rate limiter lives in each server's memory. There are 5 servers behind a load balancer. The effective limit?

  3. The right HTTP status for a request refused by a rate limiter?

0 of 3 answered.