Skip to content

Set up a shared limiter

For: an operator who needs the limits of the price page to hold on every isolate.

What it does: the owned limiter keeps one count for each key and window in the table ta_limit. Every isolate and every process shares that count.

  1. On D1, pass limiter: createD1Limiter(env.DB) to createAuth.
examples/worker-d1/src/index.ts
import { createD1Adapter, createD1Limiter } from "@authtempo/adapter-d1";
import {
type Auth,
type AuthConfig,
createAuth,
type HooksConfig,
type MailPort,
} from "@authtempo/core";
import { workersLogsSink } from "@authtempo/observe/workers-logs";
/** The bindings and vars of wrangler.jsonc, and the secret of `wrangler secret put AUTH_SECRET`. */
export interface Env {
DB: D1Database;
BASE_URL: string;
AUTH_SECRET: string;
}
/**
* Your mail transport. Core calls `send` once per mail: a magic link, an
* email code, a reset link. Replace the body with a call to your mail
* provider. Until then a sign-in request answers 500, so a deploy with no
* mail fails at once and not in silence.
*/
export const mail: MailPort = {
async send() {
throw new Error("my-app: no mail transport; replace mail.send in src/index.ts");
},
};
/**
* The Worker. The test passes a mail port that keeps the mails, and hooks of its own.
* `more` adds config keys for one env, after the keys below. The measure entry
* (src/measure.ts) adds the password config and its own sink with it.
*/
export function createWorker(
mailPort: MailPort,
hooks?: HooksConfig,
more?: (env: Env) => Partial<AuthConfig>,
) {
// One auth instance per isolate. The bindings stay the same for the life of the isolate.
let auth: Auth | null = null;
const getAuth = (env: Env): Auth =>
(auth ??= createAuth({
baseURL: env.BASE_URL,
secret: env.AUTH_SECRET,
trustedOrigins: [env.BASE_URL],
storage: createD1Adapter(env.DB),
// The owned limiter counts in D1, so every isolate shares one count.
// The default limiter counts per isolate, and is for tests only.
limiter: createD1Limiter(env.DB),
mail: mailPort,
...(hooks ? { hooks } : {}),
// Each event of core goes to Workers Logs as one JSON object. wrangler.jsonc
// turns the logs on. With a sink, core writes no console line of its own.
// The sink scrubs the secret of the config from each field, as the last guard.
observe: { sink: workersLogsSink({ secrets: [env.AUTH_SECRET] }) },
...(more ? more(env) : {}),
}));
return {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
const a = getAuth(env);
const viaHandle = url.pathname.startsWith("/auth/");
try {
// The events flush after the answer. Bound on purpose: an unbound
// ctx.waitUntil throws Illegal invocation (Cloudflare Workers best
// practices, read 2026-10-14).
if (viaHandle) return await a.handle(request, { waitUntil: (p) => ctx.waitUntil(p) });
if (url.pathname === "/me") {
const s = await a.session(request);
if (!s) return Response.json({ error: "unauthorized" }, { status: 401 });
const res = Response.json({ email: s.user.email });
// A sliding refresh moved the expiry: renew the cookie, or the browser drops it early.
const renewed = a.sessionCookie(request, s);
if (renewed) res.headers.append("set-cookie", renewed);
return res;
}
return new Response("not found", { status: 404 });
} finally {
// handle flushes its own events. A call outside it, such as the session
// read of /me, flushes here, or its events wait for the next handle call.
if (!viaHandle) ctx.waitUntil(a.observe.flush());
}
},
// The cron trigger of wrangler.jsonc runs this. It deletes the rows that no flow can use.
async scheduled(
_controller: ScheduledController,
env: Env,
ctx: ExecutionContext,
): Promise<void> {
ctx.waitUntil(getAuth(env).api.sweepExpired());
},
} satisfies ExportedHandler<Env>;
}
export default createWorker(mail);
  1. On Postgres, pass limiter: createPostgresLimiter(sql) on the same client as the storage.
The storage and the limiter on Postgres
import { createPostgresAdapter, createPostgresLimiter } from "@authtempo/adapter-postgres";
import { createAuth, type MailPort } from "@authtempo/core";
import type { Sql } from "postgres";
/**
* The storage and the owned limiter on one Postgres client. Every process and
* every isolate shares the counts in `ta_limit`. The default limiter counts in
* memory, per isolate, and is for tests only.
*/
export function authOnPostgres(sql: Sql, mail: MailPort, secret: string) {
return createAuth({
baseURL: "https://api.example.com",
trustedOrigins: [],
secret,
mail,
storage: createPostgresAdapter(sql),
limiter: createPostgresLimiter(sql),
});
}
  1. Off Workers, set clientIp to a function that reads the header of your trusted proxy.
  2. Run the sweep, so that ended windows leave ta_limit.
  • The default limiter counts in memory. On Workers each isolate counts on its own, so the real limit is the limit times the isolate count.
  • Each call of the owned limiter runs one statement, so two calls at the same moment cannot both pass at the last slot.
  • The stored key is the key, the seconds, and the maximum, joined by U+001F. A key with U+001F throws.
  • A request with no client IP counts against one shared bucket of its flow, <flow>:ip:unknown.
  • For an IPv4 address, <ip> is the address. An IPv4-mapped IPv6 address gives its IPv4 form. Any other IPv6 address gives its /64 prefix, written 2001:db8:1:2::/64. The users of one /64 share each per-IP count.
  • On Workers, the default clientIp reads cf-connecting-ip, which Cloudflare sets and a caller cannot forge.
  • A per-code cap and a per-challenge cap live in their rows, so they hold under every limiter.
  • Each window of the owned limiters opens at the first call after the last window ended. The limiter port does not promise that shape.
  • A limiter of your own with windows on the clock lets more guesses through. A 10-minute device code then takes 10 guesses per session and 40 per IP, not 9 and 39. Limits gives the odds.
  • rate_limited: a limit is full. Limits lists every key, window, and maximum.
  • A shared limit that seems to allow too much is often the memory limiter. Check the limiter key of the config.