Skip to content

Rate-limit an Effect endpoint

Give each API client a request budget and return HTTP 429 with a retry time.

3 requests per client in each 5-second window

Clock 0 s

TimeClientHTTPRetry-After
  1. Click Send 5 requests at time zero. The first three return 200. The next two return 429 with Retry-After: 5.
  2. Enter another client ID and click Send request. That client still has its own budget.
  3. Return to the first client, click Advance 5 seconds, and send again. The demo uses a manual clock so you can try a new window immediately.

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.

effect-rate-limit.ts
import {
import Effect
Effect
} from 'effect'
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
, type
interface KeyedRateLimitTable<in K>

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.

@example

const time = scriptedClock()
const table = keyedRateLimitTable<string>({
maxKeyCount: 1_000,
whenFull: 'refuse',
clock: time.clock,
meter: (clock) => fixedWindowRateLimiter({ capacity: 10, windowDuration: 1_000, clock }),
})
table.take('client-a', 1) // { outcome: 'allowed', untracked: false }

KeyedRateLimitTable
} from 'knotkit/rate-limit'
export const
const requestLimit: 3
requestLimit
= 3
export const
const windowMilliseconds: 5000
windowMilliseconds
= 5_000
export function
function admitRequest(limits: KeyedRateLimitTable<string>, clientId: string): Effect.Effect<void, DeniedDecision | NeverFitsDecision | RefusedDecision, never>
admitRequest
(
limits: KeyedRateLimitTable<string>
limits
:
interface KeyedRateLimitTable<in K>

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.

@example

const time = scriptedClock()
const table = keyedRateLimitTable<string>({
maxKeyCount: 1_000,
whenFull: 'refuse',
clock: time.clock,
meter: (clock) => fixedWindowRateLimiter({ capacity: 10, windowDuration: 1_000, clock }),
})
table.take('client-a', 1) // { outcome: 'allowed', untracked: false }

KeyedRateLimitTable
<string>,
clientId: string
clientId
: string) {
return
import Effect
Effect
.
const suspend: <void, DeniedDecision | NeverFitsDecision | RefusedDecision, never>(effect: LazyArg<Effect.Effect<void, DeniedDecision | NeverFitsDecision | RefusedDecision, never>>) => Effect.Effect<void, DeniedDecision | NeverFitsDecision | RefusedDecision, never>

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.

Example (Lazily evaluating side effects)

import { Effect } from "effect"
let i = 0
const bad = Effect.succeed(i++)
const good = Effect.suspend(() => Effect.succeed(i++))
Effect.runSync(bad) // => 0
Effect.runSync(bad) // => 0
Effect.runSync(good) // => 1
Effect.runSync(good) // => 2

Example (Suspending recursive Fibonacci evaluation)

import { Effect } from "effect"
const blowsUp = (n: number): Effect.Effect<number> =>
n < 2
? Effect.succeed(1)
: Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b)
// console.log(Effect.runSync(blowsUp(32)))
// crash: JavaScript heap out of memory
const allGood = (n: number): Effect.Effect<number> =>
n < 2
? Effect.succeed(1)
: Effect.zipWith(
Effect.suspend(() => allGood(n - 1)),
Effect.suspend(() => allGood(n - 2)),
(a, b) => a + b
)
Effect.runSync(allGood(16)) // => 1597

Example (Helping TypeScript infer recursive effect types)

