Skip to Content
Runlane
Recipes

Sagas

Undo completed task steps after a real failure, then stop the run.

A saga is a sequence of actions with a matching undo action, called a compensation. Use it when inventory, payments, and shipping belong to separate services and cannot share one database transaction.

A pause does not enter catch or finally. Only a real failure starts compensation. Before the first undo, save the compensation decision and the saved reservation identifiers with context.updateMeta(). Every attempt checks that marker before running forward steps. Save each undo with context.step.run() so recovery can reuse its result.

A non-retryable RunlaneError stops the run after compensation. The metadata marker protects the gap before that final failure is stored: after a crash, the next attempt continues compensation instead of approving an order whose resources were released.

Reserve an order, then await approval

This example saves three forward steps and undoes completed steps in reverse order. The application creates approvalTokenId before triggering the task. The marked service calls are pseudocode; each service must support idempotency keys and return the identifiers used below.

src/tasks/reserve-order.ts
import { ErrorCode, RunlaneError, task, tokenIdSchema } from '@runlane/core'
import * as z from 'zod'

// Metadata is JSON, so a step that never ran is stored as null.
const compensationSchema = z.object({
  inventoryId: z.string().nullable(),
  paymentId: z.string().nullable(),
  shipmentId: z.string().nullable(),
})

export const reserveOrder = task({
  id: 'orders.reserve',
  schema: z.object({ orderId: z.string(), approvalTokenId: tokenIdSchema }),
  output: z.object({ status: z.literal('approved') }),
  retry: { maxRetries: 2, backoff: '1m' },
  async run({ orderId, approvalTokenId }, context) {
    let compensation = compensationSchema.optional().parse(context.run.meta?.compensation)
    let forwardCause: unknown

    if (compensation === undefined) {
      let inventoryId: string | null = null
      let paymentId: string | null = null
      let shipmentId: string | null = null

      try {
        inventoryId = await context.step.run('reserve-inventory', { output: z.string() }, async ({ token }) => {
          // MAKE YOUR API CALLS HERE
          return z.string().parse(await reserveInventory({ orderId, idempotencyKey: token, signal: context.signal }))
        })
        paymentId = await context.step.run('authorize-payment', { output: z.string() }, async ({ token }) => {
          // MAKE YOUR API CALLS HERE
          return z.string().parse(await authorizePayment({ orderId, idempotencyKey: token, signal: context.signal }))
        })
        shipmentId = await context.step.run('reserve-shipment', { output: z.string() }, async ({ token }) => {
          // MAKE YOUR API CALLS HERE
          return z.string().parse(await reserveShipment({ orderId, idempotencyKey: token, signal: context.signal }))
        })

        // A pending approval parks here; it does not enter the catch block.
        const approval = await context.wait
          .forToken(approvalTokenId, { output: z.object({ approved: z.boolean() }) })
          .unwrap()
        if (!approval.approved) {
          throw new RunlaneError({
            code: ErrorCode.TaskFailed,
            message: 'Order approval was declined.',
            retryable: false,
          })
        }
        return { status: 'approved' }
      } catch (cause) {
        forwardCause = cause
        compensation = { inventoryId, paymentId, shipmentId }
        // If this write fails, no undo has started. Let the attempt fail.
        await context.updateMeta({ compensation })
      }
    }

    const { inventoryId, paymentId, shipmentId } = compensation
    try {
      if (shipmentId !== null) {
        const id = shipmentId
        await context.step.run('cancel-shipment', { output: z.null() }, async ({ token }) => {
          // MAKE YOUR API CALLS HERE
          await cancelShipment({ shipmentId: id, idempotencyKey: token, signal: context.signal })
          return null
        })
      }
      if (paymentId !== null) {
        const id = paymentId
        await context.step.run('void-payment', { output: z.null() }, async ({ token }) => {
          // MAKE YOUR API CALLS HERE
          await voidPayment({ paymentId: id, idempotencyKey: token, signal: context.signal })
          return null
        })
      }
      if (inventoryId !== null) {
        const id = inventoryId
        await context.step.run('release-inventory', { output: z.null() }, async ({ token }) => {
          // MAKE YOUR API CALLS HERE
          await releaseInventory({ inventoryId: id, idempotencyKey: token, signal: context.signal })
          return null
        })
      }
    } catch (compensationCause) {
      throw new RunlaneError({
        code: ErrorCode.TaskFailed,
        message: 'Order compensation failed. Repair the remaining reservations before starting a new run.',
        retryable: false,
        meta: { orderId },
        cause: new AggregateError([forwardCause, compensationCause]),
      })
    }
    throw new RunlaneError({
      code: ErrorCode.TaskFailed,
      message: 'Order failed. Completed reservations were compensated.',
      retryable: false,
      meta: { orderId },
      cause: forwardCause,
    })
  },
})

On a pending approval, the run releases capacity with no failure or compensation. On resume, it reads the three saved identifiers and continues at the approval wait. A decline, token expiry, or service failure enters catch. The task stores the compensation marker before undoing the completed reservations. A later attempt reads that marker, skips all forward steps and the approval wait, and replays or finishes the undo steps.

Keep meta.compensation reserved for this task. Do not clear or edit it during recovery. Keep its shape and the step keys compatible across deployments. The original cause is available inside the first attempt; the marker stores only the identifiers needed for recovery.

Both errors at the end are non-retryable, even though the task has a retry policy. A plain Error could schedule a retry under that policy. Runlane stores each RunlaneError message and safe metadata; its cause stays internal. See retry decisions.

Before production

  • Make forward actions and compensations idempotent. Pass each step's token to its service to cover a crash before the result is saved.
  • Undo only actions whose results were saved. Reconcile uncertain service results through that service's idempotency record.
  • Keep connections, locks, and open spans inside step callbacks, away from the approval wait.
  • Test that a pending approval runs no compensation, a decline undoes actions in reverse order, and compensation failure stops for manual repair.
  • Interrupt the final failure write after an undo commits. Recover the expired lease and confirm that the next attempt stays on the compensation path, never returns approved, and reuses the saved undo result.
  • Start a new business operation only after compensation or repair is complete. Do not retry the compensated run automatically.

Read save step results and human-in-the-loop flows.

On this page