Skip to content

tokenBucketRateLimiter(options): RateMeter

Defined in: packages/rate-limit/src/token-bucket.ts:107

Create a RateMeter that spends weight from a bucket and refills it at refillAmount per windowDuration, continuously rather than at a boundary.

The bucket holds capacity weight when full and regains refillAmount over any windowDuration of elapsed clock, so a steady stream settles at refillAmount per window while an idle client still finds capacity waiting. A client that idles and then bursts is throttled from its second unit on, where a fixed-window meter forgives the burst at each boundary and a sliding-window-log meter gives the weight back only as each request of the first burst ages out of the trailing window.

The promise about a trailing window is the one this kind can keep: it admits at most capacity plus what refills during that window, and never more than capacity at one instant, however long the client was idle before it. Under a monotonic clock its decisions and its retryAfter times are exactly the ones a two-number bucket makes, which holds a fractional token count and refills it continuously; this meter reaches them from a single arrival time, so it carries no fraction and cannot drift.

Choose it when the caller’s contract is a sustained rate rather than a calendar window: tokens per minute in an LLM gateway, requests per second to an upstream API, bytes per second per client. Choose slidingWindowLogRateLimiter when a trailing window has to admit exactly capacity weight, and fixedWindowRateLimiter when the reset has to land on a clock face every client can predict.

peek answers with the decision take would, and neither a denied nor a never-fits answer spends weight or moves the arrival time, so a caller can ask before it acts. take and peek read the injected clock, which the meter clamps at its highest reading, so a reading taken now is never below one this meter already saw.

take, peek, and freshAt run in O(1) time, and the meter holds O(1) state.

TokenBucketOptions

The capacity, the width of one refill window, the weight refilled over it, and the clock every reading comes from.

RateMeter

With code INVALID_CAPACITY when options.capacity is not a positive safe integer, INVALID_WINDOW_DURATION when options.windowDuration is not one, INVALID_REFILL_AMOUNT when options.refillAmount is not one, or PARAMETERS_TOO_LARGE when three times capacity x windowDuration would stop being exact.

With code INVALID_WEIGHT from take and peek when the weight is not a positive safe integer, and INVALID_CLOCK_READING from take, peek, and freshAt when the injected clock returns a number that is not finite.

const time = scriptedClock()
const meter = tokenBucketRateLimiter({
capacity: 2,
windowDuration: 1_000,
refillAmount: 1,
clock: time.clock,
})
meter.take(2) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'denied', retryAfter: 1_000 }
time.advance(1_000)
meter.take(1) // { outcome: 'allowed' }