Skip to content
Backend logic · Core · about 20 minutes

Token bucket rate limiter

Implement createLimiter({ capacity, refillPerSecond }). It returns an object whose tryRemove() returns true and takes one token when the bucket has at least one whole token, and returns false otherwise. The bucket starts full. Tokens come back continuously at refillPerSecond, so half a second at 4 per second adds 2, and the bucket never holds more than capacity. A denied call takes nothing. Read the time with Date.now(). In the tests an op [at, method, ...args] calls that method at virtual time at (ms); the answer lists what each call returned.

Start from

function createLimiter({ capacity, refillPerSecond }) {
  // Return { tryRemove() } backed by a bucket of tokens.
}

Hints

Each hint gives away a little more. Open one only when you need it.

  1. Hint 1

    Keep two numbers: tokens, which can be fractional, and the time you last added tokens.

  2. Hint 2

    On each call, add (now - last) / 1000 * refillPerSecond tokens, cap at capacity, set last = now, then check tokens >= 1.

  3. Hint 3

    Never round the tokens down: rounding loses the part of a token that was already earned.

Solution

The app has this lab in JavaScript, TypeScript and Python. This page shows the JavaScript code.

From here on the page gives the method away. If you are still solving, go back to the hints.

JavaScript
function createLimiter({ capacity, refillPerSecond }) {
  let tokens = capacity;
  let last = Date.now();
  return {
    tryRemove() {
      const now = Date.now();
      tokens = Math.min(capacity, tokens + ((now - last) / 1000) * refillPerSecond);
      last = now;
      if (tokens < 1) return false;
      tokens -= 1;
      return true;
    },
  };
}

What an interviewer looks for

Rate limits protect every public API, and the token bucket is the one most gateways use. Interviewers ask for it to see whether you can turn a rate into state and time, without a timer per user.