import { Effect } from "effect"
// Without suspend, TypeScript may struggle with type inference.
// Inferred type:
// (a: number, b: number) =>
// Effect<never, Error, never> | Effect<number, never, never>
const withoutSuspend = (a: number, b: number) =>
b === 0
? Effect.fail(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// Using suspend to unify return types.
// Inferred type:
// (a: number, b: number) => Effect<number, Error, never>
const withSuspend = (a: number, b: number) =>
Effect.suspend(() =>
b === 0
? Effect.fail(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
)
Effect.runSync(withSuspend(6, 2)) // => 3

@stability ― stable

@category ― constructors

@since ― 2.0.0

suspend
(() => {
const
const decision: KeyedTableDecision
decision
=
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
(
clientId: string
clientId
, 1)
return
const decision: KeyedTableDecision
decision
.
outcome: "allowed" | "denied" | "never-fits" | "refused"
outcome
=== 'allowed' ?
import Effect
Effect
.
const void: Effect.Effect<void, never, never>
export void

Returns an effect that succeeds with void.

@stability ― stable

@category ― constructors

@since ― 2.0.0

void
:
import Effect
Effect
.
const fail: <DeniedDecision | NeverFitsDecision | RefusedDecision>(error: DeniedDecision | NeverFitsDecision | RefusedDecision) => Effect.Effect<never, DeniedDecision | NeverFitsDecision | RefusedDecision, never>

Creates an Effect that represents a recoverable error.

When to use

Use to explicitly signal a recoverable error in an Effect.

Details

The error keeps propagating unless it is handled. You can handle tagged errors with functions like

catchTag

or

catchTags

.

Example (Creating a failed effect)

import { Data, Effect } from "effect"
class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {}
// ┌─── Effect<never, OperationFailedError, never>
// ▼
const failure = Effect.fail(
new OperationFailedError()
)
Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError"

@see ― succeed to create an effect that represents a successful value.

@stability ― stable

@category ― constructors

@since ― 2.0.0

fail
(
const decision: DeniedDecision | NeverFitsDecision | RefusedDecision
decision
)
})
}
export function
function rateLimitedHandler<E, R>(handle: (clientId: string) => Effect.Effect<Response, E, R>, clock?: () => number): (clientId: string) => Effect.Effect<Response, E, R>
rateLimitedHandler
<
function (type parameter) E in rateLimitedHandler<E, R>(handle: (clientId: string) => Effect.Effect<Response, E, R>, clock?: () => number): (clientId: string) => Effect.Effect<Response, E, R>
E
,
function (type parameter) R in rateLimitedHandler<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
.
interface Effect<out A, out E = never, out R = 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
<
interface Response

The Response interface of the Fetch API represents the response to a request.

MDN Reference

Response
,
function (type parameter) E in rateLimitedHandler<E, R>(handle: (clientId: string) => Effect.Effect<Response, E, R>, clock?: () => number): (clientId: string) => Effect.Effect<Response, E, R>
E
,
function (type parameter) R in rateLimitedHandler<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.

@param ― x A numeric expression.

floor
(
var performance: Performance
performance
.
Performance.now(): DOMHighResTimeStamp

The performance.now() method returns a high resolution timestamp in milliseconds.

MDN Reference

now
()),
) {
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.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.

maxKeyCount
: 1024,
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.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
: (
meterClock: Clock
meterClock
) =>
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
:
const requestLimit: 3
requestLimit
,
RateLimiterOptions.windowDuration: number

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

clock

. A positive safe integer.

windowDuration
:
const windowMilliseconds: 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
.
interface Effect<out A, out E = never, out R = 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
<
interface Response

The Response interface of the Fetch API represents the response to a request.

MDN Reference

Response
,
function (type parameter) E in rateLimitedHandler<E, R>(handle: (clientId: string) => Effect.Effect<Response, E, R>, clock?: () => number): (clientId: string) => Effect.Effect<Response, E, R>
E
,
function (type parameter) R in rateLimitedHandler<E, R>(handle: (clientId: string) => Effect.Effect<Response, E, R>, clock?: () => number): (clientId: string) => Effect.Effect<Response, E, R>
R
> =>
import Effect
Effect
.
const matchEffect: <void, DeniedDecision | NeverFitsDecision | RefusedDecision, never, Response, never, never, Response, E, R>(self: Effect.Effect<void, DeniedDecision | NeverFitsDecision | RefusedDecision, never>, options: {
readonly onFailure: (e: DeniedDecision | NeverFitsDecision | RefusedDecision) => Effect.Effect<Response, never, never>;
readonly onSuccess: (a: void) => Effect.Effect<...>;
}) => Effect.Effect<...> (+1 overload)

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)

import { Data, Effect } from "effect"
class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {}
const success: Effect.Effect<number, ExampleError> = Effect.succeed(42)
const failure: Effect.Effect<number, ExampleError> = Effect.fail(
new ExampleError({ message: "Uh oh!" })
)
const program1 = Effect.matchEffect(success, {
onFailure: (error) =>
Effect.succeed(`failure: ${error.message}`),
onSuccess: (value) =>
Effect.succeed(`success: ${value}`)
})
Effect.runSync(program1) // => "success: 42"
const program2 = Effect.matchEffect(failure, {
onFailure: (error) =>
Effect.succeed(`failure: ${error.message}`),
onSuccess: (value) =>
Effect.succeed(`success: ${value}`)
})
Effect.runSync(program2) // => "failure: Uh oh!"

