Guides

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
1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
// Child workflow - processes a single invoice
5
#[workflow(name = "process_invoice", version = "1.0.0")]
6
pub async fn process_invoice(
7
ctx: WorkflowContext,
8
invoice_id: String,
9
) -> Result<InvoiceResult> {
10
println!("Processing invoice {}", invoice_id);
11
12
// Generate PDF
13
let pdf = ctx.execute_task(generate_pdf, invoice_id.clone()).await?;
14
15
// Send to customer
16
ctx.execute_task(send_invoice_email, pdf.clone()).await?;
17
18
Ok(InvoiceResult {
19
invoice_id,
20
sent: true,
21
})
22
}
23
24
// Parent workflow - processes multiple invoices in parallel
25
#[workflow(name = "monthly_billing", version = "1.0.0")]
26
pub 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());
31
32
// Spawn a child workflow for each customer
33
let mut handles = Vec::new();
34
35
for customer_id in customer_ids.iter() {
36
let invoice_id = format!("inv-{}-{}", customer_id, ctx.workflow_id());
37
38
let handle = ctx
39
.start_child_workflow("process_invoice", invoice_id)
40
.await?;
41
42
handles.push(handle);
43
}
44
45
println!("Spawned {} invoice workflows", handles.len());
46
47
// Wait for all children to complete
48
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 can
53
// 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 others
58
}
59
}
60
}
61
62
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
}

Next Steps