Dynamic Child Spawning
Dynamic Child Spawning
When the number of child workflows isn't known at design time, you can spawn them dynamically based on runtime data. This is the foundation of fan-out patterns — iterate over a collection of items, spawn a child workflow for each one, then collect all results. Use Promise.allSettled (TypeScript) or sequential iteration with error handling (Rust/Python) to ensure that one failed child doesn't prevent others from completing.
Parent Workflow
Fetch Items
DB query returns N items
for each item → spawn child
Item 1
child wf
Item 2
child wf
Item 3
child wf
...
Item N
child wf
collect all results
Aggregate & Complete
1use orcher::prelude::*;2use anyhow::Result;34// Child workflow - processes a single invoice5#[workflow(name = "process_invoice", version = "1.0.0")]6pub async fn process_invoice(7 ctx: WorkflowContext,8 invoice_id: String,9) -> Result<InvoiceResult> {10 println!("Processing invoice {}", invoice_id);1112 // Generate PDF13 let pdf = ctx.execute_task(generate_pdf, invoice_id.clone()).await?;1415 // Send to customer16 ctx.execute_task(send_invoice_email, pdf.clone()).await?;1718 Ok(InvoiceResult {19 invoice_id,20 sent: true,21 })22}2324// Parent workflow - processes multiple invoices in parallel25#[workflow(name = "monthly_billing", version = "1.0.0")]26pub async fn monthly_billing(27 ctx: WorkflowContext,28 customer_ids: Vec<String>,29) -> Result<BillingResult> {30 println!("Starting monthly billing for {} customers", customer_ids.len());3132 // Spawn a child workflow for each customer33 let mut handles = Vec::new();3435 for customer_id in customer_ids.iter() {36 let invoice_id = format!("inv-{}-{}", customer_id, ctx.workflow_id());3738 let handle = ctx39 .start_child_workflow("process_invoice", invoice_id)40 .await?;4142 handles.push(handle);43 }4445 println!("Spawned {} invoice workflows", handles.len());4647 // Wait for all children to complete48 let mut results = Vec::new();49 for handle in handles {50 match handle.result::<InvoiceResult>().await {51 Ok(result) => results.push(result),52 // Never swallow the suspend signal — re-throw it so the runtime can53 // pause the parent until the child completes.54 Err(e) if e.is_suspend() => return Err(e.into()),55 Err(e) => {56 eprintln!("Invoice failed: {}", e);57 // Continue processing others58 }59 }60 }6162 Ok(BillingResult {63 total: results.len(),64 successful: results.iter().filter(|r| r.sent).count(),65 failed: results.len() - results.iter().filter(|r| r.sent).count(),66 })67}