Guides

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 data
2
#[workflow(name = "process_order", version = "1.0.0")]
3
pub async fn process_order(
4
ctx: WorkflowContext,
5
order: OrderData, // Complete, self-contained input
6
) -> 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
}
11
12
// Bad - Child depends on external state
13
#[workflow(name = "process_order_bad", version = "1.0.0")]
14
pub 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.

How Deep to Nest
Good
Parent → Child
2 levels — trivial to trace
Acceptable
Parent → Child → Grandchild
3 levels for complex domains
Avoid
Parent → Child → Grandchild → Great-grandchild
4+ levels — failures get hard to follow
Each level you add multiplies the places a failure can hide — stay shallow by default.

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 handling
2
match 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
}
11
12
// Bad - Unhandled errors crash parent
13
let result = child_handle.result::<PaymentResult>().await?; // Crashes on error

4. 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 control
2
const MAX_CONCURRENT: usize = 50;
3
4
for chunk in items.chunks(MAX_CONCURRENT) {
5
let mut handles = Vec::new();
6
7
for item in chunk {
8
handles.push(ctx.start_child_workflow("process", item).await?);
9
}
10
11
// Wait for batch to complete before starting next
12
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 events
2
// NOTE: sending events to (or canceling) a child from inside a workflow via the
3
// child handle is not yet implemented in the Rust SDK — these methods currently
4
// return an unimplemented error. Deliver control events to the child from an
5
// external client, addressing it by the child's workflow id.
6
child_handle.send_event("cancel", true).await?;
7
child_handle.send_event("priority_changed", Priority::High).await?;
8
9
// Bad - Canceling and restarting is expensive
10
child_handle.cancel().await?;
11
let 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

CriteriaUse a TaskUse a Child Workflow
Duration< 1 second> 1 second, multi-step
Error handlingRetry policy is sufficientNeeds saga/compensation
ReusabilitySingle-purpose operationReusable across parents
StateStatelessNeeds its own state/journal
MonitoringPart of parent's journalIndependent status tracking

Common Patterns Summary

PatternUse CaseExample
Sequential ChildrenMulti-phase processingValidate -> Process -> Notify
Parallel ChildrenBatch processingProcess 100 invoices concurrently
Dynamic SpawningVariable workloadSpawn N children based on input
Event CoordinationRuntime controlParent signals child to expedite
HierarchicalComplex orchestrationOrder -> Payment -> Notification
Map-ReduceLarge dataset processingSplit data, process, aggregate
Fallback ChainResiliencePrimary child fails -> Try fallback

Real-World Use Cases

E-commerce Order Fulfillment

Order Processing
parent
Payment Authorization
Inventory Reservation
Shipping Coordination
Label Generation
Carrier Selection
Customer Notification

Surface tint marks nesting depth: parent → child → grandchild. Each child is an independent workflow with its own journal.

Multi-Region Deployment

Global Deployment
parent
Deploy US-East
Deploy US-West
Deploy EU-Central
Deploy Asia-Pacific

Four regional children run in parallel; the parent completes when all succeed.

Content Moderation Pipeline

Content Moderation
parent
Image Analysis
NSFW Detection
Text Extraction
Text Analysis
Human Review
conditional

Surface tint marks nesting depth; the dashed child runs only when earlier steps flag content.


Next Steps