Templates / Scheduled jobs

Nightly cleanup job: delete old rows on a schedule

A scheduled function that runs at 3am and deletes rows older than 30 days — sessions, logs, expired tokens — so storage never grows without bound.

Most apps accumulate rows nobody needs: expired sessions, old logs, abandoned carts. A nightly job that deletes anything past its retention period keeps storage small and queries fast.

Build it with Wisp

Type this into Wisp, or press Build this — it writes the code below, deploys it and gives you a URL:

Every night at 3am, delete rows older than 30 days from the sessions table, at most 1,000 per run, and return how many were deleted.

The code

*cleanup · schedule `0 3 * `*

import { table } from 'wisp';

const RETENTION_DAYS = 30;
const BATCH = 1000;

export async function handler() {
  const cutoff = new Date(Date.now() - RETENTION_DAYS * 86_400_000).toISOString();
  const sessions = table('sessions');
  const old = await sessions.find((row) => row.createdAt < cutoff, { limit: BATCH });
  for (const row of old) await sessions.delete(row.id);
  return { deleted: old.length, cutoff, more: old.length === BATCH };
}

Try it

Press Run to clean up now; the result shows how many rows went and whether more remain (more: true means the next night continues).

How it works

Variations

Questions

What time zone is 3am? The one you set on the schedule. Wisp converts “every night at 3am” to cron in your timezone.

Build it with Wisp — free trial

Related