Polski

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.

medium · typescript · javascript · python · csharp · java · go · 20 XP

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 above capacity), then: if there are at least tokens tokens – subtracts them and returns true, otherwise returns false and subtracts nothing,
  • available() – refills and returns the current (possibly fractional) number of tokens,
  • a request larger than capacity never 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).
LanguageAPI
JS/TSnew TokenBucket(capacity, refillPerSecond, clock = () => Date.now()), tryConsume(tokens = 1), available()
PythonTokenBucket(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()
Javanew TokenBucket(int capacity, double refillPerSecond, LongSupplier clockMs), tryConsume(), tryConsume(int tokens), available()
GoNewTokenBucket(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]CallResultTokens after
0tryConsume()true1
0tryConsume()true0
0tryConsume()false0
250available()0.50.5
500tryConsume()true0
10,000available()22 (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.