Skip to Content
Runlane
Run in production

Prune old runs and tokens

Remove terminal history in bounded batches without touching active work.

Pruning deletes data. Choose retention from your audit, support, replay, and compliance needs. Before you start, make sure backups or downstream exports retain anything that must outlive Runlane storage.

Only terminal runs older than the cutoff can be pruned. Active work is never a valid target.

Understand when a run disappears

Runlane deletes simple runs and their events, steps and their token owners, outbox records, logs, patch markers, and batch membership in one transaction. It can pack several runs into that transaction. A run with legacy child bindings, token links, durable streams, or too many records for one transaction first becomes logically absent through a tombstone. Both paths remove singleton and debounce keys the run still owns and block new outbox claims. Manual pruning also removes idempotency keys. Automatic retention preserves live idempotency keys and saves the final result.

Point reads, events, steps, and operator views stop returning the run at this boundary.

Runlane removes child events, steps, outbox records, and token links in bounded transactions. Cleanup can restart after interruption.

prunedCount counts runs that became logically absent. Physical storage may fall later as maintenance finishes cleanup.

Run cleanup removes matching token links and updates their counters atomically. It does not delete the token.

A pruned run cannot keep a terminal token eligible for resume.

Observation records belong to a separate export stream. Export and checkpoint anything you need before its own retention policy removes it.

Configure automatic run retention

Set runtime rules by final outcome. Runtime and task retention use the same three values. A runtime with retention rules decides every outcome; outcomes it does not list are kept forever. A task overrides the outcomes it lists. Only a runtime without outcome rules leaves unlisted task outcomes without a copied rule.

src/runlane.ts
import { createRunlane, RunRetention } from '@runlane/core'
import { lane, queues, tasks } from './definitions.js'

export const runlane = createRunlane({
  lane,
  queues,
  tasks,
  retention: {
    succeeded: RunRetention.deleteAfter('7d'),
    failed: RunRetention.deleteAfter('30d'),
    cancelled: RunRetention.deleteAfter('7d'),
    expired: RunRetention.deleteAfter('7d'),
  },
})

Keep your existing createMaintenanceHandler() or start({ maintenance: true }) entry point. The first retention pass starts the runtime-rule sweep immediately. Later runtime-rule sweeps start after contractDefaults.retention.interval (12h) has passed since discovery finished. Physical cleanup continues between sweeps. Services check for cleanup on retentionInterval, including manual pruning from other runtimes. Scheduled handlers check on each invocation.

Idle checks read the checkpoint and bounded backlog indexes without writing the sweep lease. They still update lag metrics. A pass claims ownership only when discovery or cleanup is needed.

Runs with copied rules use their saved deletion times. Runs without a copied rule for their final status use the maintenance runtime's rule for that status. This includes older runs and runs created without retention configured. The fallback sweep scans from a fixed cutoff based on the shortest runtime delay, then checks each candidate against its own status rule. DeleteImmediately counts as zero; KeepForever and unset outcomes are skipped. Both save progress after each page and resume on later invocations, including after a restart. Run-rule discovery revisits skipped runs after it catches up and retention.cleanup.interval has passed. A lease allows only one automatic retention owner per environment. An owner that loses its lease stops deleting and saving progress.

A deleteAfter rule sets the minimum age for deletion, not a guaranteed deletion deadline. Dependencies and pending hooks can retain older runs. If deleting a parent releases a child that the sweep has already visited, the child waits for the next sweep. Legacy bindings and oversized result copies can require several sweeps. A completed sweep therefore does not mean every run older than the cutoff is gone.

retention.cleanup.batchLimit bounds candidates per discovery page, per scope. Both scopes share retention.cleanup.maxBatches discovery pages per pass. An active runtime-rule sweep gets at least one page; copied run rules use the remaining pages first. Physical cleanup has a separate budget of retention.cleanup.maxBatches batches. A cleanup batch can delete several simple runs and advance one complex run. Simple runs use the packed transaction budget. Runlane reduces the batch size if storage rejects it. Large or complex runs use bounded child cleanup. These are work budgets, not time limits. Choose smaller budgets for short function timeouts. See the retention options for defaults.

