Use Knotkit from source and install effect@4.1.7. Call rateLimitedHandler(handle) once at startup. Pass the returned handler an authenticated client ID for each request.
The admission check takes one unit when the Effect runs. A rejection enters the typed error channel. At the HTTP boundary, Effect.matchEffect calls your handler for accepted requests and turns quota denials into HTTP 429. Round Knotkit’s millisecond delay up to whole seconds for Retry-After. Errors from your handler still reach its caller.
The table is bounded and lives in one process. When all slots are busy, a new client receives 503. A quota shared across service replicas needs shared state. See the rate-limit module for other meter choices.
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.
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, type
interfaceKeyedRateLimitTable<inK>
A bounded table of rate-limit meters, one per client key.
The table owns three things a caller would otherwise write by hand. It clamps
its clock once and builds every meter with that one reading, so a key it
forgot and rebuilt sees the time the one it replaced would have seen. It
tracks the instant each key's meter becomes fresh, and forgets a key only at
that instant, so forgetting never changes a later decision: a client that
comes back after being dropped gets exactly the answer the meter the table
dropped would have given. And when a new key arrives with no room and nothing
forgettable, it applies the caller's table-full choice instead of guessing.
Any object meeting
RateMeter
works as the meter, so two limits per
client — requests per minute plus tokens per minute — are one meter that
peeks both and takes both only when both allow. The table reads a meter's
freshness report and trusts it: it cannot verify the report without running
the caller's algorithm again. A custom meter that reports fresh too early
makes the table forget a key that was still in debt, which forgives its
clients; the documentation of such a meter owes that sentence.
take and peek of a held key run in O(1) expected time plus the meter's
own. A take of a new key on a full table walks the held keys whose queued
fresh instant has passed, O(log n) each, where n is the number of keys held.
A bounded table of rate-limit meters, one per client key.
The table owns three things a caller would otherwise write by hand. It clamps
its clock once and builds every meter with that one reading, so a key it
forgot and rebuilt sees the time the one it replaced would have seen. It
tracks the instant each key's meter becomes fresh, and forgets a key only at
that instant, so forgetting never changes a later decision: a client that
comes back after being dropped gets exactly the answer the meter the table
dropped would have given. And when a new key arrives with no room and nothing
forgettable, it applies the caller's table-full choice instead of guessing.
Any object meeting
RateMeter
works as the meter, so two limits per
client — requests per minute plus tokens per minute — are one meter that
peeks both and takes both only when both allow. The table reads a meter's
freshness report and trusts it: it cannot verify the report without running
the caller's algorithm again. A custom meter that reports fresh too early
makes the table forget a key that was still in debt, which forgives its
clients; the documentation of such a meter owes that sentence.
take and peek of a held key run in O(1) expected time plus the meter's
own. A take of a new key on a full table walks the held keys whose queued
fresh instant has passed, O(log n) each, where n is the number of keys held.
Creates an Effect lazily, delaying construction until it is needed.
When to use
Use when you need to defer the evaluation of an effect until it is required.
Details
suspend takes a thunk that represents an effect and delays creating it
until the suspended effect is evaluated. This is useful for optimizing
expensive computations, managing circular dependencies such as recursive
functions, and helping TypeScript unify return types when branches construct
different effects. Any side effects or scoped captures inside the thunk are
re-executed on each invocation.
Gotchas
If the thunk throws, the thrown value is treated as a defect, not as a typed
failure. Use Effect.try when a throw should become a typed failure.
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.
functionrateLimitedHandler<E, R>(handle: (clientId:string) =>Effect.Effect<Response, E, R>, clock?: () =>number): (clientId:string) =>Effect.Effect<Response, E, R>
rateLimitedHandler<
function (typeparameter) EinrateLimitedHandler<E, R>(handle: (clientId:string) =>Effect.Effect<Response, E, R>, clock?: () =>number): (clientId:string) =>Effect.Effect<Response, E, R>
E,
function (typeparameter) RinrateLimitedHandler<E, R>(handle: (clientId:string) =>Effect.Effect<Response, E, R>, clock?: () =>number): (clientId:string) =>Effect.Effect<Response, E, R>
R>(
handle: (clientId:string) => Effect.Effect<Response, E, R>
handle: (
clientId: string
clientId:string) =>
import Effect
Effect.
interfaceEffect<outA, outE=never, outR=never>
The Effect interface defines a value that lazily describes a workflow or
job. The workflow requires some context R, and may fail with an error of
type E, or succeed with a value of type A.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
Effect values model resourceful interaction with the outside world,
including synchronous, asynchronous, concurrent, and parallel interaction.
They use a fiber-based concurrency model, with built-in support for
scheduling, fine-grained interruption, structured concurrency, and high
scalability.
To run an Effect value, you need a Runtime, which is a type that is
capable of executing Effect values.
@stability ― stable
@category ― models
@since ― 2.0.0
Effect<
interfaceResponse
The Response interface of the Fetch API represents the response to a request.
function (typeparameter) EinrateLimitedHandler<E, R>(handle: (clientId:string) =>Effect.Effect<Response, E, R>, clock?: () =>number): (clientId:string) =>Effect.Effect<Response, E, R>
E,
function (typeparameter) RinrateLimitedHandler<E, R>(handle: (clientId:string) =>Effect.Effect<Response, E, R>, clock?: () =>number): (clientId:string) =>Effect.Effect<Response, E, R>
R>,
clock: () => number
clock: () =>number= () =>
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.floor(x: number): number
Returns the greatest integer less than or equal to its numeric argument.
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.clock: Clock
The time source every meter reads through. The table clamps it once, for all of them.
clock,
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 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.
The most weight one instant can admit from a fresh state. A positive safe
integer.
capacity:
constrequestLimit:3
requestLimit,
RateLimiterOptions.windowDuration: number
The width of the kind's trailing window, in the milliseconds of
clock
. A positive safe integer.
windowDuration:
constwindowMilliseconds:5000
windowMilliseconds,
RateLimiterOptions.clock: Clock
The time source the meter reads through, injected so a test replays every decision.
clock:
meterClock: Clock
meterClock }),
})
return (
clientId: string
clientId:string):
import Effect
Effect.
interfaceEffect<outA, outE=never, outR=never>
The Effect interface defines a value that lazily describes a workflow or
job. The workflow requires some context R, and may fail with an error of
type E, or succeed with a value of type A.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
Effect values model resourceful interaction with the outside world,
including synchronous, asynchronous, concurrent, and parallel interaction.
They use a fiber-based concurrency model, with built-in support for
scheduling, fine-grained interruption, structured concurrency, and high
scalability.
To run an Effect value, you need a Runtime, which is a type that is
capable of executing Effect values.
@stability ― stable
@category ― models
@since ― 2.0.0
Effect<
interfaceResponse
The Response interface of the Fetch API represents the response to a request.
function (typeparameter) EinrateLimitedHandler<E, R>(handle: (clientId:string) =>Effect.Effect<Response, E, R>, clock?: () =>number): (clientId:string) =>Effect.Effect<Response, E, R>
E,
function (typeparameter) RinrateLimitedHandler<E, R>(handle: (clientId:string) =>Effect.Effect<Response, E, R>, clock?: () =>number): (clientId:string) =>Effect.Effect<Response, E, R>
Handles both success and failure by running effectful handlers.
When to use
Use when you need to handle an Effect's failure or success with handlers
that return effects.
Details
Use matchEffect when either branch needs to return an Effect, such as
performing logging, recovery, notification, or other effectful work. The
returned effect succeeds or fails according to the handler that is run.
Gotchas
If the cause contains a defect, the handler is skipped and every typed error
is converted to a defect, preserving reason order and interrupts. An
interruption alongside a typed error does not prevent recovery.
Example (Matching success and failure with effectful handlers)
The json() static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json.
The json() static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json.