Gateway · Rate limiting
Rate-limit contract and the in-process reference adapter — RateLimiter interface, fixed-window InMemoryLimiter, and what you provide for multi-node deployments.
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
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
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, returnallowed: falseand let the caller fail open or closed.- Distinct
keyvalues are independent. A denied tenant doesn't affect a peer's quota.
In-process reference adapter
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
interface InMemoryRateLimiterConfig {
readonly defaultWindowMs?: number // default 60_000
readonly defaultMaxRequests?: number // default 60
}Per-call overrides are passed to check():
// Tighter limit for an expensive route, same limiter instance.
await limiter.check(`tenant:${tenantId}:expensive-llm`, {
windowMs: 60_000,
maxRequests: 5,
})What it is
A fixed-window counter in process memory. It suits local dev, single-node deployments, and unit tests.
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
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:
await limiter.check(`tenant:${tenantId}:callClass:${callClass}`, {
maxRequests: callClass === "synthesize" ? 10 : 100,
})Public surface
RateLimitercontract and the fixed-window in-process adapter, from@pleach/gateway/rateLimit.
Where to go next
Gateway · BYOK credential routing
Per-tenant BYOK credential storage and routing — TenantCredentialStore contract, Postgres / Redis / external-secret-manager adapters, and CredentialRoutingMiddleware.
Gateway · Cost events
Per-call cost-event emission — CostEmitter contract, CostMiddleware factory, and four reference adapters (OTel, Postgres, Datadog, Honeycomb).