When a service pass makes progress and work remains, it continues without waiting for the next sweep interval. Scheduled handlers can invoke another bounded pass promptly when status is Pending, hasMore is true, and the previous pass made progress. A twice-daily invocation alone may leave a large sweep unfinished. Keep time-sensitive maintenance on its existing cadence.

Retention failures log retention_pass_failed, increment the retention phase error metric, and return RetentionPassStatus.Failed. They do not reject the maintenance call or fail its schedule and delivery work. A retry reuses durable progress; some deletions can have committed before a failure, so a failed result's zero counters do not mean nothing changed. Services back off repeated failures from retentionInterval using the existing exponential retry cadence. Busy means another invocation owns the sweep. Scheduled handlers should retry failed or busy passes on their normal cadence rather than in a tight loop.

hasMore signals unresolved work, not an instruction to retry immediately. This operator example allows at most ten passes. It stops on failure, contention, completion, or a pass with no progress; the normal schedule handles later retries.

scripts/drain-runlane-retention.ts
import { MaintenancePhase, RetentionPassStatus, type RunlaneRuntime } from '@runlane/core'

export async function drainRetention(runlane: RunlaneRuntime) {
  for (let pass = 0; pass < 10; pass += 1) {
    const { retention } = await runlane.runMaintenanceOnce({ phases: [MaintenancePhase.Retention] })
    if (retention?.status !== RetentionPassStatus.Pending || !retention.hasMore) return
    const progress = retention.prunedCount + retention.collectedRunCount + retention.deletedChildRecords
    if (progress === 0) return
  }
}

Maintenance physical cleanup runs only in MaintenancePhase.Retention, including tombstones created by manual pruning. Explicit runs.prune() calls still attempt cleanup and reject on failure.

Keep runtime fallback rules consistent across maintenance owners in the same environment. Changing a rule does not rewrite copied rules. Removing runtime rules stops fallback deletion; copied rules and tombstone cleanup still apply. MaintenancePhase.RunFinalization only finalizes runs.

Override retention per task

import { RunRetention, task } from '@runlane/core'
import * as z from 'zod'

export const sync = task({
  id: 'integration.sync',
  schema: z.object({ integrationId: z.string() }),
  retention: { succeeded: RunRetention.DeleteImmediately, failed: RunRetention.deleteAfter('7d') },
})

This deletes successful syncs as soon as they finish and keeps failed ones for 7 days. Omitted outcomes inherit runtime rules. See creation-time resolution for snapshots and maintenance fallback. runs.prune() can still delete any finished run, including KeepForever runs.

DeleteImmediately deletes the run right after Runlane saves its final result and notifies any runs waiting on it. runNow() and other execution calls still return the saved run. These runs are deleted later:

  • A run with pending lifecycle hooks is deleted after its last hook finishes. A failing hook first retries on the hook retry schedule.
  • Unfinished or oversized child result copies and legacy bindings hold runs.
  • A run with legacy bindings, wait-token links, streams, or too many records for one transaction is deleted by maintenance.
  • If deletion fails, Runlane logs run_completion_deletion_failed and maintenance deletes the run later. The attempt, delivery, or cancellation still succeeds.
  • If a worker stops between saving the result and deleting the run, maintenance deletes it.

Maintenance finds these runs by their deletion time. It applies the settle margin for slow commits and clock differences. It continues from where it stopped on every pass and starts over after it catches up and retention.cleanup.interval has passed to revisit runs it skipped, so a held run can wait until then.

After deletion, runs.get(), the CLI, retry, and rerun cannot find the run. Automatic retention preserves a live idempotency key with its saved final snapshot until the key expires. Repeat triggers return that result without executing. If the encoded key record with its saved result would exceed maxRecordBytes, retention holds the run until the key expires. Manual runs.prune() removes the key. Caller-chosen run IDs have no TTL and become free again after deletion. A runs.watch() that has not yet seen the final state can end with run_not_found. A raw context.join() wait is rejected with configuration_invalid if any final status has a DeleteImmediately rule. Use context.step.trigger(stepKey, task, payload) and join its result, or use RunRetention.deleteAfter(duration). A raw join on an already deleted run fails with run_not_found; its message names DeleteImmediately retention as a possible cause. Named steps preserve results through child result retention. Export any history you need before choosing DeleteImmediately.

Give retention its own execution capacity

For large backlogs, use a separate scheduled handler:

