A token-bucket rate limiter class
Limit how often something may happen
Coding, Medium
Small real code that works when called late, twice, or with bad input.
Write a class TokenBucket in JavaScript (or the same idea in another language) that limits how often something may happen inside one process. The constructor takes capacity (most tokens the bucket holds), refillPerSec (tokens added each second, may be a fraction) and now (a function that returns the time in milliseconds; default: the system clock). The bucket starts full. tryTake(n = 1) takes n tokens and returns true if the bucket has at least n. If it has fewer, it takes nothing and returns false. Tokens are added as time passes, and the bucket never holds more than capacity. Do not use timers or loops that run in the background.
Examples
Constraints
capacityis a whole number >= 1.refillPerSecis a number > 0.nis a whole number >= 1. Refuse bad values with a clear error.- Time must come only from the
nowfunction, so a test can move the clock by hand. tryTakemust run in constant time and must not use memory that grows with the number of calls.- If
nowever returns a smaller time than before (a clock change), the bucket must not gain or lose tokens because of it.
Your answer must contain
- The code
- What state the class keeps and how a refill is calculated (without a timer)
- How a refused call, a call bigger than the capacity, and a clock that goes back are handled
- How you would test it, using the injected clock
Target A strong answer covers the lazy refill formula, the capacity cap, all-or-nothing takes, a clock that goes back, and tests with an injected clock.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Think about a bucket that gains tokens as time passes. When does it need to know the current count?
Hint 2 the approach
No timer is needed. Store the token count and the time of the last visit. At each call, add tokens for the time that passed, up to the capacity.
Hint 3 the key step
Take n tokens only if the bucket holds at least n. A refused call takes nothing. Get the time from an injected clock, so tests can move it.
Walkthrough
Full walkthrough brute force to best
Naive version
Run a timer that adds a token every interval. It keeps the process alive, it drifts, it leaks if the object is dropped, and it is hard to test because the test must wait for real time.
Better version
Store the count and the time of the last call, and refill by the elapsed time at each call, but round the refill down to whole tokens. A slow rate such as 0.5 per second then never gains a token, because each call rounds the gain to zero.
Best method
Keep two numbers: the tokens at the last visit and the time of that visit. At each call, refill lazily: tokens become the smaller of the capacity and tokens plus elapsed seconds times refillPerSec, then store the new time. No timer is needed, because nobody can see the bucket between calls. Keep fractional tokens so slow rates work. Then take n tokens only if the bucket holds at least n. A refused call takes nothing. If the clock goes back, cut the elapsed time to 0 and do not move the last time back, so the bucket neither gains nor loses tokens.
Worked example
Run the first example: capacity 3, refill 1 per second. The bucket starts with 3 tokens, so the first three calls at time 0 succeed and the fourth fails. At 1000 ms one second has passed, so 1 token is added and the next call succeeds. The call after that finds 0 tokens and fails.
Reference code
class TokenBucket {
// capacity: most tokens held. refillPerSec: tokens added each second. now: returns the time in ms.
constructor(capacity, refillPerSec, now = Date.now) {
if (!Number.isInteger(capacity) || capacity < 1) throw new RangeError('capacity must be a whole number >= 1');
if (!Number.isFinite(refillPerSec) || refillPerSec <= 0) throw new RangeError('refillPerSec must be a number > 0');
this.capacity = capacity;
this.refillPerSec = refillPerSec;
this.now = now;
this.tokens = capacity; // starts full
this.last = now();
}
refill() {
const t = this.now();
const elapsedMs = Math.max(0, t - this.last); // a clock that goes backwards adds nothing
this.tokens = Math.min(this.capacity, this.tokens + (elapsedMs / 1000) * this.refillPerSec);
this.last = Math.max(this.last, t);
}
// Takes n tokens if there are enough and returns true. Otherwise takes nothing and returns false.
tryTake(n = 1) {
if (!Number.isInteger(n) || n < 1) throw new RangeError('n must be a whole number >= 1');
this.refill();
if (n > this.tokens) return false; // also false when n > capacity: it can never succeed
this.tokens -= n;
return true;
}
}Time and memory
O(1) time and O(1) memory per call, because the state is two numbers.
Common mistakes
- Refilling with a repeating timer. It drifts, keeps the process alive and is hard to test.
- Rounding the refill down on every call, so slow rates never add a token.
- Forgetting the capacity cap. A long idle time then stores a huge burst.
- Taking some tokens and then returning false. A refused call must take nothing.