@see ― match if you don't need side effects and only want to handle the result or failure.

@stability ― stable

@category ― pattern matching

@since ― 2.0.0

matchEffect
(
function admitRequest(limits: KeyedRateLimitTable<string>, clientId: string): Effect.Effect<void, DeniedDecision | NeverFitsDecision | RefusedDecision, never>
admitRequest
(
const limits: KeyedRateLimitTable<string>
limits
,
clientId: string
clientId
), {
onSuccess: (a: void) => Effect.Effect<Response, E, R>
onSuccess
: () =>
handle: (clientId: string) => Effect.Effect<Response, E, R>
handle
(
clientId: string
clientId
),
onFailure: (e: DeniedDecision | NeverFitsDecision | RefusedDecision) => Effect.Effect<Response, never, never>
onFailure
: (
decision: DeniedDecision | NeverFitsDecision | RefusedDecision
decision
) => {
if (
decision: DeniedDecision | NeverFitsDecision | RefusedDecision
decision
.
outcome: "denied" | "never-fits" | "refused"
outcome
!== 'denied') {
return
import Effect
Effect
.
const succeed: <Response>(value: Response) => Effect.Effect<Response, never, never>

Creates an Effect that always succeeds with a given value.

When to use

Use when an effect should complete successfully with a specific value without any errors or external dependencies.

Example (Creating a successful effect)

import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)
Effect.runSync(success) // => 42

@see ― fail to create an effect that represents a failure.

@stability ― stable

@category ― constructors

@since ― 2.0.0

succeed
(
var Response: {
new (body?: BodyInit | null, init?: ResponseInit): Response;
prototype: Response;
error(): Response;
json(data: any, init?: ResponseInit): Response;
redirect(url: string | URL, status?: number): Response;
}

The Response interface of the Fetch API represents the response to a request.

MDN Reference

Response
.
function json(data: any, init?: ResponseInit): Response

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.

MDN Reference

json
({
error: "never-fits" | "refused"
error
:
decision: NeverFitsDecision | RefusedDecision
decision
.
outcome: "never-fits" | "refused"
outcome
}, {
ResponseInit.status?: number | undefined
status
: 503 }))
}
const
const retryAfter: number
retryAfter
=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.ceil(x: number): number

Returns the smallest integer greater than or equal to its numeric argument.

@param ― x A numeric expression.

ceil
(
decision: DeniedDecision
decision
.
DeniedDecision.retryAfter: number

The least whole number of milliseconds after which the same request succeeds with no other traffic, never below 1.

retryAfter
/ 1000)
return
import Effect
Effect
.
const succeed: <Response>(value: Response) => Effect.Effect<Response, never, never>

Creates an Effect that always succeeds with a given value.

When to use

Use when an effect should complete successfully with a specific value without any errors or external dependencies.

Example (Creating a successful effect)

import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)
Effect.runSync(success) // => 42

@see ― fail to create an effect that represents a failure.

@stability ― stable

@category ― constructors

@since ― 2.0.0

succeed
(
var Response: {
new (body?: BodyInit | null, init?: ResponseInit): Response;
prototype: Response;
error(): Response;
json(data: any, init?: ResponseInit): Response;
redirect(url: string | URL, status?: number): Response;
}

The Response interface of the Fetch API represents the response to a request.

MDN Reference

Response
.
function json(data: any, init?: ResponseInit): Response

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.

MDN Reference

json
(
{
error: string
error
: 'too_many_requests' },
{
ResponseInit.status?: number | undefined
status
: 429,
ResponseInit.headers?: HeadersInit | undefined
headers
: { 'Retry-After':
var String: StringConstructor
(value?: any) => string

Allows manipulation and formatting of text strings and determination and location of substrings within strings.

String
(
const retryAfter: number
retryAfter
) } },
),
)
},
})
}

Modules: knotkit/rate-limit · API reference