Recipes
Four products as workflows, compiled and run: an order saga, a campaign send, an intake with approval, a booking with reminders; the generator's templates.
Generated from the SDK's own source (
docs/durable/recipes.md) at build; edit there.
Four products, each the shape of a well-known one, each written as a
workflow of five to seven statements (the cancel one) against the verbs
as they landed
(eight to twenty-five lines as the formatter prints them): an order
saga with compensation (the storefront shape), a campaign send in
batches with tracking webhooks (the Mailchimp shape), an intake with a
provider's approval and a prescription follow-up (the telehealth shape),
and a booking with reminders and a reschedule (the Calendly shape). They
are the roadmap's acceptance test: when each is ten lines and runs in
testDurable(), the SDK is what it claims. Where one could not be written
in ten lines, the last section says so.
The page stands for any host. Every ts block below is a file (the fence
names it), imports from @durable-sdk/core and
@durable-sdk/vercel/react-router alone (the fifth section's test block
from @durable-sdk/testing and vitest too, being a test), and names
nothing of the 3PL. tests/docs/recipes.test.ts extracts the blocks, compiles them as
one program against the package's types (a block that does not type-check
fails the build) and runs every workflow in testDurable() with in-test
doubles for the outside. To build on them, copy the blocks into a project
that has the packages, bind the Services that services.ts declares to
real clients at boot (createDurable({ services })) and bind the four
products as the plugins plugins.ts defines
(createDurable({ plugins: [orders, campaigns, intakes, bookings] });
ADR-0063 Appendix M U5), or hand catalog.ts's merged descriptors to
createDurable({ catalog }) and list the files in a manifest.
Three files are shared by the four.
The catalog. The facts the recipes emit, one descriptor each, one
defineEvents per product (what its plugin declares; RECIPE_EVENTS is
the four merged, for a host that binds one catalog): the key
is the fact's identity from its payload (never the clock), parts the
fields it is made of. A part that is a moment by name (startsAt,
before) says in moments whose clock stamped it, the booking's own
record and the sweep's slot here: the catalog refuses the part without
the sentence, since a moment read at the emit site would key a second
fact on every attempt (ADR-0060 decision 6).
The payload types join EventPayloads, the one interface every emit,
on and waitFor is typed against, so a name outside it is a type error.
The log names a recipe writes (ctx.log.info("reminder.skipped", …)) are
rows of its log catalog the same way (ADR-0060 decision 17): RECIPE_LOGS
says each name's level, the fields it passes and what the line means,
joins HostLogEvents, and is bound as createDurable({ logs }) beside
the events; a misspelled name is a type error naming the rows under its
prefix, and a line under an unlisted name still prints, said once as
log.unlisted.
import { defineEvents, type LogRowsOf } from "@durable-sdk/core";
declare module "@durable-sdk/core" {
interface EventPayloads {
/** The saga's end: stock held, the card charged, a shipment made. */
"order.placed": { orderId: string; shipmentId: string };
/** The campaign went out: to how many recipients. */
"campaign.sent": { campaignId: string; recipients: number };
/** The provider's tracking webhook: one message delivered, one opened. */
"campaign.delivered": { campaignId: string; messageId: string };
"campaign.opened": { campaignId: string; messageId: string };
/** The follow-up after a prescription, due days later; the listener re-reads the intake. */
"prescription.followup.due": { intakeId: string };
/** A booking's reminder, keyed on the start too: a reschedule is a new key. */
"booking.reminder.due": {
bookingId: string;
startsAt: string;
reminder: string;
};
/** A booking the calendar reported unattended. */
"booking.noshow": { bookingId: string; before: string };
}
}
/** Spelled once, beside the emit and the cancel (ADR-0050 amendment). */
export const followUpKey = (intakeId: string) =>
`prescription.followup.due:${intakeId}`;
export const reminderKey = (
bookingId: string,
startsAt: string,
reminder: string,
) => `booking.reminder.due:${bookingId}:${startsAt}:${reminder}`;
export const ORDER_EVENTS = defineEvents({
"order.placed": {
key: (p) => `order.placed:${p.orderId}`,
parts: ["orderId"],
},
});
export const CAMPAIGN_EVENTS = defineEvents({
"campaign.sent": {
key: (p) => `campaign.sent:${p.campaignId}`,
parts: ["campaignId"],
},
"campaign.delivered": {
key: (p) => `campaign.delivered:${p.campaignId}:${p.messageId}`,
parts: ["campaignId", "messageId"],
},
"campaign.opened": {
key: (p) => `campaign.opened:${p.campaignId}:${p.messageId}`,
parts: ["campaignId", "messageId"],
},
});
export const INTAKE_EVENTS = defineEvents({
"prescription.followup.due": {
key: (p) => followUpKey(p.intakeId),
parts: ["intakeId"],
},
});
export const BOOKING_EVENTS = defineEvents({
"booking.reminder.due": {
key: (p) => reminderKey(p.bookingId, p.startsAt, p.reminder),
parts: ["bookingId", "startsAt", "reminder"],
moments: {
startsAt:
"the booking's own start, from its record: a reschedule is a new start and a new key, never a clock read at the emit",
},
},
"booking.noshow": {
key: (p) => `booking.noshow:${p.bookingId}:${p.before}`,
parts: ["bookingId", "before"],
moments: {
before:
"the sweep's slot (slot.at), the schedule's moment handed to the run's input and the same on every attempt; never a clock read at the emit",
},
},
});
/** The four merged, for a host that binds one catalog (`createDurable({ catalog })`) instead of the plugins. */
export const RECIPE_EVENTS = {
...ORDER_EVENTS,
...CAMPAIGN_EVENTS,
...INTAKE_EVENTS,
...BOOKING_EVENTS,
};
/** The lines the recipes write: a row per name, merged into `LogName` below. */
export const RECIPE_LOGS = {
"followup.skipped": {
level: "info",
fields: ["status"],
meaning:
"The follow-up's listener re-read the intake and found it no longer open (`status`, or `gone`): nothing is sent.",
},
"reminder.skipped": {
level: "info",
fields: ["startsAt"],
meaning:
"The reminder's listener re-read the booking and found it moved or gone (`startsAt`): nothing is sent for this key.",
},
} as const;
declare module "@durable-sdk/core" {
interface HostLogEvents extends LogRowsOf<typeof RECIPE_LOGS> {}
}The outside. Stock, payments, shipping, an audience, a notify
provider (and the secret it signs its tracking webhook with), the intakes,
a pharmacy, a calendar: interfaces a product implements with its own
clients (a host's are connectors behind a registry), declared on the
core's Services interface (declare module, the way the catalog joins
EventPayloads) and bound once at boot, createDurable({ services: { stock: (scope) => stockClientFor(scope), … } }), one factory per name,
called at each read with the read's scope (the partition, the run's scope
id, the fact's origin, the context's client); a test binds doubles through
testDurable({ services }). A step reads them off its context
(i.services.stock, a lazy getter per read; ADR-0063 Appendix M U4), so
its row lists the names it touched (declared.services), the catalog's
steps and the reaction graph show them, and a read outside any step is
answered too but said on the run (run.services_outside_step), the
double-run guard's finding; a route reads one through
instance().service(name).
import type { Secret } from "@durable-sdk/core";
/** One page of a cursor: the items and the cursor after them, null at the end. */
export type Page<T> = { items: T[]; cursor: string | null };
export type Recipient = { id: string; email: string };
export type Message = { to: string; subject: string; text: string };
export type Intake = {
patientEmail: string;
status: "open" | "prescribed" | "cancelled";
};
export type Booking = { guestEmail: string; startsAt: string };
declare module "@durable-sdk/core" {
interface Services {
stock: {
reserve(sku: string, qty: number): Promise<{ holdId: string }>;
release(holdId: string): Promise<void>;
};
payments: {
charge(orderId: string, amount: number): Promise<{ chargeId: string }>;
refund(chargeId: string): Promise<void>;
};
shipping: {
create(orderId: string, holdId: string): Promise<{ shipmentId: string }>;
cancel(shipmentId: string): Promise<void>;
};
audience: {
page(
campaignId: string,
cursor: string | null,
size: number,
): Promise<Page<Recipient>>;
};
notify: {
/** One message per idempotency key: a resend under the key is the same message. */
send(
message: Message,
options: { idempotencyKey: string },
): Promise<{ messageId: string }>;
/** The shared secret the provider signs its tracking webhook with. */
webhookSecret: Secret<string>;
};
intakes: { get(intakeId: string): Promise<Intake | null> };
pharmacy: {
order(
intakeId: string,
prescription: string,
): Promise<{ orderId: string }>;
};
bookings: { get(bookingId: string): Promise<Booking | null> };
/** The loyalty program a second module extends the order saga with (ADR-0063 Appendix M U1). */
loyalty: {
grant(orderId: string, points: number): Promise<{ points: number }>;
revoke(orderId: string): Promise<void>;
};
calendar: {
book(bookingId: string, startsAt: string): Promise<void>;
move(bookingId: string, startsAt: string): Promise<void>;
cancel(bookingId: string): Promise<void>;
/** The bookings that ended before the moment and nobody attended; null while the report is not ready. */
noShows(before: string): Promise<string[] | null>;
};
}
}The plugins. Each product as one object (definePlugin, ADR-0063
Appendix M U5): its facts, the modules that define its workflows,
register its listeners and register its hook handlers (the saga's loyalty
consumer, a module of the orders plugin), each a () => import(…) thunk
the engine awaits one at a time after the host's own manifest, under the
plugin's name. A host binds the four, createDurable({ plugins: [orders, campaigns, intakes, bookings] }), and the catalog rows (GET catalog/workflows, catalog/events) and the reaction graph say which
product each definition, listener and handler belongs to (plugin); a
fact two plugins declare, or a reverter, a log row, a service or a
console entry two plugins spell, is refused at the boot naming both. The
families a plugin brings beside these (tickTasks, retention,
reverters, remedies, logs, routes, services, observers) are
the shapes createDurable takes at the top level, which stay and are the
implicit plugin, named by createDurable({ name }).
import { definePlugin } from "@durable-sdk/core";
import {
BOOKING_EVENTS,
CAMPAIGN_EVENTS,
INTAKE_EVENTS,
ORDER_EVENTS,
} from "./catalog";
export const orders = definePlugin({
name: "orders",
events: ORDER_EVENTS,
workflows: [() => import("./order-saga")],
hooks: [() => import("./order-loyalty")],
});
export const campaigns = definePlugin({
name: "campaigns",
events: CAMPAIGN_EVENTS,
workflows: [() => import("./campaign-send")],
listeners: [() => import("./campaign-send")],
});
export const intakes = definePlugin({
name: "intakes",
events: INTAKE_EVENTS,
workflows: [() => import("./intake-approval")],
listeners: [() => import("./intake-approval")],
});
export const bookings = definePlugin({
name: "bookings",
events: BOOKING_EVENTS,
workflows: [() => import("./booking-reminders")],
listeners: [() => import("./booking-reminders")],
});1. An order saga with compensation (the storefront shape)#
Reserve the stock, charge the card, create the shipment: three steps,
each with its undo, each a provider call (effect: "provider"), so the
ledger holds every call's answer and every undo's row without a spec. The
key is the order, so a second checkout of the same order finds the first
run instead of charging twice. A charge that fails releases the stock: the
saga runs the completed steps' undos in reverse and the run lands
COMPENSATED. The saga also declares a hook, placed (ADR-0063 Appendix
M U1): a point another file extends without touching the saga, run inside
it as rows of its own.
import { as, defineWorkflow } from "@durable-sdk/core";
export const placeOrder = defineWorkflow({
name: "order.place",
key: ["orderId"],
example: { orderId: "o1", sku: "sku-1", qty: 2, amount: 4200 },
hooks: {
placed: {
input: as<{ orderId: string; shipmentId: string }>(),
output: as<{ loyaltyPoints?: number }>(),
},
},
async run(ctx) {
const { orderId, sku, qty, amount } = ctx.input;
const hold = await ctx.step(
"stock.reserve",
(i) => i.services.stock.reserve(sku, qty),
{
undo: (i, h) => i.services.stock.release(h.holdId),
effect: "provider",
},
);
const paid = await ctx.step(
"card.charge",
(i) => i.services.payments.charge(orderId, amount),
{
undo: (i, c) => i.services.payments.refund(c.chargeId),
effect: "provider",
},
);
const box = await ctx.step(
"shipment.create",
(i) => i.services.shipping.create(orderId, hold.holdId),
{
undo: (i, s) => i.services.shipping.cancel(s.shipmentId),
effect: "provider",
},
);
const extra = await ctx.hook(
"placed",
{ orderId, shipmentId: box.shipmentId },
{ id: "hook.placed" },
);
ctx.emit("order.placed", { orderId, shipmentId: box.shipmentId });
return {
holdId: hold.holdId,
chargeId: paid.chargeId,
shipmentId: box.shipmentId,
...extra,
};
},
});The hook's consumer. A second file, loaded with the saga (a host
lists it in its manifest as it lists a definer), registers one handler on
placed: a provider call with its undo, run as the row
hook:placed#loyalty inside the saga's hook:placed row, so a shipment
that fails later revokes the points with the rest, and the points join
the saga's output.
import { placeOrder } from "./order-saga";
placeOrder.hooks.placed(
"loyalty",
async ({ orderId }, i) => {
const grant = await i.services.loyalty.grant(orderId, 10);
return { loyaltyPoints: grant.points };
},
{
undo: ({ orderId }, _output, i) => i.services.loyalty.revoke(orderId),
effect: "provider",
},
);Facts. order.placed { orderId, shipmentId }, published with the
run's completion and never for a run that compensated.
Listeners. None needed for the saga itself; the product's reactions
(a confirmation, an analytics row) are on("order.placed", …).
What the engine gives it. The key (order.place:orderId=o1, one run
per order, a retry of the checkout reusing it), the step rows on the run
page with each step's input and output (card.charge with its
chargeId), the ledger rows of the four calls (provider/stock.reserve,
create, the answer as the after image, under the run's actor; a row a
person, a verifier and the undo read; the loyalty grant's under
hook:placed#loyalty) and of each undo the saga ran (a
delete row reversing the call's, reversesId naming it), the
compensation (the undos run in the reverse of completion order,
stock.reserve COMPENSATED beside the failed card.charge, the run's
compensation list naming both), the fact published only when the run
completed, the crash resume (an attempt cut off after the charge replays
the charge from its row and continues at the shipment, appending no
second row), the hook's rows (hook:placed, read, nothing of its own to
undo, and hook:placed#loyalty inside it with the grant's undo; the
catalog lists the hook with its handler and its module), and the
console's redrive for a failed run a person wants to try again.
2. A campaign send in batches with tracking webhooks (the Mailchimp shape)#
One run per campaign sends to the audience a chunk at a time through a
cursor: a chunk is a step row, the resume point after a crash and the
console's row; concurrency: 4 runs four chunks at once as one wave
under the attempt's one lease (ADR-0061 decision 1): the next chunk
starts once the previous read answered its cursor, the first failure is
held while the chunks in flight settle and then thrown, and a park,
whether the function's deadline or the provider's bucket asks for it,
waits for the wave to settle and happens once, the refused chunks
re-running from their rows on the wake; a chunk's output is a count,
never the recipients. Each message goes out under an idempotency key the
provider honours, so a resumed chunk sends nothing twice. The provider's
tracking webhook is one route whose deliveries are facts, exported as it
is (the route reads the bound instance itself), and two listeners count
them per campaign.
import { createHmac, timingSafeEqual } from "node:crypto";
import { defineWorkflow, instance, on } from "@durable-sdk/core";
import { webhookRoute } from "@durable-sdk/vercel/react-router";
export const sendCampaign = defineWorkflow({
name: "campaign.send",
key: ["campaignId"],
example: { campaignId: "c1", subject: "Hello", text: "Our news." },
async run(ctx) {
const { campaignId, subject, text } = ctx.input;
// The reader runs inside each chunk's step, so the audience read lands
// on the chunk's row with the cursor it read from.
const reader = {
next: (cursor: string | null, size: number) =>
ctx.services.audience.page(campaignId, cursor, size),
};
const sent = await ctx.batch(
"campaign.chunk",
reader,
{ size: 100, concurrency: 4 },
async (recipients, _index, i) => {
for (const r of recipients)
await i.services.notify.send(
{ to: r.email, subject, text },
{ idempotencyKey: `${campaignId}:${r.id}` },
);
return recipients.length;
},
{ irreversible: "a sent message cannot be unsent" },
);
ctx.emit("campaign.sent", { campaignId, recipients: sent.items });
return { recipients: sent.items, chunks: sent.chunks };
},
});
/** The provider's tracking event, as its webhook posts it: `type` is the provider's word, and only two of them are facts here. */
type TrackingEvent = {
type: string;
campaignId: string;
messageId: string;
};
/**
* The tracking webhook: one route, its facts. The provider signs the body
* with the shared secret; a delivery that does not verify is a 401 and no
* fact; a duplicate delivery collapses on the first row (the catalog's
* key); an event of a type the catalog does not name is a 200 and no fact
* (`{ ignored }`, logged), never a fact name the catalog lacks, which an
* emit refuses and the route does not catch. The route emits under the
* instance bound where it runs and reads the provider's secret off it
* (`instance().service("notify")`, the read outside any run), so a host's
* route file exports it as its action (`export { trackingWebhook as action }`).
*/
export const trackingWebhook = webhookRoute({
verify: async (request) => {
const body = await request.text();
const secret = instance().service("notify").webhookSecret;
const mac = createHmac("sha256", secret.reveal())
.update(body)
.digest("hex");
const given = request.headers.get("x-tracking-signature") ?? "";
const ok =
given.length === mac.length &&
timingSafeEqual(Buffer.from(given), Buffer.from(mac));
return ok
? { ok: true, context: JSON.parse(body) as TrackingEvent }
: { ok: false, status: 401 };
},
toFacts: (event) =>
event.type === "delivered" || event.type === "opened"
? [
{
name: `campaign.${event.type}`,
payload: {
campaignId: event.campaignId,
messageId: event.messageId,
},
},
]
: { ignored: `tracking event ${event.type}` },
});
/** The campaign's numbers: the app's own table, counted as the facts land. */
export const tracking = new Map<
string,
{ delivered: number; opened: number }
>();
const count = (campaignId: string, field: "delivered" | "opened") => {
const row = tracking.get(campaignId) ?? { delivered: 0, opened: 0 };
tracking.set(campaignId, { ...row, [field]: row[field] + 1 });
};
on(
"campaign.delivered",
"count-delivered",
async (e) => count(e.payload.campaignId, "delivered"),
{ describe: "Counts a delivery on the campaign's row." },
);
on(
"campaign.opened",
"count-opened",
async (e) => count(e.payload.campaignId, "opened"),
{ describe: "Counts an open on the campaign's row." },
);Facts. campaign.sent { campaignId, recipients } from the run;
campaign.delivered and campaign.opened { campaignId, messageId } from
the webhook, keyed per campaign and message, so the provider's redelivery
of an event is one row and an open counted once per message.
Listeners. count-delivered and count-opened, each a keyed run per
outbox row (listener.count-delivered:<outboxId>), so a redelivered fact
counts nothing twice; the counters are the product's table (a Map here).
What the engine gives it. One run per campaign (a second click finds
it), the chunk rows (campaign.chunk#0, #1, #2) with the cursor
before each on the row and the count after it, the resume from the last
recorded cursor after a crash (a chunk done is never re-read), the park on
a continue wait when the function's deadline nears so a million-row
audience runs to the end on a 300 s function, the route's verification
before any fact and its 200 whatever the listeners do (the route reading
the bound instance itself, so the page exports it and a test runs it
under its harness), the outbox's key collapsing the provider's retries,
and the Events page showing every delivery with the listener runs it
caused.
3. An intake with a provider's approval and a prescription follow-up (the telehealth shape)#
The intake parks until a provider decides: the run is WAITING on the
token provider, the console's Runs page lists it under Waiting with a
Signal button, and the product's own task row points the provider there
(or posts runs/:id/signal itself; a route that knows the intake and not
the run posts runs/signal with the run's own key,
{ "key": "intake.review:intakeId=i1", "token": "provider", "payload": … },
the same run.signal run; ADR-0063 Appendix M, U7); what the signal carries
is the type the body names (waitForApproval<Decision>). A prescription orders with the
pharmacy and schedules a follow-up days ahead as a delayed fact. When the
patient cancels, the follow-up is set aside by its key before its moment.
What the intake stores (the patient's answers in the run's input, the
provider's decision in the signal's payload as the step's output, the
prescription on the ledger) is PHI, and the recipe's host seals it with
the payload codec (ADR-0063 B25): createDurable({ codec }) seals every
stored input, output, memo and ledger image after the redaction policy
walked it and opens them on every read, the key ring's id beside each
row, with no line in the recipe itself; what the codec does not cover
(the error text, the log lines, the facts on the outbox and the wire) the
recipe keeps free of PHI by construction, as every recipe here does.
import { defineWorkflow, on } from "@durable-sdk/core";
import { followUpKey } from "./catalog";
/** What the provider's signal carries: the prescription, or none. */
type Decision = { prescription: string | null };
export const reviewIntake = defineWorkflow({
name: "intake.review",
key: ["intakeId"],
example: {
intakeId: "i1",
reviewBy: "2026-10-01T12:00:00.000Z",
followUpAt: "2026-10-08T09:00:00.000Z",
},
async run(ctx) {
const { intakeId, reviewBy, followUpAt } = ctx.input;
const review = await ctx.waitForApproval<Decision>({
token: "provider",
deadline: reviewBy,
});
const rx = review.fired === "signal" ? review.payload.prescription : null;
if (!rx) return { prescribed: false };
await ctx.step(
"pharmacy.order",
(i) => i.services.pharmacy.order(intakeId, rx),
{
irreversible: "an order placed with the pharmacy is theirs to cancel",
},
);
ctx.emit(
"prescription.followup.due",
{ intakeId },
{ deliverAt: new Date(followUpAt) },
);
return { prescribed: true };
},
});
/** The patient cancelled: the follow-up is set aside before its moment (a moment passed is delivered, and the listener's re-read is the guard). */
export const cancelIntake = defineWorkflow({
name: "intake.cancel",
key: ["intakeId", "requestId"],
example: { intakeId: "i1", requestId: "r1" },
async run(ctx) {
return ctx.step(
"followup.cancel",
() => ctx.cancelScheduled(followUpKey(ctx.input.intakeId)),
{
irreversible: "a cancelled fact is not re-scheduled here",
effect: "ledgered",
},
);
},
});
/** Days later: re-read the intake first (the fact is what was true at emit; a read step, so the row records the service and a resumed attempt replays it), then one message under one key. */
on(
"prescription.followup.due",
"send-followup",
async (e, ctx) => {
const intake = await ctx.step(
"intake.read",
(i) => i.services.intakes.get(e.payload.intakeId),
{ irreversible: "a read" },
);
if (intake?.status !== "prescribed") {
ctx.log.info("followup.skipped", { status: intake?.status ?? "gone" });
return;
}
const message = {
to: intake.patientEmail,
subject: "How is it going?",
text: "A week in: any side effects?",
};
await ctx.step(
"followup.send",
(i) => i.services.notify.send(message, { idempotencyKey: e.key }),
{
irreversible: "a message sent cannot be unsent",
},
);
},
{ describe: "Sends the week-in follow-up to a patient still prescribed." },
);Facts. prescription.followup.due { intakeId }, emitted with
deliverAt and keyed on the intake alone, so the cancel can spell the key
from what it has.
Listeners. send-followup (the notify send, after re-reading the
intake); the cancel is the workflow intake.cancel the patient's route
runs.
What the engine gives it. The wait row and the WAITING run that
holds no function (a provider who decides next week costs nothing
meanwhile), the deadline that fails the run for a person when nobody
decided in time, the signal as a keyed and ledgered operator action
(run.signal, the console's button, the API, the MCP), the resume as the
next attempt with the parked step's outcome replayed, the delayed fact
that is not live until its moment and the cancel as a recorded write with
the row's images on the ledger, the Events page saying "cancelled by
4. A booking with reminders and a reschedule (the Calendly shape)#
A booking holds the calendar slot and emits two reminders as delayed
facts, keyed on the booking, the start and the reminder. A reschedule
cancels the old reminders by key (a reminder already delivered answers
delivered and is left alone), moves the slot and emits new reminders
under new keys. A daily schedule sweeps no-shows: the calendar's report
lags, so the sweep polls it once an hour until it answers, and done
((r) => r !== null, a type guard to the compiler) leaves the answer the
list it proved.
import {
defineWorkflow,
on,
parseDurationMs,
pollTimedOut,
} from "@durable-sdk/core";
import { reminderKey } from "./catalog";
const REMINDERS = ["24h", "1h"] as const;
/** The reminder's moment: that long before the start. */
const before = (startsAt: string, reminder: string) =>
new Date(Date.parse(startsAt) - parseDurationMs(reminder));
export const createBooking = defineWorkflow({
name: "booking.create",
key: ["bookingId"],
example: { bookingId: "b1", startsAt: "2026-10-01T15:00:00.000Z" },
async run(ctx) {
const { bookingId, startsAt } = ctx.input;
await ctx.step(
"calendar.book",
(i) => i.services.calendar.book(bookingId, startsAt),
{
effect: "provider",
undo: (i) => i.services.calendar.cancel(bookingId),
},
);
for (const reminder of REMINDERS)
ctx.emit(
"booking.reminder.due",
{ bookingId, startsAt, reminder },
{ deliverAt: before(startsAt, reminder) },
);
return { bookingId, startsAt };
},
});
export const rescheduleBooking = defineWorkflow({
name: "booking.reschedule",
key: ["bookingId", "startsAt"],
example: {
bookingId: "b1",
from: "2026-10-01T15:00:00.000Z",
startsAt: "2026-10-02T15:00:00.000Z",
},
async run(ctx) {
const { bookingId, from, startsAt } = ctx.input;
await ctx.step(
"reminders.cancel",
async () => {
for (const r of REMINDERS)
await ctx.cancelScheduled(reminderKey(bookingId, from, r));
},
{
irreversible:
"a cancelled reminder is re-emitted below under its new key",
effect: "ledgered",
},
);
await ctx.step(
"calendar.move",
(i) => i.services.calendar.move(bookingId, startsAt),
{
effect: "provider",
undo: (i) => i.services.calendar.move(bookingId, from),
},
);
for (const reminder of REMINDERS)
ctx.emit(
"booking.reminder.due",
{ bookingId, startsAt, reminder },
{ deliverAt: before(startsAt, reminder) },
);
return { bookingId, startsAt };
},
});
/** Every day at 00:00 UTC: the no-shows before the slot's moment, polled until the calendar's report is in. */
export const sweepNoShows = defineWorkflow({
name: "booking.noshow.sweep",
key: ["before"],
schedule: { every: "1d", input: (slot) => ({ before: slot.at }) },
example: { before: "2026-10-01T00:00:00.000Z" },
async run(ctx) {
const { before } = ctx.input;
const report = await ctx.poll(
"calendar.report",
(i) => i.services.calendar.noShows(before),
{
every: "1h",
until: "12h",
done: (r) => r !== null,
irreversible: "a look at the calendar",
},
);
const noShows = pollTimedOut(report) ? [] : report;
for (const bookingId of noShows)
ctx.emit("booking.noshow", { bookingId, before });
return { before, noShows: noShows.length };
},
});
/** A reminder: re-read the booking in a read step (a reminder that outran its cancel is skipped by the start it names), then one message under the fact's key. */
on(
"booking.reminder.due",
"send-reminder",
async (e, ctx) => {
const booking = await ctx.step(
"booking.read",
(i) => i.services.bookings.get(e.payload.bookingId),
{ irreversible: "a read" },
);
if (booking?.startsAt !== e.payload.startsAt) {
ctx.log.info("reminder.skipped", {
startsAt: booking?.startsAt ?? "gone",
});
return;
}
const message = {
to: booking.guestEmail,
subject: `Your booking in ${e.payload.reminder}`,
text: `See you at ${e.payload.startsAt}.`,
};
await ctx.step(
"reminder.send",
(i) => i.services.notify.send(message, { idempotencyKey: e.key }),
{
irreversible: "a message sent cannot be unsent",
},
);
},
{ describe: "Sends the reminder for a booking still at the start it names." },
);Facts. booking.reminder.due { bookingId, startsAt, reminder } twice
per booking, delayed to their moments; booking.noshow { bookingId, before } per unattended booking the sweep found.
Listeners. send-reminder (the notify send, after re-reading the
booking); the no-show's reactions (a fee, a message) are the product's
on("booking.noshow", …).
What the engine gives it. The delayed facts that are not live until
their moment (the Events page lists them as scheduled), the cancel by key
as a recorded write with the row's images on the ledger and the Events
page saying cancelled, the key that makes a new start a new reminder
(booking.reminder.due:b1:<start>:24h), the schedule as one field on the
definition (the core's tick task computes the slot, fires schedule.due,
and the core's listener runs the sweep under system:schedule:…, one run
per slot), the poll as probe rows (calendar.report#1, #2) with the run
WAITING between them and a window that ends as a value, and the Workers
page listing the schedule's next fire and the timers due.
5. A new workflow, as durable-sdk new workflow writes it (ADR-0060 decision 19)#
The four blocks below are the generator's templates: durable-sdk new workflow <name> --key <fields> reads them off this page by the fences'
names (new-workflow.ts, new-workflow-scheduled.ts,
new-workflow-test.ts, new-workflow-listener.ts; never a second copy),
renders them by substitution (the name, its camel-case export, the key's
fields in the type, the list, the example, the destructure and the call,
the sentence, the path, the harness import and the module paths) and
writes the result once the doctor passed the would-be tree. A block that
loses one of the anchors the renderer reads is refused by the renderer
naming it, so the templates cannot drift from what this page proves:
tests/docs/recipes.test.ts compiles every block and runs the definer's
three cases in testDurable().
The definer. One step with its undo and its effect, over an effects
seam the host binds at boot (Object.assign(checkoutCompleteEffects, { apply, revert })) and a test binds as a double; until bound, every call says
what is not implemented and where. The input type is the example's; the
key is a field list, pure by construction, with the request's moment as
requestId (ADR-0060 decision 5).
import { defineWorkflow } from "@durable-sdk/core";
/**
* What `checkout.complete` changes outside the ledger, as one seam: the host
* binds its client here once at boot, a test binds a double. Until bound,
* every call says what is not implemented and where.
*/
export const checkoutCompleteEffects = {
apply: async (input: {
checkoutId: string;
}): Promise<{ receipt: string }> => {
void input;
throw new Error(
"not implemented: new-workflow.ts (checkoutCompleteEffects.apply)",
);
},
revert: async (receipt: string): Promise<void> => {
void receipt;
throw new Error(
"not implemented: new-workflow.ts (checkoutCompleteEffects.revert)",
);
},
};
export const checkoutComplete = defineWorkflow({
name: "checkout.complete",
version: 1,
describe:
"Completes a checkout once per request, undone when a later step fails.",
key: ["checkoutId", "requestId"],
example: { checkoutId: "chk_4f21", requestId: "q1" },
async run(ctx) {
const { checkoutId } = ctx.input;
const done = await ctx.step(
"checkout.complete.apply",
() => checkoutCompleteEffects.apply({ checkoutId }),
{
undo: (_, out) => checkoutCompleteEffects.revert(out.receipt),
effect: "provider",
},
);
return { receipt: done.receipt };
},
});The scheduled form (--schedule): the same shape keyed on the slot
alone, the schedule handing slot.id to the input (ADR-0050 decision 2);
the key then names no requestId, since the slot is the one other moment
a key may carry.
import { defineWorkflow } from "@durable-sdk/core";
/**
* What `checkout.sweep` changes outside the ledger, as one seam: the host
* binds its client here once at boot, a test binds a double. Until bound,
* every call says what is not implemented and where.
*/
export const checkoutSweepEffects = {
apply: async (input: { slotId: string }): Promise<{ receipt: string }> => {
void input;
throw new Error(
"not implemented: new-workflow-scheduled.ts (checkoutSweepEffects.apply)",
);
},
revert: async (receipt: string): Promise<void> => {
void receipt;
throw new Error(
"not implemented: new-workflow-scheduled.ts (checkoutSweepEffects.revert)",
);
},
};
export const checkoutSweep = defineWorkflow({
name: "checkout.sweep",
version: 1,
describe: "Sweeps the abandoned checkouts once per slot, every ten minutes.",
key: ["slotId"],
example: { slotId: "0" },
schedule: { every: "10m", input: (slot) => ({ slotId: slot.id }) },
async run(ctx) {
const { slotId } = ctx.input;
const done = await ctx.step(
"checkout.sweep.apply",
() => checkoutSweepEffects.apply({ slotId }),
{
undo: (_, out) => checkoutSweepEffects.revert(out.receipt),
effect: "provider",
},
);
return { receipt: done.receipt };
},
});The test. Three cases on the harness (the host's …TestDurable
where the tree has one, the package's otherwise), the engine's own tick
alone (tickTasks: []: the lanes and the resumer, no host task): the
same intent twice is one run; a failing step compensates what came
before it (nothing here, so the run lands FAILED with an empty
compensation record and waits for a redrive); crashed after its step and
claimed by the resumer, the run completes on attempt 2 with the step
served from attempt 1's row (a memo hit writes no replay row since
FW-091, ADR-0016 item 4 as amended, so the detail holds that one row)
and the effect applied once (ADR-0060 decision 1).
import { testDurable } from "@durable-sdk/testing";
import { afterEach, describe, expect, it } from "vitest";
import { checkoutComplete, checkoutCompleteEffects } from "./new-workflow";
const T0 = "2026-09-28T12:00:00.000Z";
const harnesses: ReturnType<typeof testDurable>[] = [];
/** A harness at T0 over the engine's own tick: the lanes and the resumer, no host task. */
function open() {
const t = testDurable({ clock: { start: T0 }, tickTasks: [] });
harnesses.push(t);
return t;
}
afterEach(async () => {
for (const t of harnesses.splice(0)) await t.dispose();
});
/** The effects as a double: `apply` answers a receipt or refuses as told, `revert` records what it was handed; every call counted. */
function bind(refuse: string | null = null) {
const calls = { apply: 0, revert: [] as string[] };
Object.assign(checkoutCompleteEffects, {
apply: async () => {
calls.apply += 1;
if (refuse !== null) throw new Error(refuse);
return { receipt: `rcpt-${calls.apply}` };
},
revert: async (receipt: string) => {
calls.revert.push(receipt);
},
});
return calls;
}
describe("checkout.complete", () => {
it("the same intent twice is one run: the second start answers the first, the effect applied once, one ledger row; another request is another run", async () => {
const calls = bind();
const t = open();
const input = { checkoutId: "chk_4f21", requestId: "q1" };
const first = await t.run(checkoutComplete, input);
expect(first).toMatchObject({
status: "completed",
output: { receipt: "rcpt-1" },
});
const again = await t.run(checkoutComplete, input);
expect(again).toMatchObject({
status: "completed",
reused: true,
runId: first.runId,
});
expect(calls.apply).toBe(1);
expect(await t.ledger()).toMatchObject([
{
runId: first.runId,
step: "checkout.complete.apply",
after: { receipt: "rcpt-1" },
},
]);
const other = await t.run(checkoutComplete, {
checkoutId: "chk_4f21",
requestId: "q2",
});
expect(other.runId).not.toBe(first.runId);
});
it("a failing step compensates what came before it (nothing here): the run lands FAILED with an empty compensation record, the revert never called, and the same intent answers the same run until a redrive", async () => {
const calls = bind("the provider said no");
const t = open();
const input = { checkoutId: "chk_4f22", requestId: "q1" };
const r = await t.run(checkoutComplete, input);
expect(r).toMatchObject({
status: "failed",
error: "the provider said no",
});
expect((await t.detail(r.runId))!).toMatchObject({
status: "FAILED",
compensation: { undone: [], irreversible: [], failed: [] },
});
expect(calls.revert).toEqual([]);
expect(await t.run(checkoutComplete, input)).toMatchObject({
status: "failed",
reused: true,
runId: r.runId,
});
expect(calls.apply).toBe(1);
});
it("crashed after its step and claimed by the resumer, the run completes on attempt 2 with the step served from attempt 1's row and no replay row of its own (FW-091): the effect applied once, one ledger row (ADR-0060 decision 1)", async () => {
const calls = bind();
const t = open();
t.crashAfterStep(1, { workflow: "checkout.complete" });
const crashed = await t.run(checkoutComplete, {
checkoutId: "chk_4f23",
requestId: "q1",
});
expect(crashed).toMatchObject({ status: "in_progress", fenced: true });
expect(t.crashed()).toMatchObject({
runId: crashed.runId,
attempt: 1,
at: "step",
seq: 1,
});
await t.advance(t.durable.leaseMs + 60_000);
const detail = (await t.detail(crashed.runId))!;
expect(detail).toMatchObject({
status: "COMPLETED",
attempts: 2,
output: { receipt: "rcpt-1" },
});
expect(detail.steps.map((s) => [s.attempt, s.name, s.status])).toEqual([
[1, "checkout.complete.apply", "COMPLETED"],
]);
expect(calls.apply).toBe(1);
expect(await t.ledger()).toHaveLength(1);
});
});The listener (--event <fact> --why "…" [--policy record|execute]):
the registration a host appends to its listener module (the generator
drops the on import there, where on is the module's own), the fact's
payload fields handed to the input by name and the fact's key as the
request id, the policy the row in ADR-0040's table says (the reason is
--why), the workflow imported lazily so no cycle closes through on.
import { on } from "@durable-sdk/core";
on(
"checkout.submitted",
"complete-on-submit",
async (e, ctx) => {
const { checkoutComplete } = await import("./new-workflow");
await checkoutComplete.execute(
{ checkoutId: e.payload.checkoutId, requestId: e.key },
{ actor: ctx.actor },
);
},
{
describe: "Starts checkout.complete once per checkout.submitted fact.",
relay: "record",
},
);What each recipe needed, and where the claim strained#
The short form: every recipe runs in testDurable() on the
verbs as landed (ctx.step with undo and effect: "provider",
ctx.batch over a cursor, webhookRoute reading the bound instance
itself, ctx.waitForApproval<S>, ctx.emit with deliverAt,
ctx.cancelScheduled, schedule, ctx.poll with a done that
narrows), and the first pass needed no engine change. Of the strains the
first pass found, five were shapes the SDK could plainly give and now
does (the provider effect, the typed signal, the narrowing poll, on() on
the root, the route without the instance by name); what remains is the
formatter's width, the catalog as one global interface, the client seam's
type parameters and a counting listener outside a step.