# Gateway · Rate limiting (/docs/gateway/rate-limit)



The rate-limit seam sits between your shared quota store (Redis,
Upstash, DynamoDB, Postgres) and the per-tenant, per-user or per-route
throttling decision. The package ships a contract and one in-process
reference adapter. Production adapters aren't available yet.

## `RateLimiter` contract [#ratelimiter-contract]

```typescript
interface RateLimitCheckOptions {
  readonly windowMs?: number
  readonly maxRequests?: number
}

interface RateLimitDecision {
  readonly allowed: boolean
  readonly remaining: number
  readonly resetAt: number       // epoch ms; window reset
  readonly retryAfterMs?: number // populated only when !allowed
}

interface RateLimiter {
  check(key: string, opts?: RateLimitCheckOptions): Promise<RateLimitDecision>
}
```

Given a key and optional per-call overrides, `check()` returns whether
the call is allowed, the remaining quota, and the reset time. You can
render HTTP `429` responses with `Retry-After` and `X-RateLimit-*`
headers straight from the decision.

### Implementation requirements [#implementation-requirements]

* `check()` must be atomic: the count increment and the ceiling
  comparison happen as one operation.
* `check()` must not throw under normal load. If the backing store
  misbehaves, return `allowed: false` and let the caller fail open or
  closed.
* Distinct `key` values are independent. A denied tenant doesn't
  affect a peer's quota.

## In-process reference adapter [#in-process-reference-adapter]

```typescript
import { createInMemoryRateLimiter } from "@pleach/gateway/rateLimit"

const limiter = createInMemoryRateLimiter({
  defaultWindowMs: 60_000,
  defaultMaxRequests: 100,
})

const decision = await limiter.check(`tenant:${tenantId}`)
if (!decision.allowed) {
  return new Response("Too Many Requests", {
    status: 429,
    headers: {
      "Retry-After": String(Math.ceil((decision.retryAfterMs ?? 0) / 1000)),
      "X-RateLimit-Remaining": "0",
      "X-RateLimit-Reset": String(Math.ceil(decision.resetAt / 1000)),
    },
  })
}
```

### Configuration [#configuration]

```typescript
interface InMemoryRateLimiterConfig {
  readonly defaultWindowMs?: number      // default 60_000
  readonly defaultMaxRequests?: number   // default 60
}
```

Per-call overrides are passed to `check()`:

```typescript
// Tighter limit for an expensive route, same limiter instance.
await limiter.check(`tenant:${tenantId}:expensive-llm`, {
  windowMs: 60_000,
  maxRequests: 5,
})
```

### What it is [#what-it-is]

A fixed-window counter in process memory. It suits local dev,
single-node deployments, and unit tests.

### What it is NOT [#what-it-is-not]

**Not distributed-safe.** Counters live in one process. Several Node.js
instances behind a load balancer each keep their own count, so a
request can pass on one instance while another is at the ceiling. For
multi-node deployments, provide a `RateLimiter` over a shared store.

**Memory is reclaimed lazily.** Idle keys are dropped only when a later
`check()` finds their window expired, so many one-shot keys can
accumulate. With short-lived per-user keys, use an adapter with
explicit eviction.

## What you provide [#what-you-provide]

For a shared store such as Redis or DynamoDB, implement `RateLimiter`
over it. For a different window per call class inside one tenant,
encode the class in the key:

```typescript
await limiter.check(`tenant:${tenantId}:callClass:${callClass}`, {
  maxRequests: callClass === "synthesize" ? 10 : 100,
})
```

## Public surface [#public-surface]

* `RateLimiter` contract and the fixed-window in-process adapter, from
  `@pleach/gateway/rateLimit`.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Cost events" href="/docs/gateway/cost-events" description="Per-call cost emission, keyed by the same tenant." />

  <Card title="BYOK credential routing" href="/docs/gateway/byok" description="Per-tenant key resolution." />

  <Card title="`@pleach/gateway` overview" href="/docs/gateway" description="GatewayClient, cost events, family-strict cascade, transport seam." />
</Cards>
