State Patterns
Common State Patterns
These patterns demonstrate how to use workflow state for real-world scenarios. Each example shows how state enables progress tracking, status transitions, and result accumulation across long-running workflows.
Progress Tracking
Track how far a batch workflow has progressed. External systems can query the progress state to display completion percentage in a dashboard or UI.
1use orcher::prelude::*;2use anyhow::Result;34#[task]5pub async fn process_item(_ctx: TaskContext, item: Item) -> Result<ProcessedItem> {6 // ...7}89#[workflow]10pub async fn batch_processor(11 ctx: WorkflowContext,12 items: Vec<Item>,13) -> Result<BatchResult> {14 // Initialize progress state15 ctx.set_state("total_items", &items.len())?;16 ctx.set_state("processed_items", &0usize)?;17 ctx.set_state("failed_items", &0usize)?;18 ctx.set_state("status", &"running")?;1920 let mut results = Vec::new();2122 for (index, item) in items.iter().enumerate() {23 // Update progress24 ctx.set_state("current_item", &index)?;25 ctx.set_state("processed_items", &(index + 1))?;2627 // Process item28 match ctx.execute_task(process_item, item.clone()).await {29 Ok(result) => {30 results.push(result);31 }32 Err(_e) => {33 let failed: usize = ctx.get_state("failed_items")?.unwrap_or(0);34 ctx.set_state("failed_items", &(failed + 1))?;35 }36 }3738 // Calculate percentage39 let percentage = ((index + 1) as f64 / items.len() as f64) * 100.0;40 ctx.set_state("progress_percentage", &percentage)?;41 }4243 ctx.set_state("status", &"completed")?;4445 Ok(BatchResult {46 total: items.len(),47 processed: results.len(),48 failed: items.len() - results.len(),49 })50}Status Machine
Model workflow execution as a state machine with well-defined transitions. Each phase of the workflow updates the status, making it easy to track where the workflow is at any point — and to resume from the correct phase after a crash.
Validate inputProcess paymentArrange shipmentSend confirmation1use orcher::prelude::*;2use anyhow::Result;34#[derive(Serialize, Deserialize, Clone)]5enum OrderStatus {6 Created,7 PaymentProcessing,8 PaymentCompleted,9 Fulfilling,10 Shipped,11 Delivered,12 Failed,13}1415#[task]16pub async fn process_payment(_ctx: TaskContext, order_id: String) -> Result<Payment> { /* ... */ }1718#[task]19pub async fn fulfill_order(_ctx: TaskContext, order_id: String) -> Result<Fulfillment> { /* ... */ }2021#[task]22pub async fn ship_order(_ctx: TaskContext, fulfillment_id: String) -> Result<Tracking> { /* ... */ }2324#[workflow]25pub async fn order_fulfillment(26 ctx: WorkflowContext,27 order_id: String,28) -> Result<OrderResult> {29 // Initialize status30 ctx.set_state("status", &OrderStatus::Created)?;31 ctx.set_state("order_id", &order_id)?;3233 // Payment phase34 ctx.set_state("status", &OrderStatus::PaymentProcessing)?;35 let payment = ctx.execute_task(process_payment, order_id.clone()).await?;36 ctx.set_state("status", &OrderStatus::PaymentCompleted)?;37 ctx.set_state("payment_id", &payment.payment_id)?;3839 // Fulfillment phase40 ctx.set_state("status", &OrderStatus::Fulfilling)?;41 let fulfillment = ctx.execute_task(fulfill_order, order_id.clone()).await?;42 ctx.set_state("fulfillment_id", &fulfillment.fulfillment_id)?;4344 // Shipping phase45 ctx.set_state("status", &OrderStatus::Shipped)?;46 let tracking = ctx.execute_task(ship_order, fulfillment.fulfillment_id).await?;47 ctx.set_state("tracking_number", &tracking.tracking_number)?;4849 // Delivery50 ctx.set_state("status", &OrderStatus::Delivered)?;5152 Ok(OrderResult {53 order_id,54 status: "delivered".to_string(),55 })56}Accumulating Results
Collect results from multiple steps into aggregate state. This pattern is useful for fan-out workflows where you process data from multiple sources and need to track totals across iterations.
1use orcher::prelude::*;2use anyhow::Result;34#[task]5pub async fn fetch_from_source(_ctx: TaskContext, source: DataSource) -> Result<SourceData> {6 // ...7}89#[workflow]10pub async fn data_aggregation(11 ctx: WorkflowContext,12 sources: Vec<DataSource>,13) -> Result<AggregateResult> {14 // Initialize aggregation state15 ctx.set_state("total_records", &0usize)?;16 ctx.set_state("total_bytes", &0usize)?;17 ctx.set_state("sources_completed", &0usize)?;1819 let mut all_data = Vec::new();2021 for source in sources {22 // Fetch data from source23 let data: SourceData = ctx24 .execute_task(fetch_from_source, source)25 .await?;2627 // Accumulate results28 all_data.extend(data.records);2930 // Update aggregate state31 let total_records: usize = ctx.get_state("total_records")?.unwrap_or(0);32 let total_bytes: usize = ctx.get_state("total_bytes")?.unwrap_or(0);33 let sources_completed: usize = ctx.get_state("sources_completed")?.unwrap_or(0);3435 ctx.set_state("total_records", &(total_records + data.records.len()))?;36 ctx.set_state("total_bytes", &(total_bytes + data.size_bytes))?;37 ctx.set_state("sources_completed", &(sources_completed + 1))?;38 }3940 Ok(AggregateResult {41 total_records: all_data.len(),42 total_bytes: ctx.get_state("total_bytes")?.unwrap_or(0),43 })44}Querying Workflow State
External systems can query workflow state without blocking execution. Workflows register query handlers that return state values on demand — clients call query_workflow() with a query name, and the handler runs inside the workflow context with access to the current state.
Registering Query Handlers
Define query handlers inside your workflow to expose state to external callers. Each handler has a name and returns a serializable value.
1use orcher::prelude::*;2use anyhow::Result;34#[workflow]5pub async fn order_workflow(6 ctx: WorkflowContext,7 input: OrderInput,8) -> Result<OrderResult> {9 ctx.set_state("status", &"processing")?;10 ctx.set_state("progress", &0.0f64)?;1112 // Register query handlers — external clients can call these13 ctx.register_query_handler("get_status", || {14 "processing".to_string()15 });1617 ctx.register_query_handler("get_progress", || {18 serde_json::json!({19 "completed": 0,20 "total": 100,21 "percentage": 0.022 })23 });2425 // ... workflow logic ...2627 Ok(result)28}Querying from External Systems
Use the Orcher client SDK to query a running workflow's state from outside the workflow — for example, from a REST API handler, a monitoring dashboard, or another service.
1use orcher::prelude::*;2use anyhow::Result;34#[tokio::main]5async fn main() -> Result<()> {6 let client = OrcherClient::connect("http://localhost:50051").await?;78 let workflow_id = "order-abc123";910 // Query registered handlers by name11 let status: String = client12 .query_workflow(workflow_id, None, "get_status", ())13 .await?;1415 let progress: serde_json::Value = client16 .query_workflow(workflow_id, None, "get_progress", ())17 .await?;1819 println!("Workflow status: {}", status);20 println!("Progress: {}", progress);2122 Ok(())23}State vs Variables
Understanding when to use workflow state vs. local variables helps you write efficient workflows. Use state for values that need to survive crashes or be queried externally. Use local variables for temporary computations that can be cheaply recomputed on replay.
Use Workflow State When:
- Need persistence — Value must survive crashes and be consistent on replay
- External queries — Value needs to be queried by external systems via query handlers
- Progress tracking — Monitoring workflow execution from a dashboard or API
- Long-running workflows — Workflow runs for hours/days and needs observable state
Use Local Variables When:
- Temporary computation — Only needed within a single code block
- Derived values — Can be recomputed from task results on replay
- Performance critical — Avoid serialization overhead for hot-path values
- Private data — Should not be externally queryable
1#[workflow]2pub async fn example_workflow(3 ctx: WorkflowContext,4 input: Input,5) -> Result<Output> {6 // State: Needs to survive crash and be queryable7 ctx.set_state("order_id", &input.order_id)?;89 // Local variable: Temporary computation, recomputed on replay10 let tax = input.amount * 0.08;11 let total = input.amount + tax;1213 // State: Progress tracking (queryable by external systems)14 ctx.set_state("status", &"processing")?;1516 let result = ctx.execute_task(process, total).await?;1718 // Local variable: Derived from task result19 let formatted = format!("Result: {}", result);2021 // State: Final result (queryable)22 ctx.set_state("result", &result)?;2324 Ok(Output { result })25}