Cleanup Tasks

Delete rows past a retention window every day: declare a task with defineCleanupTask, index its column, and change or turn off the kit's own tasks.

A cleanup task names a table, a window and the rows to delete. The daily run (03:00 UTC) deletes them in batches. You never write the DELETE: the engine does, bounded and by the database's clock.

Recipe: Delete Rows Older Than 14 Days

Data exports are kept for two weeks, then deleted.

1. The table, with an index on the column the task filters on. Without it, every batch scans the whole table.

// apps/web/db/schema.ts
import { v7 as uuidv7 } from 'uuid';
import { index, pgTable, text, timestamp, uuid } from 'void/schema-pg';
export const dataExport = pgTable(
'data_export',
{
id: uuid('id').$defaultFn(uuidv7).primaryKey(),
userId: uuid('user_id').notNull(),
fileKey: text('file_key').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [index('data_export_created_at_idx').on(table.createdAt)],
);

Then pnpm --filter web exec void db generate, review the SQL, and commit it.

2. The task, in your config file: replace the empty cleanupTasks there and merge the imports.

// apps/web/config/cleanup.config.server.ts
import { lt } from 'drizzle-orm';
import { defineCleanupTask, type CleanupTask } from '@kit/cleanup';
import { dataExport } from '#/db/schema.ts';
export const cleanupTasks: CleanupTask[] = [
defineCleanupTask({
name: 'app.exports',
table: dataExport,
window: { days: 14 },
where: ({ cutoff }) => lt(dataExport.createdAt, cutoff),
}),
];

3. A test that proves old rows go and recent ones stay: Testing has the complete file.

The next 03:00 run deletes exports created more than 14 days ago. Nothing else to wire: the task is part of the daily schedule as soon as it is in cleanupTasks. No batchSize: the default 1000 rows per transaction keeps each delete short (Batch Size); these rows are small.

The Task

FieldWhat
nameUnique; app. prefix for yours (kit. is the kit's). Up to 100 lowercase letters, digits, ., _, -, starting with a letter or digit; no : (it is part of the job keys).
tableNeeds a single-column primary key.
window{ days, hours }, whole numbers, at most a century. {} deletes matching rows on the next daily run.
where({ cutoff })The rows to delete. cutoff is SQL for the database's now() minus window.
batchSizeRows per transaction, default 1000.
enabledfalse skips it on the daily run.
  • Build where with the query builder (lt, and, eq, …) or the sql template, which binds values as parameters. Never sql.raw with a variable.
  • Compare with cutoff, not new Date(): the cutoff is the database's clock, the same on every Worker. Kit timestamps use timestamptz for absolute instants. Each batch still runs in UTC for customer tables that store UTC values in timestamp columns.
  • The run is daily, so a row lives up to its window plus a day: { hours: 6 } means "at the first daily run once it's 6 hours old".
  • A where that returns no condition is refused (undefined, e.g. an and() with nothing in it: it would delete every row), and so are a duplicate name, a bad window or a table without a single-column primary key. createCleanup checks every task when the app loads: the kit's config/__tests__/cleanup.server.test.ts imports your config, so a bad task fails pnpm test:unit, and a Worker with one wouldn't start.

Batch Size

Each batch is one transaction: up to batchSize rows, FOR UPDATE SKIP LOCKED (rows your app is writing right now are skipped, not waited on) and a 2 s lock timeout (behind a migration's table lock, the task gives way and retries later instead of waiting, so it never holds up the migration). 1000 rows keeps each transaction short. Lower it for wide rows (large JSON or text) or a busy table; raising it gains little.

Large Backlogs

On a database with millions of old rows, a task runs about 45 s, then hands the rest to a follow-up job that runs straight away, until it is caught up. It doesn't wait for the next day.

Changing the Kit's Tasks

Change a kit task by name in kitTaskOverrides: its window, enabled or batchSize. The kit's tables and conditions stay the kit's, so a kit update never conflicts with your file.

// apps/web/config/cleanup.config.server.ts
import type { KitCleanupOverrides } from '@kit/cleanup';
export const kitTaskOverrides: KitCleanupOverrides = {
'kit.sessions': { window: { days: 7 } }, // keep expired sessions a week
'kit.invitations': { enabled: false }, // keep every invitation
};

Two windows have a floor, checked by the kit's tests: kit.step-up keeps codes as long as the step-up limits count them (STEP_UP_RETENTION_HOURS, a day), and kit.rate-limits keeps counters longer than your longest rate-limit window.


Next: Purge Targets →