Skip to content

slidingWindowCounterRateLimiter(options): RateMeter

Defined in: packages/rate-limit/src/sliding-window-counter.ts:65

Create a RateMeter that estimates a trailing window from the two anchored windows it overlaps.

The state is the current window’s spend and the previous window’s. A request fits when previous × (windowDuration − elapsed) + (current + weight) × windowDuration is within capacity × windowDuration, which counts the previous window as if its weight had been spread evenly over it and only the part still inside the trailing window mattered. That assumption is the whole economy of the kind: two counters and one index per key, where the log needs one buffered instant per unit of admitted weight.

The promise is therefore approximate, and it is stated as its worst case. With the previous window’s weight spread evenly, every trailing window of that width admits exactly capacity. With it clustered instead, the trailing window ending elapsed milliseconds into the current one can hold up to capacity + previous × (elapsed / windowDuration), approaching 2 × capacity as that window’s end comes near: the estimate has by then forgotten weight that a window of that width still counts.

Choose it when a smoothed throttle is enough — an API key’s requests per minute, a crawler’s pages per hour — and the caller would rather pay two counters per key than an exact scan. Choose slidingWindowLogRateLimiter when the trailing window has to be exact, and fixedWindowRateLimiter when a boundary burst up to twice the capacity has to be admitted at the lowest cost anyway.

peek answers with the decision take would, and neither a denied nor a never-fits answer spends weight, 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.

RateLimiterOptions

The capacity, the width of the anchored windows, 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, 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 = slidingWindowCounterRateLimiter({ capacity: 2, windowDuration: 1_000, clock: time.clock })
meter.take(2) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'denied', retryAfter: 1_500 }
time.advance(1_500)
meter.take(1) // { outcome: 'allowed' }