Skip to content

Limit each client to a request rate

A keyed table builds one rate-limit meter per client, spends and refuses weight on that client alone, and forgets a client only once its meter would decide like a fresh one.

import {
function fixedWindowRateLimiter(options: RateLimiterOptions): RateMeter

Create a

RateMeter

that counts weight in fixed windows anchored at clock zero.

Windows sit on one grid, windowIndex = Math.floor(now / windowDuration), so every client's allowance resets at the same instant and the whole state is that index plus the weight spent in it. The promise is exactly what that grid can keep: a request is admitted whenever the window it lands in has room, so a client can be admitted up to 2 × capacity within one trailing window of that width — a full capacity on each side of a boundary — while every window of the grid itself admits capacity and no more.

Choose it when the reset has to be a clock face everyone can predict — capacity per minute, per day — when the boundary burst is acceptable or cannot happen because traffic is paced, and when the memory per key has to stay at one index and one counter. Choose slidingWindowLogRateLimiter instead when the trailing window itself is the contract, and slidingWindowCounterRateLimiter when a smoothed estimate of it is enough for less memory than the log needs.

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.

@param ― options - The capacity, the width of the anchored window, and the clock every reading comes from.

@throws ― {RateLimitInvalidInputError} 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.

@throws ― {RateLimitInvalidInputError} 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.

@example

const time = scriptedClock()
const meter = fixedWindowRateLimiter({ 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' }

fixedWindowRateLimiter
,
function keyedRateLimitTable<K>(options: KeyedRateLimitTableOptions): KeyedRateLimitTable<K>

Create a

KeyedRateLimitTable

over a caller-supplied meter factory.

Choose it when the server limits many clients and must survive a flood of new keys without growing with every client it has ever seen. Choose a single meter instead when there is one quota and no keys: a table for one key is a meter with extra steps.

@param ― options - The key bound, the meter factory, the clock, and the table-full choice.

@throws ― {RateLimitInvalidInputError} With code INVALID_MAX_KEY_COUNT when maxKeyCount is not a positive safe integer, or INVALID_WHEN_FULL when whenFull is neither refuse nor allow-untracked. A factory that rejects its own options throws its own package's error from here, because the table builds one meter at construction to answer for keys it does not hold.

keyedRateLimitTable
} from 'knotkit/rate-limit'
let
let now: number
now
= 0
const
const limits: KeyedRateLimitTable<string>
limits
=
keyedRateLimitTable<string>(options: KeyedRateLimitTableOptions): KeyedRateLimitTable<string>

Create a

KeyedRateLimitTable

over a caller-supplied meter factory.

Choose it when the server limits many clients and must survive a flood of new keys without growing with every client it has ever seen. Choose a single meter instead when there is one quota and no keys: a table for one key is a meter with extra steps.

@param ― options - The key bound, the meter factory, the clock, and the table-full choice.

@throws ― {RateLimitInvalidInputError} With code INVALID_MAX_KEY_COUNT when maxKeyCount is not a positive safe integer, or INVALID_WHEN_FULL when whenFull is neither refuse nor allow-untracked. A factory that rejects its own options throws its own package's error from here, because the table builds one meter at construction to answer for keys it does not hold.

keyedRateLimitTable
<string>({
KeyedRateLimitTableOptions.maxKeyCount: number

The most keys the table holds meters for. A positive safe integer. It bounds the table's memory; it is not a limit on traffic.

maxKeyCount
: 1,
KeyedRateLimitTableOptions.whenFull: "refuse" | "allow-untracked"

What a request from a key the table cannot hold gets: refuse, or allow-untracked. Required, because neither answer is safe for every server.

whenFull
: 'refuse',
KeyedRateLimitTableOptions.clock: Clock

The time source every meter reads through. The table clamps it once, for all of them.

clock
: () =>
let now: number
now
,
KeyedRateLimitTableOptions.meter: RateMeterFactory

Build one meter for one key. The table calls it with its own clamped reading, so every meter it holds shares one highest reading, and with a built-in factory the meter clamps it again to no effect.

meter
: (
clock: Clock
clock
) =>
function fixedWindowRateLimiter(options: RateLimiterOptions): RateMeter

Create a

RateMeter

that counts weight in fixed windows anchored at clock zero.

Windows sit on one grid, windowIndex = Math.floor(now / windowDuration), so every client's allowance resets at the same instant and the whole state is that index plus the weight spent in it. The promise is exactly what that grid can keep: a request is admitted whenever the window it lands in has room, so a client can be admitted up to 2 × capacity within one trailing window of that width — a full capacity on each side of a boundary — while every window of the grid itself admits capacity and no more.

Choose it when the reset has to be a clock face everyone can predict — capacity per minute, per day — when the boundary burst is acceptable or cannot happen because traffic is paced, and when the memory per key has to stay at one index and one counter. Choose slidingWindowLogRateLimiter instead when the trailing window itself is the contract, and slidingWindowCounterRateLimiter when a smoothed estimate of it is enough for less memory than the log needs.

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.

@param ― options - The capacity, the width of the anchored window, and the clock every reading comes from.

@throws ― {RateLimitInvalidInputError} 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.

@throws ― {RateLimitInvalidInputError} 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.

@example

const time = scriptedClock()
const meter = fixedWindowRateLimiter({ 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' }

fixedWindowRateLimiter
({
RateLimiterOptions.capacity: number

The most weight one instant can admit from a fresh state. A positive safe integer.

capacity
: 2,
RateLimiterOptions.windowDuration: number

The width of the kind's trailing window, in the milliseconds of

clock

. A positive safe integer.

windowDuration
: 1_000,
RateLimiterOptions.clock: Clock

The time source the meter reads through, injected so a test replays every decision.

clock
}),
})
const limits: KeyedRateLimitTable<string>
limits
.
KeyedRateLimitTable<string>.take: (key: string, weight: number) => KeyedTableDecision

Spend weight against the key's meter, creating that meter when the table has room or can forget a fresh key.

A weight that can never fit is answered before the table considers its own key bound, so a table too full to track a key still tells the caller the request is impossible rather than admitting it untracked.

@returns ― The meter's decision with untracked: false, a refused decision in refuse mode, or an allowed decision with untracked: true in allow-untracked mode.

@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when weight is not a positive safe integer. With code INVALID_CLOCK_READING when the injected clock returns a non-finite number. The table records nothing for the request after either.

take
('client-a', 1) // { outcome: 'allowed', untracked: false }
const limits: KeyedRateLimitTable<string>
limits
.
KeyedRateLimitTable<string>.take: (key: string, weight: number) => KeyedTableDecision

Spend weight against the key's meter, creating that meter when the table has room or can forget a fresh key.

A weight that can never fit is answered before the table considers its own key bound, so a table too full to track a key still tells the caller the request is impossible rather than admitting it untracked.

@returns ― The meter's decision with untracked: false, a refused decision in refuse mode, or an allowed decision with untracked: true in allow-untracked mode.

@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when weight is not a positive safe integer. With code INVALID_CLOCK_READING when the injected clock returns a non-finite number. The table records nothing for the request after either.

take
('client-a', 1) // { outcome: 'allowed', untracked: false }
const limits: KeyedRateLimitTable<string>
limits
.
KeyedRateLimitTable<string>.take: (key: string, weight: number) => KeyedTableDecision

Spend weight against the key's meter, creating that meter when the table has room or can forget a fresh key.

A weight that can never fit is answered before the table considers its own key bound, so a table too full to track a key still tells the caller the request is impossible rather than admitting it untracked.

@returns ― The meter's decision with untracked: false, a refused decision in refuse mode, or an allowed decision with untracked: true in allow-untracked mode.

@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when weight is not a positive safe integer. With code INVALID_CLOCK_READING when the injected clock returns a non-finite number. The table records nothing for the request after either.

take
('client-a', 1) // { outcome: 'denied', retryAfter: 1_000 }
const limits: KeyedRateLimitTable<string>
limits
.
KeyedRateLimitTable<string>.take: (key: string, weight: number) => KeyedTableDecision

Spend weight against the key's meter, creating that meter when the table has room or can forget a fresh key.

A weight that can never fit is answered before the table considers its own key bound, so a table too full to track a key still tells the caller the request is impossible rather than admitting it untracked.

@returns ― The meter's decision with untracked: false, a refused decision in refuse mode, or an allowed decision with untracked: true in allow-untracked mode.

@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when weight is not a positive safe integer. With code INVALID_CLOCK_READING when the injected clock returns a non-finite number. The table records nothing for the request after either.

take
('client-b', 1) // { outcome: 'refused' }, the only slot holds a client in debt
let now: number
now
= 1_000
const limits: KeyedRateLimitTable<string>
limits
.
KeyedRateLimitTable<string>.take: (key: string, weight: number) => KeyedTableDecision

Spend weight against the key's meter, creating that meter when the table has room or can forget a fresh key.

A weight that can never fit is answered before the table considers its own key bound, so a table too full to track a key still tells the caller the request is impossible rather than admitting it untracked.

@returns ― The meter's decision with untracked: false, a refused decision in refuse mode, or an allowed decision with untracked: true in allow-untracked mode.

@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when weight is not a positive safe integer. With code INVALID_CLOCK_READING when the injected clock returns a non-finite number. The table records nothing for the request after either.

take
('client-b', 1) // { outcome: 'allowed', untracked: false }, client-a's window ended, so the table forgot it
const limits: KeyedRateLimitTable<string>
limits
.
KeyedRateLimitTable<string>.take: (key: string, weight: number) => KeyedTableDecision

Spend weight against the key's meter, creating that meter when the table has room or can forget a fresh key.

A weight that can never fit is answered before the table considers its own key bound, so a table too full to track a key still tells the caller the request is impossible rather than admitting it untracked.

@returns ― The meter's decision with untracked: false, a refused decision in refuse mode, or an allowed decision with untracked: true in allow-untracked mode.

@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when weight is not a positive safe integer. With code INVALID_CLOCK_READING when the injected clock returns a non-finite number. The table records nothing for the request after either.

take
('client-b', 3) // { outcome: 'never-fits' }, no wait makes weight 3 fit a capacity of 2
const limits: KeyedRateLimitTable<string>
limits
.
KeyedRateLimitTable<string>.size: number

Number of keys held, each with its own meter. O(1).

size
// 1

The table holds at most maxKeyCount clients, and whenFull decides what a client it cannot hold is told. On the pinned per-client trace, the fixed-window meter this snippet uses keeps 64 clients in 52.6 KB where a Map of counters keeps 4,146 in 684.1 KB, at about 7 times the cost per decision: the measurements.

Modules: knotkit/rate-limit · API reference