Rate limiter – token bucket
Implement the token bucket algorithm – the same one API gateways and reverse proxies use. Lazy refilling, fractional tokens and an injected clock.
A public API lets a client make short bursts but limits the average request rate. The most popular algorithm is the token bucket: the bucket holds capacity tokens, refills at a constant rate refillPerSecond, and every request takes tokens. When there are not enough tokens, the request is rejected (HTTP 429).
The clock is injected (a function returning the current time in milliseconds), so tests control time and never wait.
Task
A class TokenBucket(capacity, refillPerSecond, clock):
- the bucket starts full,
tryConsume(tokens = 1)– first refills for the time elapsed since the previous refill (elapsedMs · refillPerSecond / 1000, never abovecapacity), then: if there are at leasttokenstokens – subtracts them and returnstrue, otherwise returnsfalseand subtracts nothing,available()– refills and returns the current (possibly fractional) number of tokens,- a request larger than
capacitynever succeeds, - if the clock goes back in time, nothing is added and the reference point stays at the latest time seen so far (so the same period is not counted twice when the clock catches up).
| Language | API |
|---|---|
| JS/TS | new TokenBucket(capacity, refillPerSecond, clock = () => Date.now()), tryConsume(tokens = 1), available() |
| Python | TokenBucket(capacity, refill_per_second, clock=<monotonic clock in ms>), try_consume(tokens=1), available() |
| C# | new TokenBucket(int capacity, double refillPerSecond, Func<long> clockMs), TryConsume(int tokens = 1), Available() |
| Java | new TokenBucket(int capacity, double refillPerSecond, LongSupplier clockMs), tryConsume(), tryConsume(int tokens), available() |
| Go | NewTokenBucket(capacity int, refillPerSecond float64, clockMs func() int64), TryConsume(tokens int) bool, Available() float64 |
Example
capacity = 2, refillPerSecond = 2 (one token every 500 ms):
| Time [ms] | Call | Result | Tokens after |
|---|---|---|---|
| 0 | tryConsume() | true | 1 |
| 0 | tryConsume() | true | 0 |
| 0 | tryConsume() | false | 0 |
| 250 | available() | 0.5 | 0.5 |
| 500 | tryConsume() | true | 0 |
| 10,000 | available() | 2 | 2 (never above the capacity) |
Constraints
1 ≤ capacity ≤ 10⁶,0 < refillPerSecond ≤ 10⁶,1 ≤ tokens.- Up to 100,000 calls per test.
Expected complexity
Every operation O(1) time and memory – no queues of timestamps.