Best Practices & Performance
Best Practices
1. Keep Children Independent
Each child workflow should be self-contained and receive all the data it needs through its input parameters. Avoid having children fetch their own context from external databases or shared state — this makes them brittle and harder to test in isolation.
1// Good - Child receives all necessary data2#[workflow(name = "process_order", version = "1.0.0")]3pub async fn process_order(4 ctx: WorkflowContext,5 order: OrderData, // Complete, self-contained input6) -> Result<OrderResult> {7 ctx.execute_task(validate_order, order.clone()).await?;8 ctx.execute_task(charge_payment, order.total).await?;9 Ok(OrderResult::success(order.id))10}1112// Bad - Child depends on external state13#[workflow(name = "process_order_bad", version = "1.0.0")]14pub async fn process_order_bad(15 ctx: WorkflowContext,16 order_id: String, // Must fetch order from external source - brittle!17) -> Result<OrderResult> {18 let order = fetch_from_database(&order_id).await?;19 // ...20}2. Limit Hierarchy Depth
Keep hierarchies shallow (2-3 levels maximum) for better observability, easier debugging, and simpler error propagation. Deep nesting makes it hard to trace failures and understand the overall execution flow.
3. Handle Child Failures Gracefully
Always catch and handle child workflow errors to prevent parent crashes. Decide explicitly whether to retry, fall back, or continue with partial results.
1// Good - Graceful error handling2match child_handle.result::<PaymentResult>().await {3 Ok(result) => process_success(result),4 // Re-throw the suspend signal — never handle it as a child failure.5 Err(e) if e.is_suspend() => return Err(e.into()),6 Err(e) => {7 eprintln!("Child failed: {}", e);8 handle_fallback().await?9 }10}1112// Bad - Unhandled errors crash parent13let result = child_handle.result::<PaymentResult>().await?; // Crashes on error4. Control Concurrency for Large Fan-Outs
Spawning thousands of children simultaneously can overwhelm the database and workers. Process items in batches with a concurrency limit, waiting for each batch to complete before starting the next.
1// Good - Batch processing with concurrency control2const MAX_CONCURRENT: usize = 50;34for chunk in items.chunks(MAX_CONCURRENT) {5 let mut handles = Vec::new();67 for item in chunk {8 handles.push(ctx.start_child_workflow("process", item).await?);9 }1011 // Wait for batch to complete before starting next12 for handle in handles {13 handle.result::<ProcessResult>().await?;14 }15}5. Use Events for Dynamic Control
Send events to children to change their behavior at runtime — expedite processing, change priority, or request graceful cancellation — without restarting them.
1// Good - Dynamic control via events2// NOTE: sending events to (or canceling) a child from inside a workflow via the3// child handle is not yet implemented in the Rust SDK — these methods currently4// return an unimplemented error. Deliver control events to the child from an5// external client, addressing it by the child's workflow id.6child_handle.send_event("cancel", true).await?;7child_handle.send_event("priority_changed", Priority::High).await?;89// Bad - Canceling and restarting is expensive10child_handle.cancel().await?;11let new_child = ctx.start_child_workflow("new_child", data).await?;Performance Considerations
Child Workflow Overhead
Each child workflow carries its own overhead — a database record, an execution journal, state storage, and an event buffer. For very fast operations (under 1 second), the overhead of creating a child workflow may exceed the operation itself. Use tasks for lightweight operations and reserve child workflows for operations that involve multiple steps, need independent error handling, or take more than a few seconds.
When to Use Tasks vs Child Workflows
| Criteria | Use a Task | Use a Child Workflow |
|---|---|---|
| Duration | < 1 second | > 1 second, multi-step |
| Error handling | Retry policy is sufficient | Needs saga/compensation |
| Reusability | Single-purpose operation | Reusable across parents |
| State | Stateless | Needs its own state/journal |
| Monitoring | Part of parent's journal | Independent status tracking |
Common Patterns Summary
| Pattern | Use Case | Example |
|---|---|---|
| Sequential Children | Multi-phase processing | Validate -> Process -> Notify |
| Parallel Children | Batch processing | Process 100 invoices concurrently |
| Dynamic Spawning | Variable workload | Spawn N children based on input |
| Event Coordination | Runtime control | Parent signals child to expedite |
| Hierarchical | Complex orchestration | Order -> Payment -> Notification |
| Map-Reduce | Large dataset processing | Split data, process, aggregate |
| Fallback Chain | Resilience | Primary child fails -> Try fallback |
Real-World Use Cases
E-commerce Order Fulfillment
Surface tint marks nesting depth: parent → child → grandchild. Each child is an independent workflow with its own journal.
Multi-Region Deployment
Four regional children run in parallel; the parent completes when all succeed.
Content Moderation Pipeline
Surface tint marks nesting depth; the dashed child runs only when earlier steps flag content.