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.
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.
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());true true false
true falseThe 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.