Token Bucket Throttle With Burst Capacity

A token bucket limiter that refills at a steady rate, allows bursts up to capacity, and reports allow and deny decisions with a deterministic clock.

JavascriptData Fetching

Code

export class TokenBucket {
  constructor(options) {
    const { capacity, refillPerSecond, now = () => Date.now() } = options;
    if (!Number.isInteger(capacity) || capacity < 1) {
      throw new RangeError("capacity must be a positive integer");
    }
    if (!Number.isFinite(refillPerSecond) || refillPerSecond <= 0) {
      throw new RangeError("refillPerSecond must be a positive number");
    }
    this.capacity = capacity;
    this.refillPerSecond = refillPerSecond;
    this.now = now;
    this.tokens = capacity;
    this.lastRefill = now();
  }

  get available() {
    this.refill();
    return this.tokens;
  }

  tryConsume(cost = 1) {
    if (!Number.isFinite(cost) || cost <= 0) {
      throw new RangeError("cost must be a positive number");
    }
    if (cost > this.capacity) {
      throw new RangeError(`cost ${cost} exceeds bucket capacity ${this.capacity}`);
    }
    this.refill();
    if (this.tokens < cost) {
      return { allowed: false, remaining: this.tokens };
    }
    this.tokens -= cost;
    return { allowed: true, remaining: this.tokens };
  }

  refill() {
    const t = this.now();
    const elapsedMs = Math.max(0, t - this.lastRefill);
    const gained = (elapsedMs / 1000) * this.refillPerSecond;
    this.tokens = Math.min(this.capacity, this.tokens + gained);
    this.lastRefill = t;
  }
}

A fixed window counter lets a full burst through at each window boundary, and naive sleep loops cannot handle variable request costs.

Use case: engineers protecting outbound APIs or background jobs from bursts

Inputs / outputs

  • Input: refill rate per second, burst capacity, current time in ms
  • Output: boolean decision (allowed or denied) plus the remaining token count

Error conditions

  • non-positive capacity or refill rate
  • request cost exceeding capacity

Approach

track tokens and last refill timestamp; each tryConsume refills elapsed time first, then deducts the requested cost if available.

Implementation

export class TokenBucket {
  constructor(options) {
    const { capacity, refillPerSecond, now = () => Date.now() } = options;
    if (!Number.isInteger(capacity) || capacity < 1) {
      throw new RangeError("capacity must be a positive integer");
    }
    if (!Number.isFinite(refillPerSecond) || refillPerSecond <= 0) {
      throw new RangeError("refillPerSecond must be a positive number");
    }
    this.capacity = capacity;
    this.refillPerSecond = refillPerSecond;
    this.now = now;
    this.tokens = capacity;
    this.lastRefill = now();
  }

  get available() {
    this.refill();
    return this.tokens;
  }

  tryConsume(cost = 1) {
    if (!Number.isFinite(cost) || cost <= 0) {
      throw new RangeError("cost must be a positive number");
    }
    if (cost > this.capacity) {
      throw new RangeError(`cost ${cost} exceeds bucket capacity ${this.capacity}`);
    }
    this.refill();
    if (this.tokens < cost) {
      return { allowed: false, remaining: this.tokens };
    }
    this.tokens -= cost;
    return { allowed: true, remaining: this.tokens };
  }

  refill() {
    const t = this.now();
    const elapsedMs = Math.max(0, t - this.lastRefill);
    const gained = (elapsedMs / 1000) * this.refillPerSecond;
    this.tokens = Math.min(this.capacity, this.tokens + gained);
    this.lastRefill = t;
  }
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { TokenBucket } from "./example.mjs";

test("allows a burst up to capacity", () => {
  let clock = 0;
  const bucket = new TokenBucket({ capacity: 3, refillPerSecond: 1, now: () => clock });
  assert.equal(bucket.tryConsume().allowed, true);
  assert.equal(bucket.tryConsume().allowed, true);
  assert.equal(bucket.tryConsume().allowed, true);
  const denied = bucket.tryConsume();
  assert.equal(denied.allowed, false);
});

test("denies when tokens are exhausted", () => {
  let clock = 0;
  const bucket = new TokenBucket({ capacity: 2, refillPerSecond: 1, now: () => clock });
  bucket.tryConsume(2);
  const denied = bucket.tryConsume(1);
  assert.equal(denied.allowed, false);
  assert.equal(denied.remaining, 0);
});

test("refills over time at the configured rate", () => {
  let clock = 0;
  const bucket = new TokenBucket({ capacity: 5, refillPerSecond: 10, now: () => clock });
  bucket.tryConsume(5);
  clock = 100; // 100ms at 10/s = 1 token
  const first = bucket.tryConsume(1);
  assert.equal(first.allowed, true);
  assert.equal(bucket.tryConsume(1).allowed, false);
});

test("rejects invalid options and costs", () => {
  assert.throws(() => new TokenBucket({ capacity: 0, refillPerSecond: 1 }), RangeError);
  const bucket = new TokenBucket({ capacity: 2, refillPerSecond: 1 });
  assert.throws(() => bucket.tryConsume(0), RangeError);
  assert.throws(() => bucket.tryConsume(99), RangeError);
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node example.mjs

Limitations and error handling

single-process only; no distributed coordination; no persistence of token state.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic