Skip to content

knotkit/rate-limit

Limits each client's request weight by a fixed window, a sliding window, or a token bucket, returning the least whole millisecond a denial must wait

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
} from 'knotkit/rate-limit'
const
const meter: RateMeter
meter
=
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
: () => 582,
})
const meter: RateMeter
meter
.
RateMeter.take: (weight: number) => RateLimitDecision

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.

take
(1) // { outcome: 'allowed' }
const meter: RateMeter
meter
.
RateMeter.take: (weight: number) => RateLimitDecision

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.

take
(1) // { outcome: 'allowed' }
const meter: RateMeter
meter
.
RateMeter.take: (weight: number) => RateLimitDecision

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.

take
(1) // { outcome: 'denied', retryAfter: 418 }
rate-limit.ts
import {
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
,
function tokenBucketRateLimiter(options: TokenBucketOptions): RateMeter

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.

@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.

@example

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' }

tokenBucketRateLimiter
} from 'knotkit/rate-limit'
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
: 100_000,
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
: () =>
var Date: DateConstructor

Enables basic storage and retrieval of dates and times.

Date
.
DateConstructor.now(): number

Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).

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 tokenBucketRateLimiter(options: TokenBucketOptions): RateMeter

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.

@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.

@example

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' }

tokenBucketRateLimiter
({
RateLimiterOptions.capacity: number

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

capacity
: 20,
RateLimiterOptions.windowDuration: number

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

clock

. A positive safe integer.

windowDuration
: 1_000,
TokenBucketOptions.refillAmount: number

The weight the bucket regains over one

RateLimiterOptions.windowDuration

. A positive safe integer; a steady trickle of requests settles at one refillAmount per window.

refillAmount
: 10,
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-7', 1) // { outcome: 'allowed', untracked: false }
  • limit one client's request weight and tell it the least whole millisecond to wait before retrying
  • limit many clients without letting the per-client table grow with every client ever seen
  • choose a rate-limit algorithm by the most weight it admits in a trailing window rather than by its name
  • combine two limits for one client into one meter a keyed table accepts like a built-in kind
  • prove a limiter's worst case and its retry boundary by replaying the same arrival schedules
FactoryChoose whenCost
fixedWindowRateLimiter
kind fixed-window
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 capacityone 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 windowone 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 10two 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 windowone arrival time per key, held as two integers; O(1) per decision

Performance and benchmarks for this module

{"v":1,"box":[259.3628,140.4708,930.5703,496.6349],"x":{"s":"linear","lim":[0,20.64],"inv":false,"g":0,"t":"weight units","tk":[[0,"0"],[8,"8"],[16,"16"]]},"y":{"s":"linear","lim":[-0.65,3.65],"inv":false,"g":0,"tk":[[3,"fixed-window"],[2,"sliding-window-log"],[1,"sliding-window-counter"],[0,"token-bucket"]]},"ti":"Most weight in a window","a":[{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[16,3],"p":[779.68,194.31],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#1d5fa6","s":"xy","d":[8,2],"p":[519.52,277.14],"r":6.09},{"k":"annotation","c":"#1d5fa6"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[8,1],"p":[519.52,359.97],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[8,0],"p":[519.52,442.8],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#111111"}],"lg":[]} 0 8 16 weight units fixed-window sliding-window-log sliding-window-counter token-bucket 16 8 8 8 boundary-burst arrivals, capacity 8 Most weight in a window {"v":1,"box":[1000.7925,140.4708,1672,496.6349],"x":{"s":"linear","lim":[0,1548],"inv":false,"g":1,"t":"milliseconds","tk":[[0,"0"],[300,"300"],[600,"600"],[900,"900"],[1200,"1,200"]]},"y":{"s":"linear","lim":[-0.65,3.65],"inv":false,"g":1,"tk":[[3,""],[2,""],[1,""],[0,""]]},"ti":"Wait a denial reports","a":[{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[1000,3],"p":[1434.39,194.31],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#1d5fa6","s":"xy","d":[999,2],"p":[1433.96,277.14],"r":6.09},{"k":"annotation","c":"#1d5fa6"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[125,1],"p":[1054.99,359.97],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[124,0],"p":[1054.56,442.8],"r":6.09},{"k":"annotation","c":"#2b2b28"}],"lg":[]} 0 300 600 900 1,200 milliseconds 1000 ms 999 ms 125 ms 124 ms Wait a denial reports
{"v":1,"box":[259.3628,140.4708,680,528.2578],"x":{"s":"linear","lim":[0,20.64],"inv":false,"g":0,"t":"weight units","tk":[[0,"0"],[8,"8"],[16,"16"]]},"y":{"s":"linear","lim":[-0.65,3.65],"inv":false,"g":0,"tk":[[3,"fixed-window"],[2,"sliding-window-log"],[1,"sliding-window-counter"],[0,"token-bucket"]]},"ti":"Most weight in a window","a":[{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[16,3],"p":[585.44,199.09],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#1d5fa6","s":"xy","d":[8,2],"p":[422.4,289.27],"r":6.09},{"k":"annotation","c":"#1d5fa6"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[8,1],"p":[422.4,379.46],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[8,0],"p":[422.4,469.64],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#111111"}],"lg":[]} 0 8 16 weight units fixed-window sliding-window-log sliding-window-counter token-bucket 16 8 8 8 boundary-burst arrivals, capacity 8 Most weight in a window {"v":1,"box":[259.3628,697.6478,680,1085.4349],"x":{"s":"linear","lim":[0,1548],"inv":false,"g":1,"t":"milliseconds","tk":[[0,"0"],[300,"300"],[600,"600"],[900,"900"],[1200,"1,200"]]},"y":{"s":"linear","lim":[-0.65,3.65],"inv":false,"g":1,"tk":[[3,"fixed-window"],[2,"sliding-window-log"],[1,"sliding-window-counter"],[0,"token-bucket"]]},"ti":"Wait a denial reports","a":[{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[1000,3],"p":[531.09,756.27],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#1d5fa6","s":"xy","d":[999,2],"p":[530.82,846.45],"r":6.09},{"k":"annotation","c":"#1d5fa6"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[125,1],"p":[293.33,936.63],"r":6.09},{"k":"annotation","c":"#2b2b28"},{"k":"segments","c":"#8c8c84"},{"k":"scatter","c":"#5c5c57","s":"xy","d":[124,0],"p":[293.06,1026.82],"r":6.09},{"k":"annotation","c":"#2b2b28"}],"lg":[]} 0 300 600 900 1,200 milliseconds fixed-window sliding-window-log sliding-window-counter token-bucket 1000 ms 999 ms 125 ms 124 ms Wait a denial reports
  • 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.

ExportReturnsDoes
fixedWindowRateLimiterRateMeterAnchors every key to one clock grid and admits until the current window's capacity is spent.
slidingWindowLogRateLimiterRateMeterKeeps the instant and weight of every request still inside the trailing window, so its decisions and retry times are exact.
slidingWindowCounterRateLimiterRateMeterEstimates the trailing window from the current and previous anchored windows, weighting the previous one by how much of it has elapsed.
tokenBucketRateLimiterRateMeterRefills continuously at refillAmount per windowDuration, carrying the bucket as one exact arrival time rather than a fractional token count.
keyedRateLimitTableKeyedRateLimitTable<K>Holds one caller-built meter per key under a key bound, forgetting a key only once its meter is fresh.

Cost per member. Open a row for every operation.

fixedWindowRateLimiter 3 members
MemberCost
takeO(1)
peekO(1)
freshAtO(1)
slidingWindowLogRateLimiter 3 members
MemberCost
takeO(k) amortised, k entries pruned plus the retry scan
peekO(k) amortised
freshAtO(1)
slidingWindowCounterRateLimiter 3 members
MemberCost
takeO(1)
peekO(1)
freshAtO(1)
tokenBucketRateLimiter 3 members
MemberCost
takeO(1)
peekO(1)
freshAtO(1)
keyedRateLimitTable 3 members
MemberCost
takeO(log n) expected
peekO(log n) expected
sizeO(1)
InputTypeGet one from
time source every meter reads; nothing in the module reads the time on its ownClockknotkit/cache
the meter a keyed table builds for each key, which is how a caller supplies an algorithm of their ownRateMeterFactoryknotkit/rate-limit

Every error this module throws is RateLimitInvalidInputError, with a code from a closed, exported list. Branch on the code; the message is for people.

INVALID_CAPACITY INVALID_WINDOW_DURATION INVALID_REFILL_AMOUNT INVALID_WEIGHT INVALID_MAX_KEY_COUNT INVALID_WHEN_FULL INVALID_CLOCK_READING PARAMETERS_TOO_LARGE
If you need to…Use instead
RateLimit or Retry-After response headers, or middleware for one server frameworkthe server's own response layer, fed by the decision's retryAfter
a limit shared across processes or kept outside memorya store with its own atomic increment and expiry, such as Redis, behind a caller-supplied meter
delaying a request until it fitsa queue or a scheduler in front of the request handler
bounding how many requests are in flight at oncea concurrency semaphore in the server
a decision that survives the process, as meter state on diska caller-supplied meter over a durable store, which the keyed table accepts

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.

Prompt · knotkit/rate-limit
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/