Skip to content

Rate Limiting

End-to-end rate limiting: L1 global-IP + L2 auth + L3 handler opt-in.

  • Handler rateLimit: { per, limit, windowSeconds }
  • Several buckets on one handler: rateLimit: [{ per: "user", ... }, { per: "tenant+handler", ... }]
  • How L1/L2 from buildServer stack with L3

Pass a list to enforce several budgets on one handler, for example a per-caller and a per-tenant cap:

r.writeHandler({
// ...
rateLimit: [
{ per: "user", limit: 2, windowSeconds: 3600 },
{ per: "tenant+handler", limit: 3, windowSeconds: 3600 },
],
});

Each bucket applies on its own. The check is all-or-nothing: if any bucket is exhausted the call answers 429 rate_limited for that bucket (the one with the longest wait when several are exhausted) and no bucket is charged. Each per may appear once; an empty list fails at boot. An anonymous handler needs every bucket to be ip-keyed, and { disabled: true, reason } stays a single declaration.

A bulk handler books one token per item instead of one per request. Declare rateLimitCost next to rateLimit:

r.writeHandler({
// ...
rateLimit: { per: "tenant+handler", limit: 20, windowSeconds: 600 },
rateLimitCost: (payload) => payload.files.length,
});

The cost is computed from the validated payload and booked on every declared bucket, so a schema-invalid payload costs nothing, while a payload rejected afterwards by a validation hook or field roles still consumes its cost. Results below 1 count as 1. Because it books after the parse, boot rejects rateLimitCost on anonymous or ip-limited handlers.

A public write handler that mails an address typed by the caller is also limited per address, so rotating IPs does not help against mail flooding. Declare it next to rateLimit:

r.writeHandler({
// ...
access: { roles: ["anonymous"] },
rateLimit: { per: "ip+handler", limit: 5, windowSeconds: 600 },
additionalRateLimits: [{ per: { payloadField: "email" }, limit: 3, windowSeconds: 86400 }],
});

additionalRateLimits only complements rateLimit: an anonymous handler still needs a real, ip-keyed rateLimit (boot fails otherwise), and payloadField must be a top-level string field of the handler’s Zod object schema. The value is trimmed, lowercased and HMAC-hashed into the bucket key, so Redis never holds the address in plaintext. The check runs after schema validation and before the handler, identically for matching and non-matching values, and is skipped for system callers. Exceeding it answers 429 rate_limited.

Hand-written extraRoutes take the same rateLimit as r.httpRoute. buildServer enforces it through the shared Redis store before the body limit, verify() and the handler, so the limit holds across replicas and restarts. "ip+handler" keeps one bucket per METHOD path, "ip" shares one bucket with every route that declares it.

const badgeRoute: ExtraRouteDefinition = {
method: "GET",
path: "/badge.svg",
entry: "anonymous",
rateLimit: { per: "ip+handler", limit: 120, windowSeconds: 60 },
handler,
};

During an HTTP request every handler gets ctx.visitorKey, a keyed hash of the UTC day, the client IP and the User-Agent. The same browser gets the same key in every handler for one day, so a public page can count a visit once per visitor and day without storing the IP. It is absent in jobs and event consumers and when the client IP is unknown; skip the dedup then instead of merging callers. Keep it in short-lived records, never in events.

r.queryHandler({
name: "visitor-key",
schema: z.object({}),
handler: async (_event, ctx) => ({ visitorKey: ctx.visitorKey ?? null }),
access: { roles: ["Admin", "User"] },
});

Feature entry point: src/feature.ts.

Needs the Postgres from the repo root’s docker-compose.yml (docker compose up -d); TEST_DATABASE_URL defaults to postgresql://kumiko:kumiko@localhost:15432/kumiko_test.

Terminal window
cd samples/recipes/rate-limiting
bun test

The feature entry point — embedded straight from the source file, so the code here is exactly what runs. Multi-file samples keep their remaining files next to it on GitHub (link below):

// Rate-Limiting Showcase — minimal feature
//
// Declares one query handler with an L3 rateLimit option so the
// dispatcher gates calls before the handler body runs. The integration
// test pairs this with L1+L2 middleware wired via buildServer's
// `rateLimit` option to prove all three layers stack.
import { defineFeature, type FeatureDefinition } from "@cosmicdrift/kumiko-framework/engine";
import { z } from "zod";
export function createRateLimitShowcaseFeature(): FeatureDefinition {
return defineFeature("rl-showcase", (r) => {
// Per-user budget. Real apps tune `limit` to actual handler cost — a
// search call against a sharded index might warrant 5/min, a full
// export 1/min. The bucket is `user:<userId>` (see rate-limit/bucket.ts).
r.queryHandler({
name: "expensive-search",
schema: z.object({ q: z.string().min(1) }),
handler: async ({ payload }) => ({ q: payload.q, hits: 0 }),
access: { roles: ["Admin", "User"] },
rateLimit: { per: "user", limit: 3, windowSeconds: 60 },
});
// Combined budget: each caller gets 2 submits per hour and the tenant 3 per hour in
// total. Both buckets are checked together; a request one bucket rejects charges neither.
r.writeHandler({
name: "submit-report",
schema: z.object({}),
handler: async () => ({ isSuccess: true as const, data: {} }),
access: { roles: ["Admin", "User"] },
rateLimit: [
{ per: "user", limit: 2, windowSeconds: 3600 },
{ per: "tenant+handler", limit: 3, windowSeconds: 3600 },
],
});
// Bulk upload: a request books one token per item instead of one per request. The cost
// comes from the validated payload, so a schema-invalid request costs nothing; a request
// that would exceed the remaining budget is rejected and consumes nothing.
r.writeHandler({
name: "bulk-upload",
schema: z.object({ files: z.array(z.string()).min(1).max(20) }),
handler: async () => ({ isSuccess: true as const, data: {} }),
access: { roles: ["Admin", "User"] },
rateLimit: { per: "tenant+handler", limit: 20, windowSeconds: 600 },
rateLimitCost: (payload) => payload.files.length,
});
// A daily pseudonym of the HTTP caller for anonymous dedup and per-visitor limits, absent outside HTTP.
r.queryHandler({
name: "visitor-key",
schema: z.object({}),
handler: async (_event, ctx) => ({ visitorKey: ctx.visitorKey ?? null }),
access: { roles: ["Admin", "User"] },
});
});
}

📄 On GitHub: samples/recipes/rate-limiting/src/feature.ts