---
title: "Delete old data on a schedule"
description: "Keep each table's rows only as long as you need them: defineRetention deletes rows past their age in bounded batches that schedule themselves, scheduleRetention starts every rule from one line of crons.ts, and the token helpers keep secrets out of your tables."
canonical_url: "https://nuxt-backend.dev/docs/build/data/retention"
---
# Delete old data on a schedule

> Keep each table's rows only as long as you need them: defineRetention deletes rows past their age in bounded batches that schedule themselves, scheduleRetention starts every rule from one line of crons.ts, and the token helpers keep secrets out of your tables.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

Every row you keep is a row you protect, export and erase. Convex gives you crons and the scheduler, but no time-to-live on a table. `defineRetention` turns one rule into an internal mutation that deletes a table's rows once they pass an age, a batch per transaction, until none is left, on the `schedule` the rule names; one line in `backend/crons.ts` starts every rule. The package's own tables need no rule from you: its component prunes them every hour.

## Define a rule

```ts [backend/retention.ts]
import { defineRetention } from 'nuxt-backend/functions'
import { DAY } from 'nuxt-backend/rate-limit'
import { internalMutation } from './_generated/server'
import { storage } from './storage'

// Drafts nobody touched in 30 days, with their photos.
export const pruneDrafts = defineRetention(internalMutation, {
  fn: 'retention:pruneDrafts',
  table: 'strips',
  index: 'by_status_and_updatedAt',
  match: { status: 'draft' },
  ttl: 30 * DAY,
  batch: 100,
  schedule: { cron: '10 3 * * *' },
  onDelete: (ctx, strip) => storage.release(ctx, strip.photoId),
})

// Failed strips stay 14 days for a retry.
export const pruneFailedStrips = defineRetention(internalMutation, {
  fn: 'retention:pruneFailedStrips',
  table: 'strips',
  index: 'by_status_and_updatedAt',
  match: { status: 'failed' },
  ttl: 14 * DAY,
  batch: 50,
  schedule: { cron: '20 3 * * *' },
  onDelete: async (ctx, strip) => {
    await storage.release(ctx, strip.photoId)
    await storage.revokeShareLink(ctx, 'strips', strip._id)
  },
})
```

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      Default
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        fn
      </code>
    </td>
    
    <td>
      (required)
    </td>
    
    <td>
      The rule's own function path, as <code>
        npx convex run
      </code>
      
       takes it. A batch that leaves rows behind schedules it again
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        table
      </code>
    </td>
    
    <td>
      (required)
    </td>
    
    <td>
      The table to prune. Its rows are typed from your schema
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        index
      </code>
    </td>
    
    <td>
      (required)
    </td>
    
    <td>
      The index to read through, named by its fields as Convex's guidelines ask (<code>
        by_status_and_updatedAt
      </code>
      
      ): the rule reads the field names from the name. The field after any <code>
        match
      </code>
      
       fields holds the time, such as <code>
        updatedAt
      </code>
      
      ; <code>
        by_creation_time
      </code>
      
       uses <code>
        _creationTime
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        match
      </code>
    </td>
    
    <td>
      none
    </td>
    
    <td>
      Equal values for the index's leading fields, in the index's order, such as <code>
        { status: 'failed' }
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ttl
      </code>
    </td>
    
    <td>
      (required)
    </td>
    
    <td>
      How old a row may get, in milliseconds, on the index's time field. <code>
        0
      </code>
      
       deletes a row once that time has passed, for an <code>
        expiresAt
      </code>
      
       field
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        batch
      </code>
    </td>
    
    <td>
      <code>
        100
      </code>
    </td>
    
    <td>
      Rows per transaction. Lower it for large rows or a heavy <code>
        onDelete
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        onDelete
      </code>
    </td>
    
    <td>
      none
    </td>
    
    <td>
      Runs before each row is deleted, in the same transaction
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        schedule
      </code>
    </td>
    
    <td>
      none
    </td>
    
    <td>
      When the rule runs: <code>
        { cron: '10 3 * * *' }
      </code>
      
       (five fields, UTC) or <code>
        { every: { hours: 6 } }
      </code>
      
      . <code>
        scheduleRetention
      </code>
      
       starts it
    </td>
  </tr>
