Skip to content
jshacks.dev
Async

Build a token bucket for API calls

Build a token bucket for API calls in JavaScript: tokens refill over time, each call takes one, and bursts up to the capacity are allowed.

1 min read
Summarize in AI

A token bucket allows a burst up to its capacity and then a steady rate. The bucket refills as time passes, and each call must take a token.

JavaScript
class TokenBucket {
  #tokens;
  #updated;
  constructor(capacity, perSecond, now = () => Date.now()) {
    this.capacity = capacity;
    this.perSecond = perSecond;
    this.now = now;
    this.#tokens = capacity;
    this.#updated = now();
  }
  tryTake() {
    const t = this.now();
    const refill = ((t - this.#updated) / 1000) * this.perSecond;
    this.#tokens = Math.min(this.capacity, this.#tokens + refill);
    this.#updated = t;
    if (this.#tokens < 1) return false;
    this.#tokens -= 1;
    return true;
  }
}

let clock = 0;
const bucket = new TokenBucket(2, 1, () => clock);
console.log(bucket.tryTake(), bucket.tryTake(), bucket.tryTake());

clock = 1500;
console.log(bucket.tryTake(), bucket.tryTake());
Text
true true false
true false

The bucket starts with two tokens, so two calls pass and the third is refused. After 1.5 seconds at one token per second it holds 1.5 tokens: one call passes and leaves 0.5, and the next is refused. The clock is passed in so the example is repeatable; in real use the default Date.now applies.

Refilling on demand needs no timer. When tryTake returns false, either reject the call, such as with an HTTP 429, or wait and retry.

Also inAPIs
Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.