# Rate-limit an Effect endpoint

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

## Try a burst

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.

## Run the TypeScript

Use [Knotkit from source](/getting-started/#install-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](https://effect.website/docs/v4/error-management/expected-errors). At the HTTP boundary, `Effect.matchEffect` calls your handler for accepted requests and turns quota denials into [HTTP 429](https://www.rfc-editor.org/rfc/rfc6585.html#section-4). Round Knotkit’s millisecond delay up to whole seconds for [Retry-After](https://www.rfc-editor.org/rfc/rfc9110.html#name-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](/modules/rate-limit/) for other meter choices.

```ts
import { Effect } from 'effect'
import { fixedWindowRateLimiter, keyedRateLimitTable, type KeyedRateLimitTable } from 'knotkit/rate-limit'

export const requestLimit = 3
export const windowMilliseconds = 5_000

export function admitRequest(limits: KeyedRateLimitTable<string>, clientId: string) {
  return Effect.suspend(() => {
    const decision = limits.take(clientId, 1)

    return decision.outcome === 'allowed' ? Effect.void : Effect.fail(decision)
  })
}

export function rateLimitedHandler<E, R>(
  handle: (clientId: string) => Effect.Effect<Response, E, R>,
  clock: () => number = () => Math.floor(performance.now()),
) {
  const limits = keyedRateLimitTable<string>({
    clock,
    maxKeyCount: 1024,
    whenFull: 'refuse',
    meter: (meterClock) =>
      fixedWindowRateLimiter({ capacity: requestLimit, windowDuration: windowMilliseconds, clock: meterClock }),
  })

  return (clientId: string): Effect.Effect<Response, E, R> =>
    Effect.matchEffect(admitRequest(limits, clientId), {
      onSuccess: () => handle(clientId),
      onFailure: (decision) => {
        if (decision.outcome !== 'denied') {
          return Effect.succeed(Response.json({ error: decision.outcome }, { status: 503 }))
        }

        const retryAfter = Math.ceil(decision.retryAfter / 1000)

        return Effect.succeed(
          Response.json(
            { error: 'too_many_requests' },
            { status: 429, headers: { 'Retry-After': String(retryAfter) } },
          ),
        )
      },
    })
}
```

**Modules:** [`knotkit/rate-limit`](/modules/rate-limit/) · [API reference](/reference/knotkit/rate-limit/)