src/handlers/runlane-retention.ts
import { MaintenancePhase } from '@runlane/core'
import { runlane } from '../runlane.js'

export const handler = runlane.createMaintenanceHandler({
  phases: [MaintenancePhase.Retention],
})

A long-running retention process can instead call runlane.start({ maintenance: { phases: [MaintenancePhase.Retention] } }). Keep the other phases running elsewhere. To reserve automatic cleanup for this process, omit MaintenancePhase.Retention from the other owners' phase lists. Both entry points use the same policy, checkpoint, and pruning rules.

Postgres deployments must apply the installed package's migrations before starting the upgraded runtime. The additive deadline migration adds nullable index columns and a sparse index; it does not rewrite existing history. See Postgres storage setup.

Monitor runlane.retention.pending, runlane.retention.sweep.age_ms, runlane.retention.history.lag_ms, and runlane.retention.garbage_collection.lag_ms. History lag includes terminal runs held by dependencies or pending hooks. These bounded index observations do not count the full backlog. See telemetry.

Operate retention at high volume

One million completed runs per week averages about 1.7 runs per second. This is a sizing example, not a measured throughput guarantee. Once that history ages out, cleanup must sustain the same average rate and recover from bursts or downtime. A run can have events, steps, logs, and other child records, so run count alone does not describe the deletion cost.

Keep cleanup running between sweeps

For sustained traffic, use the dedicated retention service with process supervision and shutdown handling. Keep schedule, delivery, and other maintenance phases running elsewhere.

retention.cleanup.interval controls runtime-rule sweeps and run-rule restarts. Copied deadlines continue from their saved position on every pass. The service's retentionInterval controls idle checks for physical cleanup. Productive pending passes drain immediately. You can discover expired history a couple of times a day while keeping cleanup available throughout the day. Calling one bounded pass twice a day does not provide the same capacity.

One sweep lease coordinates automatic retention within an environment. Extra service replicas provide failover; they do not multiply that environment's automatic cleanup throughput. A dedicated process separates execution capacity from time-sensitive maintenance, but both still use the same database resources.

Understand the indexes and lock scope

Retention discovers candidates through bounded index ranges and deletes records by key:

WorkAccess path
Find old terminal runsTerminalRunsByFinishedAt, scoped to the environment and finish-time cutoff
Find due copied rulesRunsByRetentionDeadline, scoped to the environment and deadline before storage time minus the settle margin
Find unfinished cleanupRunTombstonesByTombstonedAt, scoped to the environment and ordered by tombstone time
Find a run's childrenPrimary-key ranges and per-run indexes for the relevant record types

The Postgres provider supplies these paths through its physical indexes. Apply its migrations before enabling retention.

Runlane packs whole simple runs into bounded transactions. Complex runs use a tombstone and small child-cleanup transactions. It does not hold one transaction or an exclusive table lock for the whole sweep. In Postgres, ordinary reads can continue during these deletes; writes that touch the same records can wait. Bounded record counts do not guarantee a maximum transaction duration. Storage latency, contention, and payload size still matter. See PostgreSQL locking.

Budget for physical cleanup

A pass can hide at most retention.cleanup.batchLimit * retention.cleanup.maxBatches runs, but it performs at most retention.cleanup.maxBatches physical-cleanup batches. Each cleanup batch can finish several simple tombstones within the packed transaction budget and advance one complex tombstone in a separate bounded transaction. Complex runs keep the smaller child-record budget. One run can require many cleanup transactions, so logical pruning can finish well before physical cleanup.

Increasing batchLimit alone does not increase the child-record deletion budget. Increasing maxBatches allows more discovery and cleanup work per pass, which can also lengthen an invocation. Start with the default budgets and change them only after measuring your workload. For scheduled functions, keep enough timeout margin for a slow pass and use the bounded drain loop above when more work remains.

Check measured discovery-page time against retention.cleanup.leaseDuration. Checkpoints renew ownership between pages; a page that outlives its lease fails safely. Reduce batchLimit if pages approach that limit. See the retention options.

Compare runlane.retention.pruned.count with runlane.retention.deleted_child_records.count and the cleanup lag metric. A rising prune count alone does not show that storage cleanup is keeping up. Persistent history lag can also reflect retained dependencies or hooks; inspect those before treating it as a capacity problem.

