Purge Targets
Delete what a deleted user or organization leaves in tables too big to cascade: declare a purge target and let the kit drain it in batches.
A table that grows without bound per user or organization (events, logs, messages, audit rows) can't cascade: one delete would remove millions of rows in one transaction. Give it an indexed owner id with no foreign key, declare it a purge target, and request a purge when the owner is deleted. The purge deletes the owner's rows from every target in batches, in the background.
Recipe: Purge an Organization's Events
1. The table. The owner column has no references() (the rows outlive the organization until the purge reaches them) and leads an index (each batch looks rows up by it).
// apps/web/db/schema.tsimport { v7 as uuidv7 } from 'uuid';import { index, jsonb, pgTable, text, timestamp, uuid } from 'void/schema-pg';export const event = pgTable( 'event', { id: uuid('id').$defaultFn(uuidv7).primaryKey(), // no foreign key: purged after the organization is deleted organizationId: uuid('organization_id').notNull(), type: text('type').notNull(), data: jsonb('data').notNull(), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), }, (table) => [ index('event_organization_id_created_at_idx').on(table.organizationId, table.createdAt), ],);Then pnpm --filter web exec void db generate, review the SQL, and commit it. Reads are filtered by the membership as usual (Scoping Data), so rows waiting for the purge are never shown.
2. The target, in your config file: replace the empty purgeTargets there and merge the imports. No batchSize: the default 1000 rows per transaction keeps each delete short (Batch Size); lower it if data holds large JSON.
// apps/web/config/cleanup.config.server.tsimport { definePurgeTarget, type PurgeTarget } from '@kit/cleanup';import { event } from '#/db/schema.ts';export const purgeTargets: PurgeTarget[] = [ definePurgeTarget({ name: 'app.events', table: event, column: event.organizationId, owner: 'organization', }),];3. Delete the organization through Settings → Organization. The kit saves its database and storage purge jobs together before Better Auth deletes the organization. If saving either job fails, the deletion stops. One request purges every target of the kind: a second organization target needs only step 2.
4. A test: Testing has the complete file.
The Target
| Field | What |
|---|---|
name | Unique; app. prefix for yours. Appears in logs. |
table | Needs a single-column primary key. |
column | The owner's id, a column of table. A column of another table is a type error. |
owner | 'user' or 'organization'. Account deletion requests the purge of every user target, and organization deletion of every organization target (Exit Hooks). |
batchSize | Rows per transaction, default 1000 (why). |
createCleanup checks every target when the app loads and names the table and column it refuses: the column must lead an index or unique constraint (a b-tree or hash one, not partial), must not have a foreign key, and the table needs a single-column primary key. The kit's test config/__tests__/cleanup.server.test.ts imports your config, so a wrong target fails CI.
Requesting a Purge
The kit's organization delete uses prepareOrganizationPurge (apps/web/lib/cleanup.server.ts) before Better Auth's delete. It saves both purge jobs in one transaction with a unique request id. If a worker runs before the owner is gone, it retries. A failed delete leaves harmless jobs that eventually stop; a later deletion gets fresh jobs.
For delete code you write yourself, requestPurge({ tx, ownerKind, ownerId }) enqueues the jobs. Pass the deleted row's id from server code, never request input.
In the transaction that deletes the owner, only in delete code you write yourself: if the delete rolls back, so does the purge.
import { eq } from 'drizzle-orm';import { db } from 'void/db';import { requestPurge } from '#/lib/cleanup.server.ts';import { getOutbox } from '#/lib/outbox.server.ts';import { user } from '#/db/schema.ts';const purge = await db.transaction(async (tx) => {await tx.delete(user).where(eq(user.id, id));return requestPurge({ tx, ownerKind: 'user', ownerId: id });});await getOutbox().nudge([purge]); // optional: else the */5 sweep runs it
Do not call requestPurge before a delete: it cancels on a live owner, and the retained dedupe key blocks a later request. The kit's prepareOrganizationPurge uses a separate retrying request with a fresh key for this case.
If an outbox insert fails during the kit's organization delete, the organization remains. Better Auth may clear the session's active organization before the failure; select it again if needed, then request a new deletion code and retry once the database is healthy.
A repeated request returns exists and enqueues nothing. A refused enqueue throws OutboxEnqueueError. The job belongs to no tenant, so eraseTenant(organizationId) doesn't delete it.
What the Purge Does
- Checks the owner row is gone; a prepared organization purge retries while it exists. Other purge requests cancel on a live owner.
- Deletes one batch per target per round until every target is empty. After a zero-row batch, an indexed read checks whether matching rows remain. If they do, the job drains its other targets, then retries with
yielded; skipped rows cannot make even the final pass falsely complete. - Out of time (about 45 s): hands the rest to a follow-up job that runs straight away.
- Once everything is empty: one final pass an hour later, for rows that requests still in flight at the delete wrote afterwards (no foreign key stops them). Then it's done.
A target that fails (a dropped table, a wrong column) is logged as purge target failed with the target name and owner id; the other targets still drain, then the job retries. If it keeps failing it ends dead: fix the table and replay it.
Next: Testing →