Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Token bucket rate limiter in JavaScript

46 A token bucket, and the burst it allows

hard

Write a token bucket: capacity tokens, one more every refillMs, never more than the capacity. Take tokens until it is empty, advance an injected clock and watch them come back. Then wrap a call so an empty bucket is a rejection rather than a wait.

Stuck? Three hints, smallest first
  1. 1. Do not run a timer. Work out how many tokens were earned from the elapsed time when someone asks.
  2. 2. Math.floor(elapsed / refillMs) tokens are due; move lastRefill forward by exactly that many intervals, not to now.
  3. 3. Cap at the capacity, or an idle bucket banks a burst it was never meant to allow.

The answer

const fakeClock = () => {
  let now = 0;
  return { get time() { return now; }, advance(ms) { now += ms; } };
};

function tokenBucket({ capacity, refillMs, clock }) {
  let tokens = capacity;
  let lastRefill = clock.time;

  const refill = () => {
    const earned = Math.floor((clock.time - lastRefill) / refillMs);
    if (earned > 0) {
      tokens = Math.min(capacity, tokens + earned);   // the cap is the whole point
      lastRefill += earned * refillMs;                // keep the remainder
    }
  };

  return {
    take() { refill(); if (tokens === 0) return false; tokens--; return true; },
    get available() { refill(); return tokens; },
  };
}

const limited = (fn, bucket) => async (...args) => {
  if (!bucket.take()) throw new Error('429: rate limit exceeded');
  return fn(...args);
};

const clock = fakeClock();
const bucket = tokenBucket({ capacity: 3, refillMs: 100, clock });

const burst = [bucket.take(), bucket.take(), bucket.take(), bucket.take()];
const emptied = bucket.available;

clock.advance(99);
const justBefore = [bucket.available, bucket.take()];
clock.advance(1);
const atTheRefill = [bucket.available, bucket.take(), bucket.available];

clock.advance(1000);                                  // ten intervals of idling
const banked = bucket.available;

let calls = 0;
const sendSms = limited(async (to) => { calls++; return 'sent to ' + to; }, bucket);
const sent = [
  await sendSms('0801').catch((err) => err.message),
  await sendSms('0802').catch((err) => err.message),
  await sendSms('0803').catch((err) => err.message),
  await sendSms('0804').catch((err) => err.message),
];

console.log('burst of four :', burst, '- left:', emptied);
console.log('at 99ms / 100ms:', justBefore, '/', atTheRefill);
console.log('after idling 1000ms:', banked, 'not 10');
console.log('sms            :', sent, '- calls made:', calls);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a fresh bucket allows a burst up to its capacity, then refuses', burst, [true, true, true, false]);
test('and is empty afterwards', emptied, 0);
test('one millisecond before the interval nothing has come back', justBefore, [0, false]);
test('at the interval exactly one token is available, and one only', atTheRefill, [1, true, 0]);
test('idling for ten intervals still banks no more than the capacity', banked, 3);
test('the wrapper turns an empty bucket into a rejection, not a wait', sent, ['sent to 0801', 'sent to 0802', 'sent to 0803', '429: rate limit exceeded']);
test('so the refused call never reached the service', calls, 3);
test('and the bucket is empty again, having spent exactly three tokens', bucket.available, 0);

The trick is that there is no timer. Tokens are computed from elapsed time at the moment somebody asks, which means an idle bucket costs nothing at all — no interval, no callback, no wakeups on a page with fifty rate-limited widgets. A hundred buckets that nobody is using are a hundred integers.

lastRefill += earned * refillMs rather than lastRefill = clock.time is the detail worth stealing. Assigning now would throw away the remainder every time somebody checked, so a caller polling available every 99ms would earn tokens more slowly than one who never looked. Advancing by whole intervals makes the refill rate independent of who asks and when.

The cap is what makes it a token bucket rather than a counter. A burst of three is allowed on purpose: real traffic is bursty, and a limiter that permits exactly one call per 100ms with no slack rejects perfectly reasonable usage. Idling for a second and then getting ten calls, though, would defeat the limit entirely — which is the fifth assertion.

The wrapper here rejects, and that is a decision, not a default. Rejecting is right at an API boundary where the caller should back off and knows how. Queuing until a token frees up — the semaphore shape from exercise 29, with the clock instead of a permit count — is right inside a job runner where nobody is waiting on a response. Silently dropping is right for telemetry and almost nothing else.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.