Writing a workflow

One file under src/workflows, a name, a field-list key that never reads the clock, a describe and an example, and execute with a requestId.

Open in CursorView as Markdown

This page is the file you write and the four rules it keeps. The commands it teaches are durable-sdk doctor --host (run it after every edit) and pnpm test (the template's vitest run).

A workflow is one file under src/workflows/. It imports from one place, names its intent as a list of fields, carries its own example and writes its steps inline. Everything the engine guarantees, one run per intent, replay after a crash, compensation, the ledger, the facts, applies to it unchanged.

The file#

The shape durable-sdk new workflow checkout.complete --key checkoutId,requestId writes, as a file at src/workflows/checkout-complete.ts, its placeholder step named for the first thing a checkout does: one step with its undo and its effect, over an effects seam the app binds once at boot and a test binds as a double. Steps and undo adds the capture and the order after it.

import { defineWorkflow } from "@durable-sdk/core";

/**
 * What `checkout.complete` changes outside the ledger, as one seam: the
 * app binds its stock client here once at boot, a test binds a double.
 * Until bound, every call says what is not implemented and where.
 */
export const checkoutCompleteEffects = {
  reserve: async (input: {
    checkoutId: string;
  }): Promise<{ reservationId: string }> => {
    void input;
    throw new Error(
      "not implemented: checkout-complete.ts (checkoutCompleteEffects.reserve)",
    );
  },
  release: async (reservationId: string): Promise<void> => {
    void reservationId;
    throw new Error(
      "not implemented: checkout-complete.ts (checkoutCompleteEffects.release)",
    );
  },
};

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: "q7c1" },
  async run(ctx) {
    const { checkoutId } = ctx.input;
    const held = await ctx.step(
      "stock.reserve",
      () => checkoutCompleteEffects.reserve({ checkoutId }),
      {
        undo: (_, out) => checkoutCompleteEffects.release(out.reservationId),
        effect: "provider",
      },
    );
    return { reservationId: held.reservationId };
  },
});

The input type is inferred from example, the output from run. The template's durable.config.ts names one workflows loader that imports every file under src/workflows/ one at a time; add your file's import there beside hello's (one await import per file, never a Promise.all: the loader is the manifest, and the doctor says when a file is missing from it).

The name#

name is <domain>.<verb>: segments joined by dots, each opening with a lower-case letter and going on with letters, digits and underscores. "Checkout Complete" and "checkout.Complete" are refused at definition with the grammar in the sentence. The prefixes listener., run., runs., event., schedule., undo., retention., relay. and emit. (the emit door's: emitMany names its run under it) are the engine's. A name is defined once per process; a second defineWorkflow under it throws naming both modules. A step name is [a-zA-Z0-9._-]+; # and : are the engine's.

The key never reads the clock#

key: ["checkoutId", "requestId"] becomes the function (i) => "checkout.complete:checkoutId=…:requestId=…", each part spelled over the input's stored form: a string escaped, a number as its decimal, a missing value as ~, an object as its content hash. Two different inputs never spell one key. A part the redaction policy would blank (a field named token, pin, a Secret) is refused before any run exists, so a secret never names an intent.

The field list reads fields and nothing else, so it cannot read the clock. The function form (key: (i) => …) stays for a key that needs more (an upper-cased code, a hash of two fields), and the boot refuses one whose source reads Date.now(), Math.random() or randomUUID(): put the moment in the input as requestId. A scheduled workflow keys on the slot instead (Time and waits).

Why requestId is in the key: without it, the same checkoutId twice is one run for a month. With it, every request is its own run, and a retry of one request (the same requestId) is a memo hit. Leave it out only when the intent is the thing itself: a delivery to an installed app happens once, so app.event.deliver keys on deliveryId alone.

describe and example#

describe is one sentence, the intent in words, shown beside the name in the console and in GET catalog/workflows. example is an input the workflow accepts: what the identity check keys, stores and re-keys as a run's input would. Both are required under the template's definitions: "strict" boot: a definition without one is refused at defineWorkflow, naming the module, the field and the remedy. Write example: () => Input as a thunk when the value must be fresh at each read.

The input is storable by type: a field typed with a client, a function, a Secret, a Date, a Map, a Set, a bigint or bytes, at any depth, is a compile error naming the field and the remedy. Put a moment in the input as its ISO string, a credential on execute options, a computed value as data.

execute and requestId#

A route calls the definition, never the engine's internals:

import { randomUUID } from "node:crypto";

import { describeResult } from "@durable-sdk/core";

import { checkoutComplete } from "./workflows/checkout-complete";

export async function completeCheckout(
  checkoutId: string,
  actor: `user:${string}`,
) {
  const result = await checkoutComplete.execute(
    { checkoutId },
    { actor, requestId: randomUUID() },
  );
  if (result.status !== "completed") return describeResult(result);
  return result.output;
}

execute(input, { actor, requestId }) appends requestId to an input without one before keying and storing; the input's own is never overwritten. execute answers a value, never throws for an outcome: { status: "completed", output, runId, reused? }, { status: "in_progress" } when another caller holds the run, { status: "failed", error, runId } when it landed in limbo. describeResult(result) has the words for a log line or an answer. executeOrThrow is for a route that must not go on without the output: it returns the completed run's output and throws RunFailed for every other outcome, in_progress included.

The door judges the live input once, before any row: an input carrying a client, a secret, a function or a Date answers RunNotStarted naming the path and the remedy, and nothing is written. A credential a run needs rides as secrets: { token: new Secret(value) } on execute options and is read inside the first step as i.secrets?.token; it is never stored, so a resumed attempt reads none.

Check it#

durable-sdk doctor --host
pnpm test

The doctor refuses a definition without describe or example, a key that reads the clock, a step without an undo or a reason, a loader that misses a file; each finding is one line with its fix, and durable-sdk doctor --host --explain <rule id> says the law. Testing writes the three cases every workflow carries. The whole contract underneath, every option of defineWorkflow and every refusal a door throws, is the generated page Workflows.