Delete expired rows (the sweep)
For: an operator of an app that runs authtempo.
What it does: auth.api.sweepExpired() deletes the rows that no flow can use any more, and answers a count for each kind.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- A scheduler: a cron trigger on Workers, or a timer of your host off Workers. The Workers settings show the trigger.
- Add a cron trigger to
wrangler.jsonc, such as"triggers": { "crons": ["17 * * * *"] }. - Add a
scheduledhandler to the Worker that callssweepExpiredinsidectx.waitUntil. - Off Workers, call
auth.api.sweepExpired()from a timer once an hour.
import { type Auth, type Clock, createAuth, type MailPort, type StorageAdapter, systemClock,} from "@authtempo/core";
export function createSweepAuth( deps: { storage: StorageAdapter; mail: MailPort; secret: string }, clock: Clock = systemClock,) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, clock, });}
/** * The scheduled handler of a Worker. A cron trigger in wrangler.jsonc calls * it. The counts hold no secret, so the log line may carry them. */export function sweepHandler(getAuth: () => Auth) { return { async scheduled( _controller: unknown, _env: unknown, ctx: { waitUntil(p: Promise<unknown>): void }, ) { ctx.waitUntil( getAuth() .api.sweepExpired() .then((counts) => console.log("authtempo sweep", JSON.stringify(counts))), ); }, };}import { describe, expect, it } from "vitest";import { call, harness } from "../support/harness.ts";import { createSweepAuth, sweepHandler } from "./sweep.ts";
describe("delete expired rows", () => { it("deletes an expired link and answers every count", async () => { let now = new Date("2026-10-14T00:00:00.000Z"); const auth = createSweepAuth(harness(), { now: () => now }); await call(auth, "POST", "/auth/magic-link/request", { email: "ada@example.com" }); now = new Date(now.getTime() + 16 * 60_000); const counts = await auth.api.sweepExpired(); expect(counts.verificationExpired).toBe(1); expect(Object.keys(counts).sort()).toEqual([ "anonymousUsers", "apiTokens", "invitations", "jwks", "limits", "oauthClientSecrets", "oauthClients", "oauthDevices", "oauthLogouts", "oauthSessionLinks", "oauthTokens", "organizationRows", "organizationTokens", "pendingSessions", "scimTokens", "sessions", "ssoDomains", "ssoExpiryNotices", "ssoPendingDomains", "ssoSetupRows", "totpSetups", "trustedDevices", "verificationConsumed", "verificationExpired", ]); });
it("runs from the scheduled handler", async () => { const pending: Promise<unknown>[] = []; await sweepHandler(() => createSweepAuth(harness())).scheduled( {}, {}, { waitUntil: (p) => pending.push(p) }, ); // The handler hands the sweep to waitUntil, so the run outlives the event. expect(pending).toHaveLength(1); await expect(Promise.all(pending)).resolves.toHaveLength(1); });});The counts
Section titled “The counts”| Count | What it deletes |
|---|---|
verificationExpired |
Every verification row past its expiry, spent or not: links, codes, states, challenges, held requests. |
verificationConsumed |
A spent verification row one day after its spend. |
invitations |
Invitations that are accepted or expired. |
sessions |
Sessions past their expiry. |
pendingSessions |
Sessions that an act left for the sweep, past the calls of the act. A ban and a revoke of the platform role leave the sessions of the user. A ban, a revoke, an account delete, a removal, a leave, and a role change leave the impersonation sessions that the operator opened. A claim with a session.afterEnd hook on D1, SQLite, and the memory store leaves the claimant’s sessions past 100. The step ends only the unproved ones, over its runs. Each gets session.afterEnd, and an impersonation session gets the stop row of the cause. The sweep reads their rows before the idle clients, and the outbox leaves the calls of one page for them. Until the sweep ends it, every door refuses the session of a banned user, and every operator check refuses a former operator. Every door also refuses a left impersonation session. A left session of a claimant ends at its next use. A SCIM deactivate keeps its row after the work, as the record of the act. Each door refuses a session or a refresh family that began before the act, or up to 5 seconds after it, while the record lives. The record lives the longest life of a session or a refresh family, and one day more. For a family that is the top value of oauth.refreshTtlDays, 365 days, since another server can run a longer one. For a session, the longer life of the config at the act and at the sweep counts. The expiry step then deletes it. So the table holds at most one such row per act per user. |
anonymousUsers |
Anonymous users made more than anonymous.ttlDays ago with no live session, with their session rows. At most anonymous.sweepBatch in one sweep, default 100, oldest first by createdAt. Each deleted user gets user.afterDelete. The step runs last, in a share of the calls of one page that the steps before it leave free. 0 while anonymous is off. |
apiTokens |
API tokens past their expiry. A token with no expiry stays. |
organizationTokens |
Organization tokens past their expiry. A token with no expiry stays. |
trustedDevices |
Trusted devices past their expiry. |
totpSetups |
Second factor setups that no enable confirmed within 15 minutes. |
jwks |
Signing keys retired more than 24 hours ago. |
oauthTokens |
Refresh tokens past their expiry. |
oauthClients |
Up to 100 OAuth clients unseen for 90 days, with no consent and no refresh token. A client of api.oauth.clients.create stays: you made it on purpose. |
limits |
The limit windows that ended, when the limiter has a sweep. |
oauthDevices |
Device grants past their expiry: pending, decided, and spent. A poll of such a code answers expired_token before the sweep, and invalid_grant after it. |
oauthSessionLinks |
Links of OAuth clients to sessions that are gone, at most 250 in one sweep, and as many as the calls of the sweep allow. Each link becomes a back-channel sign-out message: an expiry ends a session too. |
oauthLogouts |
Back-channel sign-out messages, at most 50 in one sweep and at most 10 of one client, as many as the calls of the sweep allow. The sweep takes the messages of each client in turns. So a client that fails cannot hold back the messages of other clients. Each due message gets one more attempt. The count holds the messages that a client took, and the messages that core deleted after their sixth attempt. |
oauthClientSecrets |
Old OAuth client secrets past the overlap of a rotation. The sweep clears them from the client. |
ssoDomains |
Verified SSO domains checked again by DNS, 30 days after their last check. Three failures that span 72 hours lose the domain. A domain with a retry due comes first. The recheck runs after the back-channel steps and takes the calls that they leave, up to 20 domains in one sweep. With two resolvers and an idle outbox, one sweep of 50 calls checks 9 domains. A busy outbox still leaves the calls of 1 domain. A lost domain becomes a pending domain with a new record, for 7 days. 0 while sso is off. |
ssoPendingDomains |
Pending SSO domains past their expiry of 7 days. 0 while sso is off. |
scimTokens |
SCIM tokens past their expiry. A token with no expiry stays. 0 while scim is off. |
ssoSetupRows |
Setup links and setup sessions that expired more than 30 days ago, and test runs older than 30 days. A deleted link takes the name of its IT contact and its pending SCIM token with it. 0 while sso is off. This step runs after the pending sessions, with the calls that stay. A sweep that uses its whole budget skips it. |
ssoExpiryNotices |
Deletes no row. It counts the expiry notices that the sweep sent. A notice tells that a SAML certificate, a SCIM token, or a setup link ends in 30, 7, or 1 days. The step claims each stage of a row by one conditional write, then mails the owners and fires hooks.sso.expiring. So two sweeps at once send one notice. For each kind it reads at most 5 due rows, and it mails at most 10 owners of a row. It runs after ssoSetupRows, with the calls that stay. A row that does not fit waits for the next sweep. A disabled connection gets no notice and keeps its date. The SSO setup reference tells the rules. 0 while sso and scim are off. |
organizationRows |
Organizations that an account delete took, whose other rows went now. An account delete takes each organization where the user is the only member. It deletes the organization row, its SSO connections and domains, its SCIM tokens, and its member rows. Its SCIM Users and Groups, teams, invitations, tokens, roles, and SSO setup links and setup sessions wait for the sweep. So the delete fits the 50 queries of D1 Free. No route reaches them in the meantime. A sweep takes at most 50 SCIM Groups of such an organization, and the next sweep goes on. |
How it behaves
Section titled “How it behaves”- The sweep is an
apifunction, not a route. It is safe to run at any time. - Without a trigger, expired rows stay in the database forever.
- The sweep fires two hooks:
session.afterEndfor each pending session, anduser.afterDeleteonce for each deleted anonymous user. It fires nouser.beforeDelete: the user did not ask for the delete. A replayed token answersinvalid_tokenafter the sweep, because its row is gone. - The call budget does not count the work of
user.afterDelete. Each query or request in the hook counts against the limits of the run: 50 queries on D1 Free, 50 subrequests on Workers Free. With such a hook, setanonymous.sweepBatchso that the hook calls of one sweep and the 50 calls of the sweep fit those limits. - The two back-channel steps run near the end:
oauthSessionLinks, thenoauthLogouts. The recheck of the SSO domains comes next. The pending sessions come last, in the calls that stay. One sweep reads at most 250 links, in 5 pages of 50, and goes round all links. - By default the whole sweep fits 50 calls: the queries and the posts of the messages. D1 Free allows 50 queries in one run (D1 limits page updated 21 April 2026). Workers Free allows 50 subrequests in one run (Workers limits page updated 12 October 2026). Both pages were read 2026-10-21. Each step stops before a call that does not fit, and the next sweep goes on. A posted message always has room for its delete, so no message goes out twice.
sweepExpired({ callBudget })sets the calls of one sweep: an integer from 50 to 1000, default 50. Another value throws a RangeError before any call. D1 Paid allows 1000 queries in one run (D1 limits page, read 2026-10-20). On Workers Paid or on Postgres, a larger budget sends more messages and ends more left sessions in one sweep.- So one sweep sends about 5 messages, or makes about 15 messages from links. Take 45 sessions, each linked to one public and one pairwise client. On D1 their 90 links become messages and go out within 23 sweeps in any order. Both orders of the test take 22. A message to a client with pairwise subjects costs 1 more call, the read of its subject. The sweep keeps 9 calls for each next message, so such a message first can cost one post. A test on D1 pins the best and the worst order. To send them sooner, run the sweep more often, such as every 5 minutes.
- An operator act sends no message in its call: the end of sessions, the ban, and the revoke of the platform role. The sweep sends their messages.
If it fails
Section titled “If it fails”- The sweep answers no error code. A storage error throws, and the scheduled run fails in the Worker’s logs.
- A storage error in one of the two back-channel steps does not throw. The step writes one log line,
authtempo: the sweep link step stoppedorauthtempo: the sweep outbox step stopped, and counts 0. The counts above it stay, and the next sweep goes on. A stop loses no message. The messages of a page of links and the delete of those links are one write. A message that a stop holds before its post loses no attempt. - A storage error in the expiry step does not throw. The step writes
authtempo: the sweep sso expiry step stoppedand counts 0 for that kind. The other kinds still run. A row that a stop holds before its claim gets its notice at the next sweep. - A
limitscount of 0 with the memory limiter is normal: the memory limiter deletes ended windows at each check.