Design paradigms
The eleven rules the engine holds at its doors, each with the failure it removes and a six-line example.
A Durable workflow is written under eleven rules. None is a convention: each is held by a door the engine refuses at, a guard the doctor runs over the tree, a schema a row is judged by, or, for the eleventh, the shape of the engine's own reads. This page states each rule in one sentence, names the night it prevents, shows the lines the door admits, and names the refusal or the rule that holds it. The commands it uses are durable-sdk explain <id> and durable-sdk doctor --host. Concepts has the model; Writing a workflow and Steps and undo have the forms in full.
1. Intent-derived keys, clock-free#
The rule. A run's key is a function of its input and nothing else; the moment a request happened rides in the input as requestId, so the same intent twice is one run.
The failure it removes. A key that reads the clock names a new intent on every call. A resume after a crash, a redrive from limbo and a retry from a caller each start a second run beside the first, and the card is charged twice at 03:10 with nothing in the rows to say which run is the real one.
export const checkoutComplete = defineWorkflow({
name: "checkout.complete",
version: 1,
describe: "Completes a checkout once per request.",
key: ["checkoutId", "requestId"],
example: { checkoutId: "chk_4f21", requestId: "q7c1" },
async run(ctx) {
const held = await ctx.step(
"stock.reserve",
() => stock.reserve(ctx.input.checkoutId),
{
undo: (_, out) => stock.release(out.reservationId),
effect: "provider",
},
);
return { reservationId: held.reservationId };
},
});A second execute under the same checkoutId and requestId answers the first run's result. A second under the same key with another input is refused as a value, execute.key_reused, before anything is written.
What holds it. workflow.key.reads_clock at defineWorkflow (a key that reads Date.now(), Math.random() or randomUUID()); workflow.key.secret_part (a key part the policy redacts); catalog.key.reads_clock for a fact's key; the doctor's workflow-identity/key-reads-no-clock and definitions/example-does-not-key.
2. Read before write, compare-and-set#
The rule. A write names the image it expects to find; when the world moved since the read, the write is refused by name and nothing is overwritten.
The failure it removes. An attempt dies between its write and its row. The next attempt runs the body again, writes again, and the second write lands over what another actor changed in the meantime. The ledger then holds a before image that was never true, and the compensation restores a state nobody wants.
const capturePayment = defineExternalStep<
ExternalStepInput & { paymentId: string },
{ status: string }
>({
name: "payment.capture",
resource: (i) => ({
shop: i.shop,
resourceType: "payment",
resourceId: i.paymentId,
operation: "update",
}),
read: (i) => payments.read(i.paymentId, i.stop),
compare: (current, desired) => current.status === desired?.status,
desired: () => ({ status: "captured" }),
image: (s) => ({ status: s.status }),
write: (i) => payments.capture(i.paymentId, i.stop),
undo: (i) => payments.refund(i.paymentId, i.stop),
});
// in a run body:
await ctx.step(capturePayment, { paymentId: ctx.input.paymentId });read the world, compare it with desired, write only when they differ, image what the ledger keeps. The intent is persisted on the step row before the call, so a redrive after a lost answer finds what landed instead of writing again. A plain step keeps the same discipline by hand: judge first, as a value, then write once, and read the answer from the write's images.
What holds it. write.compared.undefined at compareAndSet (a compared column valued undefined would widen the fence to the id alone); step.effect.external_without_intent (an external effect that persisted no intent); step.write_key.shared (two writes of a step under one key); step.retry.effect (a retry on a write); the error code StaleWrite, whose remedy is the run's drift view, never a redrive that overwrites.
3. Undo, or say why not#
The rule. Every step that changes the world declares its compensation with the effect it had, or says in words why it cannot be undone; a blank in either place is refused before the body runs.
The failure it removes. A later step fails, the saga rolls back, the run reads COMPENSATED, and the charge still stands because its step's undo was an empty function that passed every test which ran once. The person on call trusts the word and does not look.
async run(ctx) {
const held = await ctx.step(
"stock.reserve",
(i) => stock.reserve(ctx.input.checkoutId, i.stop),
{ undo: (_, out) => stock.release(out.reservationId), effect: "provider" },
);
const sent = await ctx.step("customer.notify", () => mail.send(held.reservationId), {
irreversible: "the mail left",
});
return { reservationId: held.reservationId, messageId: sent.messageId };
},When customer.notify throws, the saga runs stock.release and writes a stock.reserve.undo row with the image it found and the image it restored. When a later step fails after customer.notify, the run's compensation lists the email as irreversible with its reason, so COMPENSATED means every compensable step was undone and the error names what was not.
What holds it. step.undo.declares (neither undo nor reason), step.undo.blank (an undo with no body), step.undo.reason (a reason with no words), step.undo.effect (an undo with no effect), step.undo.both (both at once), step.inline.declares; each thrown at ctx.step, defineStep and defineExternalStep, in every mode.
4. Refusals as values#
The rule. A door answers a code, a sentence and a remedy; nothing throws across a boundary for an outcome, and every sentence is a row durable-sdk explain answers offline.
The failure it removes. A route catches an exception whose message was composed at the throw site, logs it, and answers 500. The person reading the log at midnight has a sentence with no id, no trap and no remedy, and a different sentence from the one the same cause threw last week.
export async function completeCheckout(
checkoutId: string,
actor: `user:${string}`,
) {
const result = await checkoutComplete.execute(
{ checkoutId },
{ actor, requestId: randomUUID() },
);
if (result.status === "completed") return result.output;
return describeResult(result);
}execute answers completed, in_progress or failed as a value. A definition the door cannot admit throws a TypeError whose sentence is a registry row with an id, and the same id answers from the CLI:
durable-sdk explain step.undo.effect
durable-sdk explain execute.key_reused --jsonWhat holds it. The refusal registry: every row an id, a door, a sentence, a trap, a remedy and a record; execute.key_reused and run.hold.in_limbo are thrown as values. The doctor's refusals/registry-is-sentences, refusals/rows-are-thrown and refusals/sites-read-rows hold the registry to the sites. Refusals lists every row.
5. Bounded outputs, never a secret#
The rule. A step's output is its stored form, small and plain, and holds nothing the redaction policy blanks; a one-time value goes back through ctx.reply and is never stored.
The failure it removes. A step returns the provider's whole answer, a token among its fields. The row stores [redacted] where the token was, so after the next crash the memo cannot serve the step, the body runs again, and the provider mints a second token while the first is still live in someone's hand.
async run(ctx) {
const issued = await ctx.step(
"token.issue",
async () => {
const t = await tokens.issue(ctx.input.accountId);
ctx.reply(t.secret);
return { tokenId: t.id };
},
{ undo: (_, out) => tokens.revoke(out.tokenId), effect: "provider" },
);
return { tokenId: issued.tokenId };
},The secret reaches the caller of this completion alone, on ExecutionResult.reply, and a later trigger of the same intent gets no reply. The row keeps the id. The input is held to the same walk: a client, a Date, a Map, a Secret or a function at any depth is refused at execute before a row exists, and a credential rides on execute options as secrets.
What holds it. step.output.redacted and step.output.truncated at ctx.step (refused on the attempt that ran the body, the saga compensating); input.unstorable at execute; workflow.key.secret_part; the redaction policy, which blanks by name and by shape before anything is stored. Data in the ledger has the policy.
6. Everything on the ledger#
The rule. Every write a step makes leaves a row with the image it found and the image it left, chained by hash per scope, append-only by interface, by retention and by a database trigger; the ledger is the audit.
The failure it removes. An auditor asks what changed on a resource in March and who changed it. The answer is a log retention window that ended in April, a table that holds the current row alone, and a guess.
async run(ctx) {
const applied = await ctx.step(
"price.update",
(i) => prices.set(ctx.input.sku, ctx.input.cents, i.stop),
{
undo: (_, out) => prices.set(ctx.input.sku, out.previousCents),
effect: "provider",
},
);
return { previousCents: applied.previousCents };
},The step says effect: "provider", so the recorder writes the call's row to the ledger itself, provider/price.update, and a row reversing it when the saga ran the undo. A ledgered step appends its own row inside the body; an external step's row is its before and after image. Every row carries the run, the step, the actor, the attempt and hash = sha256(prevHash + content).
durable-sdk ledger export --out ledger.json --scope tenant:42
durable-sdk ledger verify --file ledger.jsonverify recomputes every chain and names the first broken link: an edited image, a re-dated row, a deleted tail.
What holds it. The trigger ledger_append_only; no update or delete method on the interface; no retention rule may name the ledger; step.effect.ledgered_without_row (a ledgered step that changed something and left no row) and step.effect.read_appended_row (a read that appended one) at ctx.step. Guarantees states what the ledger proves.
7. Facts through a catalog#
The rule. Every fact a run emits is a row of the catalog, with a schema, a sentence and a clock-free key; a fact is written with the run's final status, and every listener is registered in one module.
The failure it removes. A webhook body short of a field lands as a row no listener can trust. A fact emitted inside a step is queued on the attempt that ran the body and lost on the resume that finished the run from its rows, so the listener that should have shipped the order never hears of it.
export const EVENTS = defineEvents({
"order.placed": {
key: (p) => `order.placed:${p.checkoutId}:${p.requestId}`,
parts: ["checkoutId", "requestId"],
describe: "An order was placed; one fact per checkout request.",
schema: z.object({
orderId: z.string().min(1),
checkoutId: z.string().min(1),
requestId: z.string().min(1),
}),
},
});
// after the step returns, in the run body:
ctx.emit("order.placed", { orderId, checkoutId, requestId });The key is inserted-if-absent, so a resend collapses. A listener (on("order.placed", "deliver-to-apps", body)) is itself a keyed run, so a redelivery is harmless.
What holds it. catalog.schema.missing, catalog.key.reads_clock and catalog.unknown at defineEvents and ctx.emit; emit.inside_step (a fact emitted inside a step); listener.key.reads_clock at on; the doctor's definitions/fact-schema-missing, definitions/fact-describe-missing and authoring/emit-inside-step, and its rule that on( lives in the one listeners module. Events and listeners has the forms.
8. Limbo is a person's#
The rule. A run that failed waits in limbo with its error, its rows and the remedy; nothing retries in the dark, and a redrive is a person's next attempt that reads the world before it writes.
The failure it removes. A retry loop re-runs a failed compensation every thirty seconds through the night. Each pass writes the stale image over what the day shift corrected, and by morning the loop has undone a week of fixes with nobody told.
async run(ctx) {
const sent = await ctx.step(
"invoice.send",
(i) => mail.send(ctx.input.invoiceId, i.stop),
{ irreversible: "a sent email cannot be unsent" },
);
if (!sent.accepted)
ctx.fail(`the mail provider refused invoice ${ctx.input.invoiceId}`);
return { messageId: sent.messageId };
},ctx.fail(reason) marks the run FAILED with the body's output kept and nothing compensated: the body decided, and the reason is what the console shows. A step that throws lands the run FAILED or COMPENSATED the same way. From there a person redrives, dismisses with a reason or undoes:
durable-sdk runs limbo
durable-sdk explain <runId> --api <url>
durable-sdk runs redrive <runId>A redrive replays the rows that landed and re-invokes what did not; an external write pending on a step row is reconciled from the world first. The one exception to "a person moves it" is the engine's own redrive of a cause it classifies transient, declared once in the configuration as autoRedrive with its codes, its delays and a bound of at most ten.
What holds it. run.hold.in_limbo (a hold on a run in limbo is refused as a value: redrive or dismiss it); run.redrive.continued (a redrive of a continued run is sent to the chain's newest); the error code marked for a ctx.fail; durable.auto_redrive.shape, .codes, .delays and .max at createDurable. Errors has every code with its remedy.
9. The doctor over the tree#
The rule. Every rule the engine keeps is a guard the doctor runs over the tree offline, before a deploy; a failed rule prints as one line with its fix.
The failure it removes. A key that reads the clock, a step without its undo and a listener in the wrong file each ship on a Friday because no test exercised the path. The first crash on Monday is the first time anyone learns the rule.
durable-sdk doctor --host
durable-sdk doctor --host --explain workflow-identity/key-reads-no-clock
durable-sdk doctor --host --jsonA green run prints the rule count and exits 0. A red run prints one line per finding: the severity, the rule id, the file and line, the sentence, the fix after the arrow, the record. --explain says the law, the hazard (race, doubled write, leaked secret, lost fence, lost intent), what the rule costs you and the fix. The core pack carries fifty-one rules today, and the engine's own tree is held by several hundred of the same shape.
// Refused by definitions/strict-boot before any run exists:
export const digest = defineWorkflow({
name: "report.digest",
version: 1,
key: ["day"],
async run(ctx) {
return ctx.step("report.digest.read", () => reports.read(ctx.input.day), {
irreversible: "a read",
});
},
});The definition above has no describe and no example: the doctor names the module, the field and the remedy, and the boot under definitions: "strict" refuses it with the same words.
What holds it. durable-sdk doctor --host, the template's CI before durable-sdk test --pr, and the hosted deploy's durable-sdk platform check against the staged deployment before it promotes; definitions/strict-boot, definitions/describe-missing, definitions/example-missing, authoring/no-catch-around-step, authoring/promise-all-over-steps among the rules. The doctor reads a finding; Rules lists the pack.
10. Legible to agents#
The rule. Everything a person can read, an agent can read as data: every docs page as Markdown, the platform API as an OpenAPI document, every sentence through explain, and an AGENTS.md at the root of every app.
The failure it removes. An agent asked to fix a failed run scrapes HTML for the docs, guesses at an error sentence it cannot look up, and edits around a door it cannot see. The fix it ships is the next finding.
curl -s https://durablesdk.com/docs/guide/steps-and-undo.md
curl -s https://durablesdk.com/openapi.json
durable-sdk explain step.undo.effect --json
durable-sdk doctor --host --jsonEvery page is served at <url>.md and in /llms-full.txt, the links absolute, so an agent that fetched one page follows the next without guessing. Every CLI verb takes --json and answers a refusal as { "error": { "code", "message", "remedy", "docs" } }. durable-sdk init writes an AGENTS.md that says what the app is, its file map, the commands and the rules a workflow must keep, with CLAUDE.md as @AGENTS.md.
What holds it. The docs' own tests: every page has its Markdown twin, every internal link names a page, no page names a provider. MCP and agents lists every surface and what is coming.
11. One record, derived views#
The rule. The engine's rows are the one record: the runs, the steps, the ledger, the facts and the outbox. Everything else is derived from them and the catalogues when it is asked for and never stored a second time: a run's result and its resume point on a redrive, the console's every view (the overview, the pressure, the caps, the limits, the issues, the facts a run emitted and the runs they started), the verify read's verdict, /llms.txt and the OpenAPI document. What the world holds (a provider's answer, a store's stock) is read inside a step and kept on the step's row, the image a write found on the ledger, never mirrored into a table the workflow trusts over the world; a derived copy your app does keep is stamped with its moment, rebuilt from its source and never written back.
The failure it removes. Two truths that drift. A status column says shipped while the label was never bought, and the morning ships by the column. A mirror of a provider's stock is what the body reads while the provider's own count moved an hour ago, so the write lands on a number that was never true. A cache nobody can rebuild is backed up, restored and trusted, and no row in it can say when it was last the truth.
async run(ctx) {
const level = await ctx.step(
"stock.read",
(i) => stock.level(ctx.input.sku, i.stop),
{ irreversible: "a read" },
);
const copy = await ctx.step(
"stock.snapshot",
(i) => snapshots.put({ ...level, asOf: new Date() }, i.stop),
{ irreversible: "a derived copy, rebuilt by the next tick" },
);
return { onHand: level.onHand, asOf: copy.asOf };
},stock.read leaves its row and no image: the row is what the world said at that moment, and a redrive replays it instead of asking again. stock.snapshot writes a copy for a page to read, stamped with the moment it was taken (asOf, an ISO string in the stored form); it has no undo because the next tick of the schedule rebuilds it from the world, and nothing decides a write from it. The engine keeps its own derived copies the same way: the console's day summaries and the last full walk of the ledger are rows stamped computedAt, served stale and recomputed after the response, and a broken ledger is never served from a copy. The views are reads: durable-sdk explain <runId> --api <url> says a run from its rows, durable-sdk limits --api <url> the bounds in force, durable-sdk ledger verify --file <export> the chain's verdict over an export with no database at all. The till tells the same rule as a cash register: a tape, not a number, and the total summed from it.
What holds it. step.effect.read_appended_row at ctx.step (a read that appended a ledger row: a read's answer is its row, never an image); step.replay.input_changed (a step whose input is not what the rows hold is refused before any re-invoke: the resume point is the rows', never the body's); the trigger ledger_append_only and the operator API's verify read for the record; the intent key for a run's identity. The views are held by the read model's shape, not a door: every console read is a query over the rows and the catalogues, nothing in the engine writes a view down, and the doctor carries no rule for a mirror, since the engine keeps none.
Where each rule is held#
| Paradigm | The door | The guard | The schema or the table |
|---|---|---|---|
| 1. Intent-derived keys, clock-free | workflow.key.reads_clock, execute.key_reused |
workflow-identity/key-reads-no-clock |
the key column, one run per key while it lives |
| 2. Read before write | write.compared.undefined, step.effect.external_without_intent |
none needed: the write's phases hold in every mode | the step row's pending intent; the error code StaleWrite |
| 3. Undo, or say why not | step.undo.declares, step.undo.blank, step.undo.reason |
none needed: the door holds in every mode | the run's compensation list |
| 4. Refusals as values | every row of the registry; execute answers a value |
refusals/registry-is-sentences, refusals/rows-are-thrown |
the registry: id, door, sentence, trap, remedy, record |
| 5. Bounded outputs, never a secret | step.output.redacted, step.output.truncated, input.unstorable |
definitions/example-unstorable |
the redaction policy; the row's cap |
| 6. Everything on the ledger | step.effect.ledgered_without_row, step.effect.read_appended_row |
none needed: the trigger holds | ledger_append_only; hash = sha256(prevHash + content) |
| 7. Facts through a catalog | catalog.schema.missing, catalog.key.reads_clock, emit.inside_step |
definitions/fact-schema-missing, authoring/emit-inside-step |
the fact's zod schema; insert-if-absent under the key |
| 8. Limbo is a person's | run.hold.in_limbo, run.redrive.continued |
none needed: a failed run is never retried by code | the run's status FAILED or COMPENSATED; autoRedrive bounded |
| 9. The doctor over the tree | definitions: "strict" at the boot |
every rule of the pack | the finding line: severity, id, file, sentence, fix, record |
| 10. Legible to agents | --json on every verb |
the docs' links and vocabulary tests | /llms.txt, the .md twins, /openapi.json, AGENTS.md |
| 11. One record, derived views | step.effect.read_appended_row, step.replay.input_changed |
none needed: held by the read model's shape, not a door | the rows of the durable schema; a kept copy's computedAt |
durable-sdk explain <id> answers every id in the first column; durable-sdk doctor --host --explain <rule id> every id in the second.