---
title: Undo steps when a run fails
description: Give a durable run's steps compensations that undo them, newest first, when the run fails or is cancelled.
related:
  - /background/run-durable-work
  - /background/wait-for-a-signal
  - /sdk/ctx
---

A durable run that fails partway has already done real work, such as holding money in a wallet. Luna does not undo what a run's steps did, so the run has to undo it itself.

:::warning
A failed durable run keeps its writes, and a call it made to another luna stays done. Only a compensation undoes them.
:::

## Give a step an undo

The `compensate` option of [`ctx.step`](/sdk/ctx) takes a function that undoes the step. It gets the step's result.

```ts luna/lunas/shop.ts
import { defineLuna, t, table } from "luna";
import { Wallet } from "./wallet.ts";

export const Shop = defineLuna({
  name: "Shop",
  key: { id: t.string() },
  schema: { stock: table({ item: t.string(), count: t.int() }, { primaryKey: ["item"] }) },
  handlers: (h) => ({
    checkout: h({ args: { item: t.string(), amount: t.int() }, durable: true, errors: { OutOfStock: t.json() } }, async (ctx, { item, amount }) => {
      const wallet = ctx.call(Wallet, { id: ctx.key.id });
      const hold = await ctx.step("hold", () => wallet.hold({ amount }), {
        compensate: (hold) => wallet.release({ hold }),
      });
      await ctx.step("take", () => {
        const left = ctx.db.stock.get(item)?.count ?? 0;
        if (left < 1) return ctx.fail("OutOfStock", { item });
        ctx.db.stock.update({ where: { item }, set: { count: left - 1 } });
      });
      await ctx.step("capture", () => wallet.capture({ hold }));
    }),
  }),
});
```

When the item is out of stock, `take` fails with a declared error and the run fails. The `hold` step's compensation runs and releases the money. Then the caller gets `OutOfStock`.

## Know which compensations run

A compensation runs only for a step that finished. A step that failed, or never ran, has nothing to undo.

| Step | In the run above | On failure |
| --- | --- | --- |
| `hold` | Finished | `release` runs |
| `take` | Failed with `OutOfStock` | Nothing runs |
| `capture` | Never ran | Nothing runs |

Compensations run newest first, so the last thing done is undone first. Each runs as a step of its own, such as `compensate:hold` for the step `hold`, and is retried as any step is.

A run fails when its handler throws, including when a step runs out of attempts. See [Run durable work](/background/run-durable-work) for retries.

## Undo when a run is cancelled

`ctx.runs(luna, key).cancel(id)` asks a run to stop. The run stops at its next step, sleep or wait, runs its compensations, and ends as `cancelled`.

```ts luna/lunas/shop.ts
cancel: h({ args: { run: t.string() } }, (ctx, { run }): Promise<boolean> => ctx.runs(Shop, ctx.key).cancel(run)),
```

A step in progress sees its `signal` fire, so a `fetch` given that signal stops at once. The run's caller gets an error of kind `Cancelled`, and the run throws [`RunCancelled`](/sdk/errors) inside the handler. Listing and reading runs is covered in [Wait for a signal](/background/wait-for-a-signal).

## Write compensations that can run twice

A compensation is a step, so a crash while it runs starts it again. Make each one safe to repeat. A call to another luna with an `idempotencyKey` runs once however many times it is sent.

```ts luna/lunas/shop.ts {2}
await ctx.step("hold", () => wallet.hold({ amount }), {
  compensate: (hold) => wallet.release({ hold }, { idempotencyKey: `release-${hold}` }),
});
```

If a compensation still fails after its attempts, the ones after it do not run. The run then fails with that compensation's error.

In Python, `compensate` is a keyword argument of `ctx.step`. See [Write lunas in Python](/lunas/write-lunas-in-python).

## Next steps

- [Run durable work](/background/run-durable-work) covers steps, retries and sleeps.
- [Call another luna](/lunas/call-another-luna) explains idempotency keys.
- [Wait for a signal](/background/wait-for-a-signal) shows how to read and cancel runs.
