Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Run durable work

Write handlers whose steps run once each and that carry on after a crash, a restart or a wait of days.

A plain handler that fails halfway stops there. Its writes are undone, and a message that threw is tried again from the top, so the requests it made outside Luna are made a second time. A durable handler records each step it finishes, so it carries on from where it stopped.

Make a handler durable

Give the handler durable: true in its handler spec, and put each piece of work in ctx.step. A step runs once. Its result is recorded and returned again, without running, whenever the handler starts over.

import { defineLuna, t, table } from "luna";

const pay = (customer: string, amount: number, key: string) =>
  fetch("https://payments.example/charges", {
    method: "POST",
    headers: { "idempotency-key": key },
    body: JSON.stringify({ customer, amount }),
  }).then((r) => r.json() as Promise<{ id: string }>);

export const Shop = defineLuna({
  name: "Shop",
  key: { id: t.string() },
  schema: { orders: table({ id: t.id(), charge: t.string(), status: t.string() }) },
  handlers: (h) => ({
    checkout: h({ args: { amount: t.int() }, durable: true }, async (ctx, { amount }) => {
      const key = ctx.uuid();
      const charge = await ctx.step("charge", () => pay(ctx.key.id, amount, key));
      const order = await ctx.step("record", () => ctx.db.orders.insert({ charge: charge.id, status: "paid" }));
      return { order };
    }),
  }),
});

Each call or message to the handler starts a run, and ctx.runId holds its id. A run lives through crashes, restarts and the luna moving to another machine. It ends when the handler returns or fails, and a finished run is kept for 7 days.

A step’s result is stored as JSON, at most 1 MiB. Store a large output in a table or a bucket, and return a reference to it. ctx.step throws in a handler without durable: true.

Know what runs again

When a run starts over, its handler runs from the top. Finished steps return their recorded results, but the code between steps runs again.

This handler makes a new key each time it starts over. If it crashed while the charge was in flight, the payment service sees a second key and charges twice.

const key = crypto.randomUUID();
const charge = await ctx.step("charge", () => pay(ctx.key.id, amount, key));

This one gets the same key every time, because ctx.uuid() is recorded like a step.

const key = ctx.uuid();
const charge = await ctx.step("charge", () => pay(ctx.key.id, amount, key));

ctx.now() and ctx.random() are recorded too. Put every write and every request outside Luna in a step, or it happens again. Steps must also come in the same order each time the handler runs.

Retry a step that fails

A step that throws is tried again later. A declared error from ctx.fail, or a call to another luna that failed in a way a retry cannot fix, is recorded and thrown at once.

Option Does
attempts How many times to try in all, 3 by default
backoff Milliseconds before the first retry, 1000 by default, doubling after each
timeout How long one attempt may take before it counts as failed
compensate Undoes the step if the run fails later. See Undo steps when a run fails

The step’s function gets signal and attempt. signal fires when the attempt times out or the run is cancelled, so pass it to fetch. attempt counts from 1, including tries a crash cut short.

const charge = await ctx.step(
  "charge",
  ({ signal }) => fetch("https://payments.example/charges", { method: "POST", body, signal }).then((r) => r.json()),
  { attempts: 5, backoff: 2000, timeout: "10s" },
);

The run stops between tries, and the luna may sleep. Once the attempts run out, ctx.step throws the last error. A handler that throws ends its run as failed, and the caller gets the error.

Wait for a time

ctx.sleep takes a delay and ctx.sleepUntil takes a Date or milliseconds since 1970. The run stops, the luna may sleep, and the run starts over when the time comes. Other calls to the luna run meanwhile.

await ctx.step("ship", () => ctx.db.orders.update({ where: { id: order }, set: { status: "shipped" } }));
await ctx.sleep("14d");
await ctx.step("close", () => ctx.db.orders.update({ where: { id: order }, set: { status: "closed" } }));

To wait for an event instead of a time, see Wait for a signal.

Start a run

A call to a durable handler starts a run and waits for its result. If the caller stops waiting, the run goes on. Calls with the same idempotency key join one run instead of starting another.

For a run that lasts longer than a call can wait, send a message with ctx.send. It returns the message’s id, which is the run’s id too. A handler that names its own luna type needs its return type written out.

place: h({ args: { amount: t.int() } }, (ctx, { amount }): { run: string } => {
  const run = ctx.send(Shop, ctx.key).checkout({ amount });
  return { run };
}),

A schedule that names a durable handler starts a run each time it fires. Messages are covered in Call another luna.

Loop without end

A run that loops forever keeps a record of every step it ever made. ctx.continueAsNew clears the record and starts the handler again with new arguments, under the same run id.

poll: h({ args: { round: t.int() }, durable: true }, async (ctx, { round }): Promise<void> => {
  await ctx.step("count", () => ctx.db.orders.count({ where: { status: "paid" } }));
  await ctx.sleep("1h");
  return ctx.continueAsNew({ round: round + 1 });
}),

Deploy while runs are in progress

A luna with a run in progress stays on the version the run started on until all its runs end. Its other calls run on that version too. A run that continues as new starts its next round on the newest version.

Each time a run starts over, Luna checks its steps against the record. If they no longer match, the run fails with RunCodeChanged. Finish or cancel runs before you rename, add or reorder their steps.

In Python, the step options are keyword arguments. See Write lunas in Python.

Next steps

Was this page helpful?