Validate capacity before rollout

Use an isolated database with the same provider, database size, and resource limits as production:

  1. Load a representative backlog, such as one million terminal runs older than the policy cutoff. Include realistic payload sizes, retries, steps, logs, and dependency chains.
  2. Run retention alongside representative trigger and worker traffic. Measure cleanup rate, sweep duration, application latency at the 95th and 99th percentiles, and both history and cleanup lag. Confirm that cleanup catches up across repeated sweeps and resumes after a process restart.
  3. Inspect candidate and child lookup query plans with realistic data and current planner statistics. Index availability alone does not prove the planner will choose an efficient path for your data.
  4. On Postgres, monitor lock waits, database I/O, write-ahead log volume, dead rows, autovacuum progress, and replication lag where applicable. Deletion creates old row versions that vacuum must reclaim. Disk space can become reusable without the database files shrinking; see PostgreSQL routine vacuuming.

Accept the configuration when cleanup keeps up with newly expired history, drains the tested backlog within your operating target, and keeps foreground latency within your service limits.

Preview the candidates

Use runs.list() or runlane runs list with the same terminal statuses and time bounds. Inspect a few candidates first. Start with a small prune limit and raise it only after you see the effect on the database.

Prune one batch

olderThan accepts a duration or a date. A duration becomes one fixed cutoff when the first page starts, so later pages keep the same scope.

For manual pruning, put the paged loop in a scheduled job or operator script, such as scripts/prune-runlane-runs.ts:

scripts/prune-runlane-runs.ts
import { type RunlaneRuntime } from '@runlane/core'

export async function pruneAllRuns(runlane: RunlaneRuntime) {
  let cursor: string | undefined
  let prunedCount = 0

  do {
    const result = await runlane.runs.prune({
      cursor,
      olderThan: '30d',
      limit: 500,
    })

    prunedCount += result.prunedCount
    cursor = result.nextCursor
  } while (cursor !== undefined)

  return prunedCount
}

Continue from the returned cursor

Keep the cursor opaque. Reuse it only with the same environment, cutoff, and status filter. Save it outside the process when the job must survive a restart.

The cursor tracks terminal-run discovery. Maintenance resumes physical cleanup from durable tombstones after a process stops. A pruned run does not become visible again, but its child rows can remain stored until maintenance runs.

If Runlane rejects a cursor, restart with the intended filter. Do not edit or decode it, and do not loosen the cutoff to make the job look successful.

Prune terminal tokens separately

Tokens have their own retention boundary:

scripts/prune-runlane-tokens.ts
import { type RunlaneRuntime } from '@runlane/core'

export async function pruneOneTokenBatch(runlane: RunlaneRuntime) {
  return runlane.wait.pruneTokens({
    olderThan: '30d',
    limit: 500,
  })
}

Only terminal tokens resolved before the cutoff and connected to zero runs can be deleted. The prune transaction removes the token and its exact idempotency owner together. Pending tokens, connected terminal tokens, and inconsistent owner pairs stay in place.

Continue with nextCursor as you do for runs. The first page fixes a duration cutoff using storage time and stores that scope in the cursor. Reuse it only with the same environment and olderThan input.

Choose run and token retention together. Pruning a terminal run may need to remove links before its token becomes eligible. Pending application reviews remain outside both terminal prune sets.

Pending discovery, pending callbacks, and claimed hooks retain their terminal run until delivery settles. Done or exhausted (hooks.status === 'failed') callbacks do not delay pruning. Pruning fences late hook settlement through the existing tombstone checks.

Named output is retained with its run. Tombstones fence late appends, and bounded cleanup deletes stream records, headers, and the name registry. There is no separate stream TTL. A resume cursor for a pruned run raises run_not_found.

Prune from the CLI

Run pnpm exec runlane prune --older-than 30d --limit 100 --json from the application directory. Repeat with --cursor <nextCursor> and the same filters until no cursor remains. Use --status to select terminal statuses. The CLI reference lists every flag.

Pending discovery, callbacks, and claims retain the run. If no executable task registration can resolve them, hooks.discoveryTimeout limits how long they wait unclaimed since becoming due; a worker scan or delivery-recovery pass then marks them failed. Failed and done hooks do not block pruning. Keep maintenance running after removing a task so this cleanup can happen.

On this page