Use cases
Ten shapes Durable fits on one storefront platform, from a shopper's checkout and the fulfilment service to refunds, transfers, app events, subscriptions, provisioning, imports, a merchant's agent and notifications, each with its key, steps, undo and facts.
This page is ten workflows of one storefront platform as Durable shapes: a shopper's checkout, the platform's fulfilment service, a refund, a stock transfer, an event to a merchant's apps, a subscription, a new store, a catalogue import, a merchant's agent and a notification. Each one names the problem, the shape (the intent key, two to four steps with their undo or their reason, the facts) and what the ledger and limbo give you there. A shape is an excerpt of a defineWorkflow call as Writing a workflow and Steps and undo teach it; the whole contract is the generated page Workflows. The commands this page points at are durable-sdk doctor --host and durable-sdk explain <id>.
How to read a shape#
keyis a list of input fields. The same fields twice are one run; the clock never enters it, so the moment rides in the input asrequestId.ctx.step(name, body, options)is one unit of work and of memory. A step that changes the world carriesundowith itseffect, or saysirreversible: "<reason>"; a step that says neither is refused (step.undo.effect,step.undo.reason).ctx.emit(name, payload)is a fact of the catalog, written with the run's final status.- A failure after a step runs the finished steps' undos in reverse and the run lands
COMPENSATED; a failure nothing can undo landsFAILED. Both wait in limbo for a person.
1. Checkout and payment#
A shopper's cart becomes a checkout chk_4f21: the platform reserves the stock, captures $42.00 and creates the order. The browser retries on a slow answer, the tax service answers 503 once a week, and a capture that lands twice is a refund ticket and an apology. The intent is the checkout and the request, so a retried checkout is a memo hit on the first run and never charges twice.
key: ["checkoutId", "requestId"],
async run(ctx) {
const { checkoutId, requestId } = ctx.input;
const cart = await ctx.step("cart.read", () => carts.read(checkoutId), {
irreversible: "a read" });
const held = await ctx.step("stock.reserve", () => stock.reserve(cart.lines), {
undo: (_, out) => stock.release(out.reservationId), effect: "provider" });
const paid = await ctx.step("payment.capture", () => payments.capture(cart), {
undo: (_, out) => payments.refund(out.paymentId), effect: "provider" });
const order = await ctx.step("order.create", () => orders.create(cart, held, paid), {
undo: (_, out) => orders.cancel(out.orderId), effect: "ledgered" });
ctx.emit("order.placed", { orderId: order.orderId, checkoutId, requestId });
}The capture is a write the provider cannot repeat, so in the real file it is an external step under a writeKey, the intent on the row before the call: a redrive after a lost answer finds pay_7f3a instead of charging again. When order.create throws (the tax service answered 503), the saga refunds the capture and releases the reservation in that order, each undo its own ledger row (payment.capture.undo: captured to refunded; stock.reserve.undo: 2 to 3), the run lands COMPENSATED, and a refund the provider refuses stops the chain by name and the run waits FAILED with pay_7f3a on its row for a person.
2. Fulfilment#
An order placed is handed to the platform's fulfilment service: it buys a carrier label, records the fulfilment on the order and tells the shopper. Each write goes somewhere else, any of them can fail or answer late, and a function that dies between the label and the fulfilment is the one that buys two labels.
key: ["orderId", "requestId"],
async run(ctx) {
const { orderId, requestId } = ctx.input;
const label = await ctx.step("label.buy", () => carrier.buy(orderId), {
undo: (_, out) => carrier.void(out.labelId), effect: "provider" });
const done = await ctx.step("fulfilment.create",
() => fulfilments.create(orderId, label.tracking),
{ undo: (_, out) => fulfilments.cancel(out.fulfilmentId), effect: "ledgered" });
await ctx.step("customer.notify", () => mail.shipped(orderId, label.tracking), {
irreversible: "the mail left" });
ctx.emit("order.fulfilled", { orderId, requestId, fulfilmentId: done.fulfilmentId });
}The ledger holds lb_2c9d with the image the carrier answered and the fulfilment with its id, so a person reads what shipped and what was voided without opening the carrier's dashboard. A fulfilment the order refuses (it was cancelled meanwhile) voids the label and the run lands COMPENSATED; a label the carrier will not void stops there, the run waits FAILED with lb_2c9d on its row, and no second label is bought meanwhile.
3. Refunds#
A merchant refunds $42.00 of ord_8841 from the order page. The button is pressed twice, the provider's answer is lost once a week, and a refund issued twice is money the merchant chases for a month.
key: ["orderId", "refundId"],
async run(ctx) {
const { orderId, refundId, amount } = ctx.input;
const issued = await ctx.step("refund.issue",
() => payments.refund(orderId, amount, refundId),
{ irreversible: "money moved; a reversal is its own refund" });
await ctx.step("order.mark_refunded",
() => orders.markRefunded(orderId, issued.providerRefundId),
{ undo: () => orders.unmark(orderId), effect: "ledgered" });
ctx.emit("order.refunded", { orderId, refundId, amount });
return { providerRefundId: issued.providerRefundId };
}The issue is an external step under a writeKey with refundId as the provider's idempotency key, so a redrive after a lost answer finds the refund instead of issuing another; the row keeps the provider's refund id and the amount, never the card. A mark the order refuses leaves the money moved and the run FAILED with the refund on its row: a person reads it and redrives the mark, and nothing issues a second refund.
4. Inventory transfers#
A merchant moves stock from one location to another. A move written twice doubles the units at the destination; a transfer record lost between two writes is stock nobody can find.
key: ["transferId", "requestId"],
async run(ctx) {
const { transferId, sku, qty, from, to } = ctx.input;
const moved = await ctx.step("stock.move", () => stock.adjust(sku, from, to, qty), {
undo: (_, out) => stock.adjust(sku, to, from, out.qty), effect: "provider" });
await ctx.step("transfer.record", () => transfers.record(transferId, moved.adjustmentId), {
undo: () => transfers.remove(transferId), effect: "ledgered" });
ctx.emit("stock.moved", { transferId, sku, qty });
}The stock moves as one adjustment whose undo is the reverse adjustment, so the count is never asked twice and a record the store refuses puts the units back where they came from, each on its own ledger row with the level it found and left (3 to 2, 2 to 3). A reverse adjustment the location refuses (the units sold meanwhile) stops the chain, the run waits FAILED with the transfer id on its row, and the person decides with both images in front of them.
5. App event delivery#
A merchant installs three apps and each wants order.placed. A handler that posts to all three inline is partly done when the function dies, and the retry posts to the first again.
// src/listeners.ts: one delivery per installed app, each its own keyed run
on("order.placed", "deliver-to-apps", async (e, ctx) => {
const { deliver } = await import("./workflows/app-event-deliver");
for (const app of await apps.subscribed("order.placed"))
await deliver.execute(
{ deliveryId: `${e.key}:${app.id}`, appId: app.id, fact: e.payload },
{ actor: ctx.actor },
);
});
// src/workflows/app-event-deliver.ts
key: ["deliveryId"],
async run(ctx) {
const posted = await ctx.step(postToApp, ctx.input);
return { status: posted.status, responseId: posted.responseId };
}postToApp is an external step under a writeKey, irreversible: "the app received it": the intent lands on the row before the call, so a replayed delivery is the one run under its id and a redrive after a lost answer reads the app's 2xx and its response id off the row instead of posting again. An app that answers 500 lands its run FAILED with the status on its row and parks nothing else: the other apps' runs go on, and a person redrives the one delivery when the app is back. Events and listeners has the listener and the catalog in full.
6. Subscriptions#
A subscription renews on the first of the month. A cron that fires twice on a redeploy charges twice; one that missed a tick during an outage charges none. The period is the key: one run per subscription and month, whoever fires it and however often.
key: ["subscriptionId", "period"],
example: { subscriptionId: "sub_19", period: "2026-11" },
async run(ctx) {
const { subscriptionId, period } = ctx.input;
const sub = await ctx.step("subscription.read", () => subs.read(subscriptionId), {
irreversible: "a read" });
const paid = await ctx.step("payment.capture", () => payments.capture(sub.card, sub.amount), {
undo: (_, out) => payments.refund(out.paymentId), effect: "provider" });
await ctx.step("period.extend", () => subs.extend(subscriptionId, period), {
undo: () => subs.revert(subscriptionId, period), effect: "ledgered" });
ctx.emit("subscription.renewed", { subscriptionId, period, paymentId: paid.paymentId });
}The monthly tick is a schedule (schedule: { cron: "0 6 1 * *", input: (slot) => ({ period: slot.at.slice(0, 7) }) } on the workflow that starts one subscription.renew per due subscription), so a redeploy that fires it twice is a memo hit and catchUp: 1 fires one missed slot after an outage; the ledger shows every period with its payment id. An extension the store refuses refunds the capture and the run lands COMPENSATED; a card that declines lands it FAILED with the period on its row, so a person retries the one month instead of the whole list. Time and waits has the schedule.
7. Store provisioning#
A merchant signs up and the platform makes their store st_41: a domain, a published theme, a search index. Three services, three answers, and a half-made store when the third call fails is the one a person cleans up by hand on a Friday.
key: ["storeId", "requestId"],
async run(ctx) {
const { storeId, handle } = ctx.input;
const host = await ctx.step("domain.attach", () => domains.attach(storeId, handle), {
undo: (_, out) => domains.detach(out.hostId), effect: "provider" });
const theme = await ctx.step("theme.publish", () => themes.publish(storeId), {
undo: (_, out) => themes.unpublish(out.themeId), effect: "provider" });
await ctx.step("search.index", () => search.index(storeId), {
undo: (_, out) => search.drop(out.indexId), effect: "provider" });
ctx.emit("store.ready", { storeId, host: host.name, themeId: theme.themeId });
}Every step returns an id and never a credential: the ledger keeps the store's host, theme and index ids, so a redaction never makes a row unreplayable. An index the search service refuses unpublishes the theme and detaches the domain in reverse and the run lands COMPENSATED; a detach the registry rejects (the host already serves traffic) stops there, the run waits FAILED naming the step, and the person decides with the images in front of them.
8. Catalogue import#
A merchant uploads a catalogue and ten thousand products need their price and their stock written. The script runs for an hour, the connection drops at row 4 120, and nobody knows which products it touched, or whether a product the merchant edited during the hour was overwritten with the upload's value.
key: ["importId", "requestId"],
async run(ctx) {
return ctx.batch(
"catalogue.import",
{ next: (cursor, size) => upload.page(ctx.input.importId, cursor, size) },
{ size: 200, ledger: "chunk" },
async (rows, _index, i) => {
for (const row of rows) await putProduct(row, i);
return { rows: rows.length };
},
{ irreversible: "a catalogue corrected forward", effect: "external" },
);
}putProduct is a recordedWrite under writeKey("product.put", row.sku): it reads the product, keeps the image it found (price, version) and lands as a compare-and-set on it, so a product the merchant edited meanwhile is a StaleWrite for the next page and never an overwrite, and a chunk is one ledger transaction. A crash at row 4 120 leaves the chunk's intents on its row; the redrive adopts every write that landed, reconciles the ones whose answer was lost and goes on from the cursor, so the hour is never run twice and nothing sits in memory. Time and waits has the batch.
9. A merchant's agent#
A merchant's AI agent plans three tool calls: create a discount, update a price, publish the post that announces them. The third fails, the agent is asked to "clean up", and it calls the tools again from a transcript nobody can audit. Make each tool call a step: the undo is declared with the call, the ledger is the transcript, and a refusal is a value the agent reads instead of a stack trace it guesses at.
key: ["taskId", "planId"],
async run(ctx) {
const { taskId, plan } = ctx.input;
const code = await ctx.step("discount.create", () => discounts.create(plan.discount), {
undo: (_, out) => discounts.remove(out.discountId), effect: "provider" });
await ctx.step("price.update", () => prices.set(plan.sku, plan.cents), {
undo: (_, out) => prices.set(plan.sku, out.previousCents), effect: "provider" });
await ctx.step("post.publish", () => posts.publish(plan.post, code.code), {
undo: (_, out) => posts.remove(out.postId), effect: "provider" });
ctx.emit("agent.task.done", { taskId, planId: plan.id, discountId: code.discountId });
}The ledger row of each call keeps the image the tool answered and the undo row keeps what the compensation restored (the price's before image, the discount deleted), so a person audits what the agent did and what was taken back from the console, never from the model's own telling of it. An undo the tool refuses (the discount was used by a shopper meanwhile) stops the chain and the run waits FAILED with the step named; execute hands the agent { status: "failed", error, runId } as a value, and durable-sdk explain <runId> prints the remedy. MCP and agents is the agent's side of the operator API.
10. Notifications#
An order confirmation, a password reset, a shipping update: one message per intent, and never two because a queue redelivered or a function retried. The provider's own message id is the proof it was sent.
key: ["notificationId"],
async run(ctx) {
const { notificationId, template, recipientId } = ctx.input;
const sent = await ctx.step("message.send",
() => notify.send(template, recipientId, notificationId),
{ irreversible: "a delivered message is not recalled" });
ctx.emit("notification.sent", { notificationId, messageId: sent.messageId });
return { messageId: sent.messageId };
}A resend of the same intent is the same run and answers { reused: true } with the first message id, so the dedupe is the key and not a table you maintain; the send is an external step in the real file, with notificationId as the provider's idempotency key, so a lost answer is found on the redrive and never sent twice. The ledger row carries the provider's message id and the template, never the message or the address; a send the provider refuses waits in limbo with the refusal on its row, and a person redrives it once the provider is back.
Does yours fit?#
- Is there an intent you can key? A list of input fields that names the one run, with the moment in the input and never the clock.
- Does each write have an undo or a reason? A step either takes itself back or says in words why it cannot.
- Is there a person for limbo? A failed run is never retried by code; someone reads the row and redrives, dismisses or undoes it.
Three yeses and the workflow is one file under src/workflows/: Writing a workflow is the next page, and durable-sdk doctor --host holds it to the rules from the first edit.