# 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

## Use

```ts
import { fixedWindowRateLimiter } from 'knotkit/rate-limit'

const meter = fixedWindowRateLimiter({
  capacity: 2,
  windowDuration: 1_000,
  clock: () => 582,
})

meter.take(1) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'denied', retryAfter: 418 }
```

```ts
import { keyedRateLimitTable, tokenBucketRateLimiter } from 'knotkit/rate-limit'

const limits = keyedRateLimitTable<string>({
  maxKeyCount: 100_000,
  whenFull: 'refuse',
  clock: () => Date.now(),
  meter: (clock) => tokenBucketRateLimiter({ capacity: 20, windowDuration: 1_000, refillAmount: 10, clock }),
})

limits.take('client-7', 1) // { outcome: 'allowed', untracked: false }
```

## What it solves

* 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

## Choose a layout

| Factory                                                        | Choose when                                                                                                                                                                                                                                                    | Cost                                                                                                |
| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `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 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                                   |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/rate-limit/README.md#performance)

## Try it

Capacity88Reset

* 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`](https://github.com/jkomyno/knotkit/blob/main/packages/rate-limit/demo.ts) against `knotkit/rate-limit` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                                                        | Returns                  | Does                                                                                                                                         |
| ------------------------------------------------------------------------------------------------------------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| [`fixedWindowRateLimiter`](/reference/knotkit/rate-limit/functions/fixedwindowratelimiter/)                   | `RateMeter`              | Anchors every key to one clock grid and admits until the current window's capacity is spent.                                                 |
| [`slidingWindowLogRateLimiter`](/reference/knotkit/rate-limit/functions/slidingwindowlogratelimiter/)         | `RateMeter`              | Keeps the instant and weight of every request still inside the trailing window, so its decisions and retry times are exact.                  |
| [`slidingWindowCounterRateLimiter`](/reference/knotkit/rate-limit/functions/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`](/reference/knotkit/rate-limit/functions/tokenbucketratelimiter/)                   | `RateMeter`              | Refills continuously at refillAmount per windowDuration, carrying the bucket as one exact arrival time rather than a fractional token count. |
| [`keyedRateLimitTable`](/reference/knotkit/rate-limit/functions/keyedratelimittable/)                         | `KeyedRateLimitTable<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

| Member    | Cost |
| --------- | ---- |
| `take`    | O(1) |
| `peek`    | O(1) |
| `freshAt` | O(1) |

`slidingWindowLogRateLimiter` 3 members

| Member    | Cost                                                 |
| --------- | ---------------------------------------------------- |
| `take`    | O(k) amortised, k entries pruned plus the retry scan |
| `peek`    | O(k) amortised                                       |
| `freshAt` | O(1)                                                 |

`slidingWindowCounterRateLimiter` 3 members

| Member    | Cost |
| --------- | ---- |
| `take`    | O(1) |
| `peek`    | O(1) |
| `freshAt` | O(1) |

`tokenBucketRateLimiter` 3 members

| Member    | Cost |
| --------- | ---- |
| `take`    | O(1) |
| `peek`    | O(1) |
| `freshAt` | O(1) |

`keyedRateLimitTable` 3 members

| Member | Cost              |
| ------ | ----------------- |
| `take` | O(log n) expected |
| `peek` | O(log n) expected |
| `size` | O(1)              |

## What you pass in

| Input                                                                                                 | Type               | Get one from                                 |
| ----------------------------------------------------------------------------------------------------- | ------------------ | -------------------------------------------- |
| time source every meter reads; nothing in the module reads the time on its own                        | `Clock`            | [`knotkit/cache`](/modules/cache/)           |
| the meter a keyed table builds for each key, which is how a caller supplies an algorithm of their own | `RateMeterFactory` | [`knotkit/rate-limit`](/modules/rate-limit/) |

## Errors

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`

## When not to use it

| If you need to…                                                                   | Use instead                                                                                     |
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| 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                     |

## Performance

Measured by the suite in [`packages/rate-limit/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/rate-limit/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/rate-limitCopy prompt

```
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/
```

## See also

* [API reference](/reference/knotkit/rate-limit/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/rate-limit/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/rate-limit/knotkit.capability.json)suggest a change to the source record
