---
title: Wait for a signal
description: Pause a durable run until a named signal arrives, send signals to runs, and list, read and cancel a luna's runs.
related:
  - /background/run-durable-work
  - /background/undo-steps-when-a-run-fails
  - /sdk/ctx
---

Some work cannot go on until something outside it happens, such as a payment being confirmed. A durable run can wait for a named signal for minutes or months, then carry on with what the signal carries.

## Wait for a signal

In a [durable handler](/background/run-durable-work), [`ctx.waitFor`](/sdk/ctx) takes a signal's name and returns its payload. After `timeout`, it returns `undefined` instead.

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

export const Shop = defineLuna({
  name: "Shop",
  key: { id: t.string() },
  schema: {
    orders: table({ id: t.id(), status: t.string(), run: t.string().optional(), ref: t.string().optional() }),
  },
  handlers: (h) => ({
    fulfil: h({ args: { order: t.int() }, durable: true }, async (ctx, { order }) => {
      const paid = await ctx.waitFor<{ ref: string }>("paid", { timeout: "1d" });
      const set = paid ? { status: "paid", ref: paid.ref } : { status: "expired" };
      await ctx.step("settle", () => ctx.db.orders.update({ where: { id: order }, set }));
      return set.status;
    }),
  }),
});
```

The run stops while it waits, and the luna may sleep. Other calls to the luna run as usual. Without a `timeout`, the run waits until a signal comes.

## Send a signal to one run

Start the run with `ctx.send`, which returns the run's id, and keep the id. Then [`ctx.runs`](/sdk/ctx) sends a signal to that run.

```ts luna/lunas/shop.ts
place: h({}, (ctx): { order: number } => {
  const order = ctx.db.orders.insert({ status: "waiting" });
  const run = ctx.send(Shop, ctx.key).fulfil({ order });
  ctx.db.orders.update({ where: { id: order }, set: { run } });
  return { order };
}),
confirm: h({ args: { order: t.int(), ref: t.string() } }, async (ctx, { order, ref }): Promise<boolean> => {
  const run = ctx.db.orders.get(order)?.run;
  return run ? ctx.runs(Shop, ctx.key).signal(run, "paid", { ref }) : false;
}),
```

A signal sent to a run is kept until the run waits for that name. A payment confirmed before the run reached `ctx.waitFor` is still there when it does. `signal` returns false if the run has finished.

Whatever hears of the payment calls `confirm`, such as a webhook route. See [Receive webhooks](/http/receive-webhooks). Apps and outside callers reach runs only through handlers like this one.

:::tip
A handler that names its own luna type needs its return type written out, as `place` and `confirm` do here. Without it, TypeScript cannot infer the type.
:::

## Signal every run waiting on a luna

[`ctx.signal`](/sdk/ctx) takes a luna type, a key, a name and a payload. Every run on that luna waiting for the name gets it, and `ctx.signal` returns how many did.

```ts luna/lunas/shop.ts
confirmAll: h({ args: { ref: t.string() } }, (ctx, { ref }): Promise<number> => ctx.signal(Shop, ctx.key, "paid", { ref })),
```

Nothing is kept for a run that starts waiting later. If the run has not reached `ctx.waitFor` yet, the signal is lost. Send to one run when the signal may come early.

Signal names cannot start with `$`.

## Wait in a plain handler

`ctx.waitFor` also works in a handler that is not durable. There it waits in memory, for at most 15 minutes, and fails if the luna stops meanwhile. Only `ctx.signal` reaches it.

```ts luna/lunas/room.ts
ask: h({}, async (ctx) => {
  const answer = await ctx.waitFor<string>("answer", { timeout: "2m" });
  return answer ?? "no answer";
}),
```

## Hand out a promise

[`ctx.promise`](/sdk/ctx) makes a signal name that only this run waits for. Pass its `runId` and `name` to whoever completes it, and wait with `wait`. This handler keeps both in an `asks` table.

```ts luna/lunas/shop.ts
approve: h({ durable: true }, async (ctx) => {
  const approval = ctx.promise<boolean>();
  await ctx.step("ask", () => ctx.db.asks.insert({ run: approval.runId, name: approval.name }));
  const ok = await approval.wait({ timeout: "7d" });
  return ok === true;
}),
```

The one who completes it calls `ctx.runs(Shop, key).signal(runId, name, value)`. `ctx.promise` throws in a handler that is not durable.

## List, read and cancel runs

`ctx.runs(luna, key)` reaches the runs of any luna, this one included.

| Method | Does |
| --- | --- |
| `get(id)` | Returns the run, or fails with `NotFound` if there is none |
| `list({ status, limit })` | Returns runs newest first, 100 by default and 1,000 at most. `status: "active"` lists unfinished ones |
| `signal(id, name, payload)` | Sends a signal to one run, as above |
| `cancel(id)` | Asks the run to stop, and returns false if it has finished |

A run's `status` is `running`, `waiting`, `done`, `failed` or `cancelled`. A finished run has its `result`, and a waiting one lists the names in `waitingFor`. A finished run is kept for 7 days.

```ts luna/lunas/shop.ts
status: h({ args: { run: t.string() } }, async (ctx, { run }): Promise<string> => {
  const info = await ctx.runs(Shop, ctx.key).get(run);
  return info.status;
}),
```

A cancelled run stops at its next step, sleep or wait, and a step in progress sees its `signal` fire. Its compensations run, and its caller gets an error of kind `Cancelled`. See [Undo steps when a run fails](/background/undo-steps-when-a-run-fails).

## Next steps

- [Run durable work](/background/run-durable-work) covers steps, retries and sleeps.
- [Undo steps when a run fails](/background/undo-steps-when-a-run-fails) cleans up after a cancelled run.
- [Receive webhooks](/http/receive-webhooks) turns a payment provider's call into a signal.
