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.
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.
Spend weight when the request is allowed, otherwise report why not.
@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when
weight is not a positive safe integer, or INVALID_CLOCK_READING when
the injected clock returns a non-finite number. The meter is unchanged
after either.
Spend weight when the request is allowed, otherwise report why not.
@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when
weight is not a positive safe integer, or INVALID_CLOCK_READING when
the injected clock returns a non-finite number. The meter is unchanged
after either.
Spend weight when the request is allowed, otherwise report why not.
@throws ― {RateLimitInvalidInputError} With code INVALID_WEIGHT when
weight is not a positive safe integer, or INVALID_CLOCK_READING when
the injected clock returns a non-finite number. The meter is unchanged
after either.
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.
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.
@param ― options - The capacity, the width of one refill window, the weight
refilled over it, 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,
INVALID_REFILL_AMOUNT when options.refillAmount 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.
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.
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.
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.
@param ― options - The capacity, the width of one refill window, the weight
refilled over it, 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,
INVALID_REFILL_AMOUNT when options.refillAmount 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.
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.
the reset has to land on a clock face every client can predict, and up to twice the capacity inside one trailing window is acceptable; the boundary-burst schedule reaches exactly 2 x capacity
one window index and one counter per key; O(1) per decision
slidingWindowLogRateLimiter
kind sliding-window-log
no trailing window of windowDuration may admit more than capacity, and capacity buffered instants per key fit the memory budget; the boundary-burst schedule reaches exactly capacity in one trailing window
one instant and one weight per admitted unit, at most capacity of them; O(k) amortised per decision
slidingWindowCounterRateLimiter
kind sliding-window-counter
two counters per key fit the memory budget, and capacity plus the previous window's decayed remainder is acceptable; the end-of-previous-window schedule reaches 19 against a capacity of 10
two counters and one window index per key; O(1) per decision
tokenBucketRateLimiter
kind token-bucket
the contract is a sustained rate rather than a calendar window, and capacity plus what refills during a trailing window is acceptable; the end-of-previous-window schedule spends its capacity at once and then admits exactly refillAmount in the next window
one arrival time per key, held as two integers; O(1) per decision
On the boundary-burst schedule with a capacity of 8, the four kinds admit 16 / 8 / 8 / 8 units.
The most any one trailing window holds is 16 (fixed-window, bound 16), 8 (sliding-window-log, bound 8), 8 (sliding-window-counter, bound up to 16), 8 (token-bucket, bound up to 16).
fixed-window denies it for 1000 ms, exactly: a take there succeeds and one millisecond earlier fails.
Hover or focus a chart for exact values. Each change reruns demo.ts against knotkit/rate-limit in your browser; the defaults reproduce the README figure.
Measured by the suite in packages/rate-limit/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.
Use knotkit/rate-limit for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/rate-limit'.
Exports:
- `fixedWindowRateLimiter` → `RateMeter`: Anchors every key to one clock grid and admits until the current window's capacity is spent.
- `slidingWindowLogRateLimiter` → `RateMeter`: Keeps the instant and weight of every request still inside the trailing window, so its decisions and retry times are exact.
- `slidingWindowCounterRateLimiter` → `RateMeter`: Estimates the trailing window from the current and previous anchored windows, weighting the previous one by how much of it has elapsed.
- `tokenBucketRateLimiter` → `RateMeter`: Refills continuously at refillAmount per windowDuration, carrying the bucket as one exact arrival time rather than a fractional token count.
- `keyedRateLimitTable` → `KeyedRateLimitTable<K>`: Holds one caller-built meter per key under a key bound, forgetting a key only once its meter is fresh.
Pick the layout by these rules:
- `fixedWindowRateLimiter` (kind 'fixed-window') when the reset has to land on a clock face every client can predict, and up to twice the capacity inside one trailing window is acceptable; the boundary-burst schedule reaches exactly 2 x capacity
- `slidingWindowLogRateLimiter` (kind 'sliding-window-log') when no trailing window of windowDuration may admit more than capacity, and capacity buffered instants per key fit the memory budget; the boundary-burst schedule reaches exactly capacity in one trailing window
- `slidingWindowCounterRateLimiter` (kind 'sliding-window-counter') when two counters per key fit the memory budget, and capacity plus the previous window's decayed remainder is acceptable; the end-of-previous-window schedule reaches 19 against a capacity of 10
- `tokenBucketRateLimiter` (kind 'token-bucket') when the contract is a sustained rate rather than a calendar window, and capacity plus what refills during a trailing window is acceptable; the end-of-previous-window schedule spends its capacity at once and then admits exactly refillAmount in the next window
Inputs and their sources:
- time source every meter reads; nothing in the module reads the time on its own: `Clock` from `knotkit/cache`
- the meter a keyed table builds for each key, which is how a caller supplies an algorithm of their own: `RateMeterFactory` from `knotkit/rate-limit`
Use something else when:
- RateLimit or Retry-After response headers, or middleware for one server framework → the server's own response layer, fed by the decision's retryAfter
- a limit shared across processes or kept outside memory → a store with its own atomic increment and expiry, such as Redis, behind a caller-supplied meter
- delaying a request until it fits → a queue or a scheduler in front of the request handler
- bounding how many requests are in flight at once → a concurrency semaphore in the server
- a decision that survives the process, as meter state on disk → a caller-supplied meter over a durable store, which the keyed table accepts
Errors are RateLimitInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/rate-limit.md
Types: node_modules/knotkit/rate-limit/ and https://knotkit.jkomyno.dev/reference/knotkit/rate-limit/