Skip to content

Durable Machines

XState machines in Durable Objects that you can watch live.

Put an XState v6 machine in a Cloudflare Durable Object. It keeps its state, its timers and its messages to other objects, and you can watch every one of them happen.

src/transfer.tsts
import { DurableObject } from "cloudflare:workers";
import { DurableMachine, type Envelope } from "durable-machines";
import { transferMachine, type TransferEvent } from "./machines/transfer";

export class Transfer extends DurableObject<Env> {
  machine = new DurableMachine(this, transferMachine, {
    input: (id) => ({ transferId: id }),
    actions: {
      toAccount: ({ accountId, event }) => this.machine.deliver("Account", accountId, event),
    },
  });

  send(event: TransferEvent, envelope?: Envelope) {
    return this.machine.send(event, envelope);
  }
}

transferMachine is a plain XState machine. Send it an event from anywhere:

await env.Transfer.getByName("t-42").send({ type: "transfer.start", from: "you", to: "bob", amount: 25 });

This is what it looks like

Below is Durable Bank, built this way. You have your own account. Send money to a stranger and watch the Transfer move it from object to object. Send to bob to see a refund: his account is frozen.

Live. Open it full screen.

Why

A Durable Object is one entity that handles one request at a time: an order, a transfer, a build. That’s exactly what an XState actor wants. Durable Machines does the plumbing in between:

  • State survives. The snapshot is saved after every transition and restored when the object wakes.
  • Timers survive. after and timeout wake the object with an alarm, even after it was evicted.
  • Messages aren’t lost. deliver() writes the message in the same transaction as the state that sent it. Receivers drop repeats.
  • Failures come back. A message that can’t be delivered returns to the sender as outbox.failed, so the machine can undo its work.
  • The diagram is the code. Every object streams its machine, state and messages over a WebSocket. A machine whose transitions hide where they go is refused, so the diagram never leaves out an edge.

Other Durable Object frameworks show you an object’s data. Durable Machines shows you what it does.

Next

Type to search…

↑↓ navigate↵ selectEsc close