Skip to Content
Runlane
Build with RunlaneBuild tasks

Trigger after a database write

Start a run for every committed write, even when the process crashes between the commit and the trigger.

Many requests save data and then start background work. For example, an order is saved, and then a run fulfills it. This page shows how to make sure every committed order gets exactly one run.

Why the gap exists

Runlane writes runs through its own database connection, not through your transaction. So the order commit and the trigger are two separate steps:

BEGIN → INSERT order → COMMIT ✓   process crashes   trigger() never runs   ← order without a run

Moving the trigger before the commit doesn't help. If your transaction then rolls back, the run exists for an order that doesn't. A worker can also start the run before your commit is visible.

Every job system that stores jobs outside your transaction has this gap, including hosted services and Redis-based queues. The fix is the transactional outbox pattern: save a small "work still needs starting" marker in the same transaction, and retry from that marker until the run exists.

The pattern

  1. In your transaction, save the business row with a "not triggered yet" marker. The marker commits or rolls back together with the business row.
  2. After the commit, trigger the task with a run ID built from the row, such as fulfill.<orderId>. Then mark the row as triggered.
  3. Every minute, a sweeper finds rows that are still unmarked and repeats step 2.

A run ID is unique in its Runlane environment. Runlane never creates a second run with the same ID, so repeating step 2 is safe. This holds after the run finishes or fails, until the run is pruned.

Add the marker column

This example uses an orders table in your own database. The marker is one column: NULL means "not triggered yet."

migrations/add-order-fulfillment.sql
ALTER TABLE orders
  ADD COLUMN fulfillment_triggered_at timestamptz DEFAULT now();

CREATE INDEX CONCURRENTLY orders_fulfillment_pending
  ON orders (created_at)
  WHERE fulfillment_triggered_at IS NULL;

CONCURRENTLY builds the index without blocking writes to orders. It can't run inside a transaction block, so if your migration tool wraps each file in one, put the index in its own migration that runs outside it.

The default makes the rollout safe. Existing orders get a time, so the sweeper skips them. During the deploy, older app processes keep inserting orders without the column. Those orders also get a time, so the sweeper leaves them to the old code. Only the new code inserts NULL on purpose.

After every app process runs the new code, remove the default:

migrations/drop-order-fulfillment-default.sql
ALTER TABLE orders ALTER COLUMN fulfillment_triggered_at DROP DEFAULT;

Now an insert that forgets the column leaves it NULL, and the sweeper starts its run instead of skipping it.

If some existing orders still need fulfillment, set their fulfillment_triggered_at to NULL, and the sweeper starts their runs.

The partial index keeps the sweeper's query small. It only covers rows that still need a trigger.

The run ID comes from the order ID, so any process can rebuild it. If your run ID can't be rebuilt from the row, store it in its own column in the same transaction. If one write can start several kinds of work, use a separate pending_runs table with one row per run instead.

Save the marker in your transaction

The examples use node-postgres for your application tables. Any database library works, because the marker is ordinary data in your transaction.

src/orders/place-order.ts
import { randomUUID } from 'node:crypto'

import { db } from '../db.js'
import { logger } from '../logger.js'
import { startFulfillment } from './start-fulfillment.js'

export async function placeOrder(input: { customerId: string; total: number }) {
  const orderId = randomUUID()
  const client = await db.connect()

  try {
    await client.query('BEGIN')
    await client.query(
      'INSERT INTO orders (id, customer_id, total, fulfillment_triggered_at) VALUES ($1, $2, $3, NULL)',
      [orderId, input.customerId, input.total],
    )
    await client.query('COMMIT')
  } catch (error) {
    await client.query('ROLLBACK')
    throw error
  } finally {
    client.release()
  }

  // The order is committed. If this trigger fails, the sweeper starts the run later.
  await startFulfillment(orderId).catch((error: unknown) => {
    logger.warn({ error, orderId }, 'Fulfillment trigger deferred to the sweeper')
  })

  return orderId
}

Don't fail the request when the trigger fails: the order is already saved, and the sweeper will finish the job.

Trigger and mark the row

Use one function for both the request path and the sweeper:

src/orders/start-fulfillment.ts
import { db } from '../db.js'
import { runlane } from '../runlane.js'

export async function startFulfillment(orderId: string) {
  await runlane.trigger(runlane.tasks.fulfillOrder, { orderId }, { runId: `fulfill.${orderId}` })

  await db.query('UPDATE orders SET fulfillment_triggered_at = now() WHERE id = $1', [orderId])
}

Repeats return the existing run for this task. If the task sets singletonConflict: SingletonConflict.ReturnExisting, a trigger can instead return another run that holds the singleton, with a different ID. Leave that option off for outbox tasks, so each order gets its own run. A failed run is returned, not restarted; retry it deliberately with runs.retry(). Reusing the ID for another task throws run_id_conflict.

If the process crashes between the trigger and the UPDATE, the row stays unmarked. The next sweep triggers again, receives the existing run, and marks the row.

Run the sweeper

src/orders/sweep-fulfillment.ts
import { db } from '../db.js'
import { logger } from '../logger.js'
import { startFulfillment } from './start-fulfillment.js'

export async function sweepFulfillment() {
  const { rows } = await db.query<{ id: string }>(
    `SELECT id
       FROM orders
      WHERE fulfillment_triggered_at IS NULL
        AND created_at < now() - interval '1 minute'
      ORDER BY created_at
      LIMIT 100`,
  )

  for (const row of rows) {
    try {
      await startFulfillment(row.id)
    } catch (error) {
      logger.warn({ error, orderId: row.id }, 'Fulfillment sweep will retry this order')
    }
  }
}

Call sweepFulfillment() once a minute from a timer you already run, such as a cron job, a scheduled function, or a loop in your worker process. Several sweepers can run at once. They may trigger the same row, but the run ID allows only one run.

The one-minute delay leaves new rows to the request path. Without it, the sweeper and the request could both trigger the same new row. That still creates one run; the other call returns the existing run.

Monitor the backlog

Alert when an unmarked row is older than a few sweep intervals. A row that never clears usually means the trigger keeps failing, for example because the payload no longer matches the task schema. The sweeper's warnings show the error.

Keep your pruning retention far longer than the sweep interval. Once a pruned run is fully removed, its ID is free again, so a still-unmarked row would get a new run.

Why not share the transaction

Runlane doesn't join your transaction, because its storage writes retry themselves. A Runlane transaction that conflicts with another write runs again with fresh data. Runlane can't rerun your transaction, so a conflict would abort your business write instead. Runlane also holds short locks during a trigger. Inside your transaction, those locks would stay held until your transaction ends.

The outbox pattern keeps both sides simple. Your transaction stays yours, Runlane keeps its own retries, and the run ID makes every repeat safe. It also works with every lane and every database library.

On this page