← Back to JavaScript, page 6

javascript-0106 · Hard senior

How do you implement a rate limiter in JavaScript, and what is the difference between a token bucket and a sliding window?

A token bucket holds up to a capacity of tokens that refill at a steady rate, and each request takes one token, which allows short bursts but a steady average. A sliding window log stores timestamps and allows at most a limit of requests in any window, which is exact but uses more memory. Inject the clock so the limiter is testable.

Full answer

A rate limiter protects a service or an API client from too many requests. Two common algorithms differ in memory use and in how they treat bursts.

Token bucket: the bucket has a capacity and a refillPerSecond rate. Each request needs one token. Tokens are not added by a timer. Instead, on each call, compute the elapsed time since the last check, add elapsed * rate tokens, and cap the total at the capacity. If at least one token is available, take it and allow the request. The state is two numbers per client, so it is cheap. It allows a burst up to the capacity, and then a steady rate. Many public APIs use it.

Sliding window log: keep the timestamps of accepted requests in an array. On each call, drop timestamps older than now - windowMs, then allow the request only if fewer than limit remain. It is exact: no window ever holds more than the limit. The cost is memory proportional to the limit per client. A cheaper approximation is a fixed window counter, which has a known flaw: a client can send a full limit at the end of one window and again at the start of the next, doubling the rate for a moment.

Practical points:

  • Pass the clock in as a function (now = () => Date.now()), so tests can control time. Prefer performance.now() for in-process timing since it does not jump when the system clock changes.
  • Use one limiter per key, for example per user id or IP address, in a Map, and remove idle keys to avoid a memory leak.
  • A single Node.js process works as is. With several servers, the state has to live in a shared store such as Redis, and the check and update must be atomic, for example in a Lua script.
  • Return how long to wait (retryAfterMs), so servers can send a Retry-After header.
javascript
class TokenBucket {
  constructor({ capacity, refillPerSecond, now = () => Date.now() }) {
    this.capacity = capacity;
    this.refillPerSecond = refillPerSecond;
    this.now = now;
    this.tokens = capacity;
    this.last = now();
  }
  take() {
    const time = this.now();
    this.tokens = Math.min(this.capacity, this.tokens + ((time - this.last) / 1000) * this.refillPerSecond);
    this.last = time;
    if (this.tokens >= 1) {
      this.tokens -= 1;
      return { allowed: true, retryAfterMs: 0 };
    }
    return { allowed: false, retryAfterMs: Math.ceil(((1 - this.tokens) / this.refillPerSecond) * 1000) };
  }
}

class SlidingWindow {
  #hits = [];
  constructor({ limit, windowMs, now = () => Date.now() }) {
    this.limit = limit;
    this.windowMs = windowMs;
    this.now = now;
  }
  take() {
    const time = this.now();
    while (this.#hits.length > 0 && this.#hits[0] <= time - this.windowMs) this.#hits.shift();
    if (this.#hits.length < this.limit) {
      this.#hits.push(time);
      return { allowed: true, retryAfterMs: 0 };
    }
    return { allowed: false, retryAfterMs: this.#hits[0] + this.windowMs - time };
  }
}

let clock = 0;
const now = () => clock;
const results = (limiter, times) =>
  times.map((time) => {
    clock = time;
    const r = limiter.take();
    return r.allowed ? 'ok' : `wait ${r.retryAfterMs}`;
  });

const bucket = new TokenBucket({ capacity: 3, refillPerSecond: 1, now });
console.log('bucket:', results(bucket, [0, 0, 0, 0, 500, 1000, 1000, 5000, 5000, 5000, 5000]).join(', '));

clock = 0;
const windowLimiter = new SlidingWindow({ limit: 3, windowMs: 1000, now });
console.log('window:', results(windowLimiter, [0, 100, 200, 300, 999, 1000, 1100, 1200, 1300]).join(', '));

// fixed window flaw: 6 requests in 200 ms across a boundary pass a fixed counter, but not a sliding window
const fixed = { count: 0, windowStart: 0 };
const fixedTake = (time) => {
  const start = Math.floor(time / 1000) * 1000;
  if (start !== fixed.windowStart) Object.assign(fixed, { count: 0, windowStart: start });
  return fixed.count++ < 3;
};
const burst = [900, 910, 920, 1000, 1010, 1020];
clock = 0;
const strict = new SlidingWindow({ limit: 3, windowMs: 1000, now });
console.log('fixed window allows:', burst.filter(fixedTake).length, 'sliding window allows:', burst.filter((t) => ((clock = t), strict.take().allowed)).length);

Run with Node.js v24.22.1 as js-106.js; two runs gave identical output. Output: bucket: ok, ok, ok, wait 1000, wait 500, ok, wait 1000, ok, ok, ok, wait 1000 window: ok, ok, ok, wait 700, wait 1, ok, ok, ok, wait 700 fixed window allows: 6 sliding window allows: 3

Key points

  • Token bucket: capacity plus refill rate; allows bursts and a steady average; two numbers of state.
  • Refill lazily on each call from the elapsed time, capped at capacity.
  • Sliding window log: exact per window but stores timestamps; fixed window counters allow a double burst at boundaries.
  • Inject the clock for tests; keep one limiter per key and clean up idle keys.
  • Several servers need shared atomic state, such as Redis.

Common mistakes

  • Using setInterval to add tokens instead of computing the refill from elapsed time.
  • Letting the token count grow past the capacity after a long pause.
  • Using fixed window counters and allowing double bursts at window boundaries.
  • Keeping limiter state per user in a Map forever.

Follow-ups

  • How would you share this limiter across several servers?
  • What is a leaky bucket and how is it different from a token bucket?
  • How would you test a limiter without waiting in real time?

Tips

  • Name both algorithms and the trade-off: memory against exactness and burst behavior.
  • Inject the clock and say why.
  • Mention Retry-After and shared state for several servers.