Skip to content

slidingWindowLogRateLimiter(options): RateMeter

Defined in: packages/rate-limit/src/sliding-window-log.ts:58

Create a RateMeter that keeps the exact instant and weight of every request still inside its trailing window.

The window is (now - windowDuration, now]: a request taken exactly one window behind now has already left it, and one taken a millisecond inside it has not. That makes the promise exact: a trailing window holds exactly the weight taken into it, so a window admits capacity worth of traffic in total and refuses the next unit, never one unit early. It makes retryAfter exact too — the oldest request whose expiry frees the missing weight names the millisecond the same take fits — so a client that waits and comes back is denied only while other traffic still holds the window. A weight above capacity never fits, whatever the window holds.

Choose it when the boundary itself is the contract, such as a billing quota or a throttle an adversary probes, and the traffic admitted per window is small. It is the only kind whose trailing-window promise is exact, and the price is one buffered instant per unit of admitted weight: because every weight is a positive integer and the kept weights sum to capacity at most, at most capacity instants are held.

peek answers with the decision take would, and neither a denied nor a never-fits answer changes state, so a caller can ask before it spends.

take and peek run in O(k) amortised time, where k counts the entries a prune removes plus, on a denial, the entries the exact retry scan walks over; freshAt is O(1).

RateLimiterOptions

The capacity, the width of the trailing window, 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 = slidingWindowLogRateLimiter({ capacity: 2, windowDuration: 1_000, 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' }