Patterns
Patterns for common workflow shapes, written with the TypeScript SDK. The tasks they call are
defined with @Tasks() classes and createTaskRefs(), as in Tasks.
Saga (Compensation)
When a workflow books several things across services, a failure halfway must undo what was
already done. The SDK's Saga keeps the list of compensations and runs them newest first:
1export const bookTrip = workflow({2 name: 'bookTrip',3 run: async (ctx: WorkflowContext, trip: Trip): Promise<string[]> => {4 const saga = new Saga();5 try {6 // Run a step and, once it succeeds, register what undoes it.7 const hotel = await ctx.executeTask(bookingTasks.bookHotel, trip);8 saga.addCompensation(() => ctx.executeTask(bookingTasks.cancelHotel, hotel));910 const flight = await ctx.executeTask(bookingTasks.bookFlight, trip);11 saga.addCompensation(() => ctx.executeTask(bookingTasks.cancelFlight, flight));1213 const charge = await ctx.executeTask(bookingTasks.charge, trip);14 saga.commit();15 return [hotel, flight, charge];16 } catch (err) {17 // Waiting for a task arrives here as a thrown suspension. Re-throw it first,18 // or every healthy run cancels its own bookings.19 if (isWorkflowSuspension(err)) throw err;20 await saga.compensate(); // newest first; a failing compensation is logged and skipped21 throw err;22 }23 },24});The isWorkflowSuspension(err) check is not optional. Waiting for a task makes
ctx.executeTask() throw a suspension, and a catch without the check would compensate
on every wait: a healthy run would cancel its own bookings. Register each compensation only once
its step has succeeded, so a failed step is never "undone".
saga.addStep(action, compensation) runs a step and registers its compensation in one call. It
compensates and re-throws when the step fails, and lets a suspension through:
1export const bookTripSteps = workflow({2 name: 'bookTripSteps',3 run: async (ctx: WorkflowContext, trip: Trip): Promise<string> => {4 const saga = new Saga();5 // addStep runs the action and registers the compensation together. If the6 // action fails it compensates the earlier steps and re-throws; a suspension7 // passes through untouched. Use it when the compensation does not need the8 // action's result.9 await saga.addStep(10 () => ctx.executeTask(bookingTasks.bookHotel, trip),11 () => ctx.executeTask(bookingTasks.cancelHotel, `hotel_${trip.hotelId}`),12 );13 const charge = await saga.addStep(() => ctx.executeTask(bookingTasks.charge, trip));14 saga.commit();15 return charge;16 },17});compensate() runs each compensation once. A compensation that fails is logged and skipped, and
the rest still run. Compensations are ordinary tasks, so they are journaled and retried like any
other; make them idempotent.
Parallel Tasks
Start independent tasks together and wait for all of them with Promise.all:
1export const priceBasket = workflow({2 name: 'priceBasket',3 run: async (ctx: WorkflowContext, { skus }: { skus: string[] }): Promise<number> => {4 // All the tasks are scheduled at once; the workflow carries on when every one is done.5 const prices = await Promise.all(skus.map((sku) => ctx.executeTask(workTasks.fetchPrice, sku)));6 return prices.reduce((sum, price) => sum + price, 0);7 },8});Fan-Out / Fan-In with Child Workflows
For larger units of work, give each its own child workflow and journal. Start them all with
ctx.startChildWorkflow(), then wait for their results:
1export const priceRegion = workflow({2 name: 'priceRegion',3 run: async (ctx: WorkflowContext, { skus }: { skus: string[] }): Promise<number> => {4 const prices = await Promise.all(skus.map((sku) => ctx.executeTask(workTasks.fetchPrice, sku)));5 return prices.reduce((sum, price) => sum + price, 0);6 },7});89export const priceCatalog = workflow({10 name: 'priceCatalog',11 run: async (ctx: WorkflowContext, regions: Record<string, string[]>): Promise<number> => {12 // One child workflow per region, each with its own journal.13 const children = [];14 for (const [region, skus] of Object.entries(regions)) {15 children.push(await ctx.startChildWorkflow<number>('priceRegion', { skus }, { workflowId: `${ctx.workflowId()}-${region}` }));16 }17 const totals = await Promise.all(children.map((child) => child.result()));18 return totals.reduce((sum, total) => sum + total, 0);19 },20});When you set child ids yourself, derive them from the parent's id as above, so two runs of the parent never ask for the same id.
Approval with a Deadline
Wait for a person's decision, escalate if it doesn't come in time, and let clients ask where the request stands:
1export const purchaseApproval = workflow({2 name: 'purchaseApproval',3 run: async (ctx: WorkflowContext, requestId: string): Promise<string> => {4 let status = 'waiting for approval';5 ctx.registerQueryHandler('status', () => status);67 await ctx.executeTask(workTasks.notifyApprover, requestId);89 // The deadline is a durable timer held by the engine, so it survives worker restarts.10 const decision = await ctx.waitForEventWithTimeout<{ approved: boolean }>(11 'approval',12 Duration.fromDays(2),13 );1415 if (decision === null) {16 status = 'escalated';17 await ctx.executeTask(workTasks.escalate, requestId);18 } else {19 status = decision.approved ? 'approved' : 'rejected';20 }21 return status;22 },23});The client side sends the decision with handle.sendEvent('approval', { approved: true }), and
reads the status with handle.query('status').
Starting Work Once
Use the business identity of the work as the workflow id, so a repeated request (a retried webhook, a double click) finds the run that is already going instead of starting a second one. See starting a workflow once for the reuse policies and the sample.
Batching
Each task call is a journal entry and a round trip through the engine. When items are small and processed the same way, process them in batches:
1export const processAll = workflow({2 name: 'processAll',3 run: async (ctx: WorkflowContext, { items }: { items: string[] }): Promise<number> => {4 // One task per 100 items rather than one per item: fewer journal entries5 // and round trips. Keep each batch well under the payload limit.6 let processed = 0;7 for (let i = 0; i < items.length; i += 100) {8 processed += await ctx.executeTask(workTasks.processBatch, { items: items.slice(i, i + 100) });9 }10 return processed;11 },12});Keep every task input and result under the payload limit, 8 MiB on a default engine. For more
data than that, store it elsewhere and pass references. For a workflow that loops for a long
time, start a fresh journal now and then with
ctx.restartFresh().