Child Workflows for Service Composition
Child workflows let you break complex orchestrations into smaller, independently testable components. Each child runs with its own execution context and lifecycle — if a child fails, the parent can catch the error, try a fallback, or compensate. This pattern maps naturally to microservice boundaries: one child workflow per service domain (payments, inventory, shipping), composed by a parent that coordinates the overall transaction.
How it works
The parent reads like a function calling functions — and that's the point. Each start_child_workflow(...) here is awaited before the next begins, because the phases depend on each other: no payment without a reservation, no shipment without payment. Note the example also mixes granularity deliberately: two phases are child workflows, the third is a plain task.
Tinted boxes have their own journal and failure boundary; the plain task belongs to the parent's.
Example: composing an order fulfillment
1import {2 Workflow,3 Tasks,4 Task,5 WorkflowContext,6 createTaskRefs,7 WorkerBuilder,8} from '@orcher/sdk';910// Child workflow tasks: Inventory11@Tasks()12class InventoryTasks {13 @Task()14 async checkStock(items: OrderItem[]): Promise<StockResult> {15 return await inventoryClient.checkAvailability(items);16 }1718 @Task()19 async reserveItems(req: ReservationRequest): Promise<string> {20 return await inventoryClient.reserve(req);21 }22}2324const inventoryTasks = createTaskRefs(InventoryTasks);2526// Child workflow: Reserve inventory27@Workflow({ name: 'reserve_inventory', version: '1.0.0' })28class ReserveInventory {29 async run(ctx: WorkflowContext, items: OrderItem[]): Promise<InventoryReservation> {30 const stock = await ctx.executeTask(inventoryTasks.checkStock, items);31 if (!stock.allAvailable) {32 throw new Error(`Items out of stock: ${stock.missing.join(', ')}`);33 }34 const reservationId = await ctx.executeTask(inventoryTasks.reserveItems, {35 items,36 ttlMinutes: 15,37 });38 return { reservationId, items: stock.confirmed };39 }40}4142// Child workflow tasks: Payments43@Tasks()44class PaymentTasks {45 @Task()46 async chargeCard(input: ChargeInput): Promise<ChargeResult> {47 return await paymentClient.charge(input);48 }4950 @Task()51 async sendReceipt(chargeId: string): Promise<void> {52 await emailClient.sendReceipt(chargeId);53 }54}5556const paymentTasks = createTaskRefs(PaymentTasks);5758// Child workflow: Process payment59@Workflow({ name: 'process_payment', version: '1.0.0' })60class ProcessPayment {61 async run(ctx: WorkflowContext, input: PaymentInput): Promise<PaymentResult> {62 const charge = await ctx.executeTask(paymentTasks.chargeCard, {63 amount: input.amount,64 currency: input.currency,65 method: input.method,66 });67 await ctx.executeTask(paymentTasks.sendReceipt, charge.id);68 return { chargeId: charge.id, status: 'completed' };69 }70}7172// Parent workflow tasks73@Tasks()74class ShippingTasks {75 @Task()76 async createShipment(input: ShipmentInput): Promise<string> {77 return await shippingClient.create(input);78 }79}8081const shippingTasks = createTaskRefs(ShippingTasks);8283// Parent workflow: Compose child workflows84@Workflow({ name: 'order_fulfillment', version: '1.0.0' })85class OrderFulfillment {86 async run(ctx: WorkflowContext, order: OrderInput): Promise<OrderResult> {87 // Phase 1: Reserve inventory (child workflow)88 const reservation = await ctx.startChildWorkflow(89 ReserveInventory, order.items,90 );9192 // Phase 2: Process payment (child workflow)93 const payment = await ctx.startChildWorkflow(94 ProcessPayment, order.payment,95 );9697 // Phase 3: Ship order (task)98 const tracking = await ctx.executeTask(shippingTasks.createShipment, {99 reservationId: reservation.reservationId,100 address: order.shippingAddress,101 });102103 return { paymentId: payment.chargeId, trackingNumber: tracking };104 }105}Each child workflow has its own execution history and can be tested independently. The parent catches child failures and can retry, fall back to alternatives, or compensate — exactly like calling functions in regular code, but with automatic journaling and crash recovery.
Child workflow or plain task?
The example draws the line deliberately, and it's the decision you'll make most often with this pattern:
Multiple steps, its own failure boundary and retries, reusable from other parents, often owned by another team. Inventory and payment here.
One atomic operation with no internal state worth isolating. Wrapping it in a workflow adds ceremony, not safety. Shipment creation here.
Design notes
- Sequential here, parallel when independent. These phases depend on each other, so each child is awaited immediately. When the units are independent — sources, regions, partitions — collect the handles first and await them together, as in multi-service deployment.
- A child failure is the parent's decision point. Out-of-stock propagates from
reserve_inventoryas an ordinary error the parent can catch: retry, fall back to another warehouse, or compensate what already completed. The child stays simple; policy lives in the parent. - Children are real workflows.
reserve_inventoryandprocess_paymentcan be started directly — in tests, from other parents, or by themselves in production. Composition is reuse, not just decomposition. - Keep the hierarchy shallow. Parent → children mapped to service domains is usually enough; grandchildren of grandchildren make execution history hard to follow. See Best Practices.
Next Steps
- Saga Pattern with Automatic Rollback — Handle multi-service transaction failures with compensating actions.
- Event Gates for Human Approvals — Pause workflows until external input arrives.
- Multi-Service Deployment — Fan-out across regions with parallel execution.
- Best Practices & Performance — Guidelines and benchmarks for distributed workflows.