Sikau

System design · Day 9 · about 40 min

Rate limiting

A token bucket that lets bursts through but caps the average.

One noisy client

On the morning of an exam-result day, one badly written script in Pokhara calls your API 5,000 times a second. Every other learner now waits. A rate limiter protects the many from the few: each client gets a budget, and requests beyond it are refused quickly with a 429 Too Many Requests instead of slowly dragging the whole system down.

The classic recipe is the token bucket. Picture a jar that holds at most capacity tokens and gains refillPerSec tokens every second. Each request takes one token. An empty jar means "try again later". A quiet client slowly fills its jar, so it can burst; a flooding client just runs dry.

Refill lazily, store almost nothing

You don't need a timer topping up every jar. Store two numbers per client: the tokens left and the time you last looked. On each request, compute how many tokens *would have* arrived since then, add them (never past capacity), then spend one.

function createLimiter({ capacity, refillPerSec, now = () => Date.now() }) {
  const buckets = new Map();
  function bucket(key) {
    const t = now();
    const b = buckets.get(key) || { tokens: capacity, at: t };
    b.tokens = Math.min(capacity, b.tokens + ((t - b.at) / 1000) * refillPerSec);
    b.at = t;
    buckets.set(key, b);
    return b;
  }
  return {
    allow(key) {
      const b = bucket(key);
      if (b.tokens < 1) return false;
      b.tokens -= 1;
      return true;
    },
    remaining(key) {
      return Math.floor(bucket(key).tokens);
    },
  };
}

Where does the counter live? With several API servers it must be shared (Redis is the usual choice), or each server enforces only its own slice of the limit.

The rest of this lesson

  • What to do with a refused requestexplain
  • The empty jarpredict
  • One request through the limiterorder
  • Limiter vocabularymatch
  • Build a token bucketwrite code
  • Badge quizquiz
  • What you learnedrecap