</tbody>
</table>

Pass the builder your other writes use. When an [aggregate](https://nuxt-backend.dev/docs/build/data/read-write/aggregates) counts the table, that is the trigger-wrapped `internalMutation`, so a pruned row leaves the count too.

The mutation takes an optional `{ now }` and returns `{ deleted, more }`. Pass `now` in a test to move the clock without fake timers, or run a pass by hand: `npx convex run retention:pruneDrafts`.

## Schedule it

`scheduleRetention(crons, rules)` starts every rule that has a `schedule`, one cron each, named after the rule's `fn`. Pass it the module the rules live in:

```ts [backend/crons.ts]
import { cronJobs } from 'convex/server'
import { scheduleRetention } from 'nuxt-backend/functions'
import * as retention from './retention'

const crons = cronJobs()

scheduleRetention(crons, retention)

export default crons
```

Anything else the module exports, and a rule with no `schedule`, is left out. It returns the `fn` of each rule it scheduled. Times are UTC. Pick a minute other than `0`, so your passes do not start with everyone else's. [Schedule jobs](https://nuxt-backend.dev/docs/build/data/jobs/scheduled#your-own-jobs) covers `crons.ts`.

A rule with no `schedule` runs from a cron of your own, beside them: `crons.cron('prune drafts', '10 3 * * *', internal.retention.pruneDrafts, {})`. Keep one or the other for a rule. `scheduleRetention` names its cron after the rule's `fn`, so a cron of yours under another name is a second cron: nothing fails, and the rule runs twice.

To delete one file at a time rather than a table's rows, give it an end with [`storage.expire`](https://nuxt-backend.dev/docs/build/data/files/cleanup#give-a-file-an-end): the component's maintenance deletes it, with no rule or cron of yours.

## How a pass runs

1. **A cron starts it.** The pass fixes its cutoff, the current time minus `ttl`, so it always ends.
2. **Each batch** reads up to `batch` rows older than the cutoff through your index and deletes them, in one transaction.
3. **A batch that leaves rows behind schedules the next one** at once, through the rule's own `fn`, with the same cutoff. A batch that takes the last rows ends the pass.
4. **onDelete runs first** for each row, in the same transaction, for what the row points at: a file, a count.

Convex [scheduling](https://docs.convex.dev/scheduling/scheduled-functions) runs each batch; the package writes the loop.

## Store a token's hash, not the token

A token you store as is works for anyone who can read the table: a backup, an export, an administrator's query. Store its SHA-256 hash, compare hashes, and hand the token out once. Three helpers from `nuxt-backend/functions` run in the default Convex runtime, Node and the browser:

<table>
<thead>
  <tr>
    <th>
      Helper
    </th>
    
    <th>
      Returns
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        randomToken(bytes?)
      </code>
    </td>
    
    <td>
      32 random bytes by default, as 43 URL-safe characters. <code>
        bytes
      </code>
      
       is a whole number from 16 to 1024; anything else throws a <code>
        TypeError
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        sha256Hex(text)
      </code>
    </td>
    
    <td>
      The text's SHA-256, as lowercase hex
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        normalizeEmail(address)
      </code>
    </td>
    
    <td>
      The address trimmed and lowercased, the form to store and compare it in
    </td>
  </tr>
</tbody>
</table>

```ts [backend/reviewLinks.ts]
import { backendError, randomToken, sha256Hex } from 'nuxt-backend/functions'
import { DAY } from 'nuxt-backend/rate-limit'
import { v } from 'convex/values'
import { authed } from './functions'

// A link that lets a friend review one strip for a week.
export const create = authed.mutation({
  args: { stripId: v.id('strips') },
  handler: async (ctx, { stripId }) => {
    const strip = await ctx.db.get('strips', stripId)
    if (strip?.authorId !== ctx.user.id) throw backendError('forbidden', { reason: 'not_owner' })
    const token = randomToken()
    const tokenHash = await sha256Hex(token)
    await ctx.db.insert('reviewLinks', { stripId, tokenHash, expiresAt: Date.now() + 7 * DAY })
    return token // shown once: only its hash stays
  },
})
```

Look a link up by `await sha256Hex(token)` through an index on `tokenHash`, and prune expired ones with a rule on `by_expiresAt` and `ttl: 0`. A link to a whole row that its owner turns on and off is a [share link](https://nuxt-backend.dev/docs/build/data/files/share-links), which does all of this for you.

## What happens when…

<table>
<thead>
  <tr>
    <th>
      Situation
    </th>
    
    <th>
      Result
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      A batch throws, in <code>
        onDelete
      </code>
      
       or the delete
    </td>
    
    <td>
      The batch rolls back, the pass ends, and the log has <code>
        retention.batch_failed
      </code>
      
       with the table and the row
    </td>
  </tr>
  
  <tr>
    <td>
      The next pass starts
    </td>
    
    <td>
      It retries from the same oldest rows, so a row whose <code>
        onDelete
      </code>
      
       keeps throwing holds the rule up until you fix it
    </td>
  </tr>
  
  <tr>
    <td>
      The index's time field is missing on a row
    </td>
    
    <td>
      The row sorts first and is deleted on the first pass: give old rows the field before you add the rule
    </td>
  </tr>
  
  <tr>
    <td>
      The rule is malformed: an <code>
        fn
      </code>
      
       with no module, a negative <code>
        ttl
      </code>
      
      , a <code>
        batch
      </code>
      
       below 1, an <code>
        index
      </code>
      
       whose name does not start with the <code>
        match
      </code>
      
       fields, or a <code>
        schedule
      </code>
      
       with neither or both of <code>
        cron
      </code>
      
       and <code>
        every
      </code>
    </td>
    
    <td>
      The module throws a <code>
        TypeError
      </code>
      
       as it loads, so the deploy fails and the message names the index it expected
    </td>
  </tr>
  
  <tr>
    <td>
      You rename a rule's <code>
        fn
      </code>
    </td>
    
    <td>
      Its cron is renamed with it: Convex drops the old one and starts the new one on the next deploy
    </td>
  </tr>
</tbody>
</table>

## Limits

- **Your tables only.** The component prunes its own tables on its own windows ([Limits and retention](https://nuxt-backend.dev/docs/reference/backend/limits)); a rule never reaches them.
- **Function calls.** Each batch is one mutation call on your Convex plan. A larger `batch` makes fewer calls, within Convex's per-transaction read and write limits.
- **Not legal retention.** How long you may keep personal data is a legal question: [Privacy, GDPR and cookies](https://nuxt-backend.dev/docs/ship/compliance/privacy). Not legal advice.

## Test it

```ts [backend/retention.test.ts]
import { defineBackendTestApp } from 'nuxt-backend/test'
import { DAY } from 'nuxt-backend/rate-limit'
import { expect, test } from 'vitest'
import { internal } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('prunes drafts past 30 days', async () => {
  const t = testApp()
  await t.run(ctx => ctx.db.insert('strips', { workspaceId: 'w', authorId: 'u', title: 'Old', status: 'draft', updatedAt: 0 }))
  const result = await t.mutation(internal.retention.pruneDrafts, { now: 31 * DAY })
  expect(result).toEqual({ deleted: 1, more: false })
})
```

## Related

- [Schedule jobs](https://nuxt-backend.dev/docs/build/data/jobs/scheduled): `crons.ts`, and what the component's maintenance prunes.
- [Keep storage clean](https://nuxt-backend.dev/docs/build/data/files/cleanup): `storage.release` and the orphan sweep.
- [Your data](https://nuxt-backend.dev/docs/build/data/your-data#personal-data-joins-export-and-erasure): personal data in your tables.
- [Limits and retention](https://nuxt-backend.dev/docs/reference/backend/limits): how long the package keeps its own records.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
