$ cat docs/middleware/rate-limit.md
Rate limitingLimite de requisições
Fixed-window rate limiting per key, with in-memory storage for one process or a store you inject for distributed limits.Limite de requisições por chave em janela fixa, com storage em memória para um processo ou um store injetado para limites distribuídos.
What it doesO que faz
rateLimit(options: RateLimitOptions): MiddlewareHandler. Fixed window per key; windowMs and
limit are required (it throws TypeError when windowMs <= 0 or
limit < 0) and requires an explicit client key: trust: 'cloudflare',
trust: 'proxy' (with trustedHops) or keyGenerator; without one it throws at
creation. Over the limit it answers 429 { code: 'RATE_LIMITED', message: 'Too many requests' } without calling next().
rateLimit(options: RateLimitOptions): MiddlewareHandler. Janela fixa por chave; windowMs e
limit são obrigatórios (lança TypeError quando windowMs <= 0 ou
limit < 0) e exige uma chave de cliente explícita: trust: 'cloudflare',
trust: 'proxy' (com trustedHops) ou keyGenerator; sem ela lança na criação.
Acima do limite responde 429 { code: 'RATE_LIMITED', message: 'Too many requests' } sem chamar next().
Install and orderInstalar e ordenar
pnpm add @tupik/middleware
Call .use(rateLimit(...)) before the routes it limits, on the app or on one module. To count per API
key or tenant, provide keyGenerator. To count per user, return
(await ctx.getPrincipal())?.id: the middleware runs before access, and
getPrincipal runs the app's authenticate once per request, which access then reuses. To share counters across isolates on Workers, use
DurableObjectRateLimitStore (exact) or CloudflareRateLimitStore (the Rate Limiting binding,
per location); elsewhere implement RateLimitStore over Redis or similar.
Chame .use(rateLimit(...)) antes das rotas que ele limita, no app ou em um módulo. Para contar por API
key ou tenant, forneça keyGenerator. Para contar por usuário, devolva
(await ctx.getPrincipal())?.id: o middleware roda antes do access, e o
getPrincipal roda o authenticate do app uma vez por requisição, que o access depois reaproveita. Para compartilhar contadores entre isolates no Workers, use
DurableObjectRateLimitStore (exato) ou CloudflareRateLimitStore (o binding Rate Limiting,
por localidade); fora dele implemente RateLimitStore sobre Redis ou similar.
ExampleExemplo
import {
DurableObjectRateLimitStore,
MemoryStore,
rateLimit,
} from '@tupik/middleware';
// Choose where the client IP comes from (required): behind Cloudflare...
createModule().use(rateLimit({ windowMs: 60_000, limit: 100, trust: 'cloudflare', store: new MemoryStore() }));
// ...behind your own proxies (2 hops: load balancer + nginx)
createModule().use(rateLimit({ windowMs: 60_000, limit: 100, trust: 'proxy', trustedHops: 2 }));
// Distributed on Workers: exact counters in a Durable Object, sharded by key hash
export { RateLimitDurableObject } from '@tupik/middleware'; // bind it as RATE_LIMITER in wrangler
createModule().use(rateLimit({
windowMs: 60_000,
limit: 20,
keyGenerator: (ctx) => ctx.req.headers.get('x-api-key') ?? undefined, // undefined = no key
onMissingKey: 'reject', // 400 instead of letting it through uncounted
store: new DurableObjectRateLimitStore({ namespace: (env) => (env as Env).RATE_LIMITER, shards: 32 }),
}));
// Per signed-in user: authenticate runs once here and access reuses it
createModule().use(rateLimit({
windowMs: 60_000,
limit: 30,
keyGenerator: async (ctx) => (await ctx.getPrincipal())?.id, // anonymous: no key (onMissingKey); keep an IP limit too
}));
// 429 → { "code": "RATE_LIMITED", "message": "Too many requests" }
// ratelimit-limit: 100 · ratelimit-remaining: 0 · ratelimit-reset: 42 · retry-after: 42import {
DurableObjectRateLimitStore,
MemoryStore,
rateLimit,
} from '@tupik/middleware';
// Escolha de onde vem o IP do cliente (obrigatório): atrás da Cloudflare...
createModule().use(rateLimit({ windowMs: 60_000, limit: 100, trust: 'cloudflare', store: new MemoryStore() }));
// ...atrás dos seus proxies (2 saltos: balanceador + nginx)
createModule().use(rateLimit({ windowMs: 60_000, limit: 100, trust: 'proxy', trustedHops: 2 }));
// Distribuído no Workers: contadores exatos num Durable Object, com shards pelo hash da chave
export { RateLimitDurableObject } from '@tupik/middleware'; // ligue como RATE_LIMITER no wrangler
createModule().use(rateLimit({
windowMs: 60_000,
limit: 20,
keyGenerator: (ctx) => ctx.req.headers.get('x-api-key') ?? undefined, // undefined = sem chave
onMissingKey: 'reject', // 400 em vez de passar sem contar
store: new DurableObjectRateLimitStore({ namespace: (env) => (env as Env).RATE_LIMITER, shards: 32 }),
}));
// Por usuário logado: o authenticate roda uma vez aqui e o access reaproveita
createModule().use(rateLimit({
windowMs: 60_000,
limit: 30,
keyGenerator: async (ctx) => (await ctx.getPrincipal())?.id, // anônimo: sem chave (onMissingKey); mantenha também um limite por IP
}));
// 429 → { "code": "RATE_LIMITED", "message": "Too many requests" }
// ratelimit-limit: 100 · ratelimit-remaining: 0 · ratelimit-reset: 42 · retry-after: 42 APIAPI
| TypeTipo | ShapeFormato |
|---|---|
RateLimitOptions | { windowMs: number; limit: number; trust?: 'cloudflare' | 'proxy'; trustedHops?: number; keyGenerator?: (ctx) => string | undefined | Promise<string | undefined>; onMissingKey?: 'allow' | 'reject' | ((ctx) => Response | undefined | Promise<Response | undefined>); store?: RateLimitStore; headers?: boolean } |
RateLimitStore | { get(key, context?): Awaitable<RateLimitEntry | undefined>; increment(key, windowMs, context?: { env }): Awaitable<RateLimitEntry>; now?(): number } |
RateLimitEntry | { count: number; resetAt: number; limited?: boolean } (resetAt in epoch milliseconds; limited is set by stores that decide themselves)(resetAt em milissegundos epoch; limited vem de stores que decidem sozinhos) |
DurableObjectRateLimitStore | new DurableObjectRateLimitStore({ namespace, shards?, now? }) (talks to RateLimitDurableObject; one object per key or a fixed number of shards)(fala com o RateLimitDurableObject; um objeto por chave ou um número fixo de shards) |
CloudflareRateLimitStore | new CloudflareRateLimitStore({ binding, now? }) (limit and period live in the wrangler config; no ratelimit-remaining)(limite e período ficam no wrangler; sem ratelimit-remaining) |
MemoryStoreOptions | { now?: () => number; sweepIntervalMs?: number; maxEntries?: number } (default: unbounded; when set, evicts the least-recently-used key first)(padrão: ilimitado; quando definido, remove primeiro a chave menos usada recentemente) |
- Headers:
ratelimit-limit, ratelimit-remaining, ratelimit-reset (seconds) and, on 429, retry-after. headers: false disables them. resolveClientIp(headers, { trust, trustedHops? }): 'cloudflare' reads only cf-connecting-ip; 'proxy' reads x-forwarded-for from the right, trustedHops entries in. It never falls back to another header and returns undefined when the IP is unknown. - Requests without a key are never pooled into one shared bucket:
onMissingKey defaults to 'allow' (continue uncounted); 'reject' answers 400 CLIENT_KEY_MISSING; a callback may answer itself. MemoryStore: a Map with expiration, swept lazily on increment (no timers, safe on Workers). Options now, sweepIntervalMs (default 60 000) and maxEntries (default unbounded; a cap evicts the least-recently-used key first).
- Headers:
ratelimit-limit, ratelimit-remaining, ratelimit-reset (segundos) e, no 429, retry-after. headers: false os desativa. resolveClientIp(headers, { trust, trustedHops? }): 'cloudflare' lê só cf-connecting-ip; 'proxy' lê x-forwarded-for pela direita, trustedHops itens para dentro. Nunca cai em outro header e devolve undefined quando o IP é desconhecido. - Requisições sem chave nunca são agrupadas num balde comum:
onMissingKey é 'allow' por padrão (segue sem contar); 'reject' responde 400 CLIENT_KEY_MISSING; um callback pode responder por conta própria. MemoryStore: um Map com expiração, limpo de forma preguiçosa no increment (sem timers, seguro em Workers). Opções now, sweepIntervalMs (padrão 60 000) e maxEntries (padrão ilimitado; um limite remove primeiro a chave menos usada recentemente).
Errors and limitsErros e limites
- It never trusts IP headers by default: pick
trust to match your edge. With 'allow', a request that bypasses your edge (no trusted IP header) is not counted; use 'reject' when that path must be closed. MemoryStore counts within one process only; replicas and Workers isolates get independent windows. - The 429 response is produced by the middleware, so later
onSend hooks still run but engine error handling does not.
- Nunca confia em headers de IP por padrão: escolha
trust conforme a sua borda. Com 'allow', uma requisição que contorna a borda (sem header de IP confiável) não é contada; use 'reject' quando esse caminho precisar ficar fechado. MemoryStore conta só dentro de um processo; réplicas e isolates do Workers mantêm janelas independentes. - A resposta 429 é produzida pelo middleware, então hooks
onSend posteriores ainda rodam, mas o tratamento de erro do engine não.
When not to use itQuando não usar
Do not use it as authentication or as a hard quota on money-moving endpoints; a fixed window still allows a burst
at the boundary. For multiple processes without a shared store, add the store first or rate-limit at the edge.
Não use como autenticação nem como cota rígida em endpoints que movem dinheiro; uma janela fixa ainda permite um
burst na virada. Para múltiplos processos sem store compartilhado, adicione o store antes ou limite na borda.