Guides

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.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[task]
5
pub async fn process_item(_ctx: TaskContext, item: Item) -> Result<ProcessedItem> {
6
// ...
7
}
8
9
#[workflow]
10
pub async fn batch_processor(
11
ctx: WorkflowContext,
12
items: Vec<Item>,
13
) -> Result<BatchResult> {
14
// Initialize progress state
15
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")?;
19
20
let mut results = Vec::new();
21
22
for (index, item) in items.iter().enumerate() {
23
// Update progress
24
ctx.set_state("current_item", &index)?;
25
ctx.set_state("processed_items", &(index + 1))?;
26
27
// Process item
28
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
}
37
38
// Calculate percentage
39
let percentage = ((index + 1) as f64 / items.len() as f64) * 100.0;
40
ctx.set_state("progress_percentage", &percentage)?;
41
}
42
43
ctx.set_state("status", &"completed")?;
44
45
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.

validating
Validate input
processing
Process payment
shipping
Arrange shipment
notifying
Send confirmation
completed
done
failed
← any state can transition here
1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[derive(Serialize, Deserialize, Clone)]
5
enum OrderStatus {
6
Created,
7
PaymentProcessing,
8
PaymentCompleted,
9
Fulfilling,
10
Shipped,
11
Delivered,
12
Failed,
13
}
14
15
#[task]
16
pub async fn process_payment(_ctx: TaskContext, order_id: String) -> Result<Payment> { /* ... */ }
17
18
#[task]
19
pub async fn fulfill_order(_ctx: TaskContext, order_id: String) -> Result<Fulfillment> { /* ... */ }
20
21
#[task]
22
pub async fn ship_order(_ctx: TaskContext, fulfillment_id: String) -> Result<Tracking> { /* ... */ }
23
24
#[workflow]
25
pub async fn order_fulfillment(
26
ctx: WorkflowContext,
27
order_id: String,
28
) -> Result<OrderResult> {
29
// Initialize status
30
ctx.set_state("status", &OrderStatus::Created)?;
31
ctx.set_state("order_id", &order_id)?;
32
33
// Payment phase
34
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)?;
38
39
// Fulfillment phase
40
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)?;
43
44
// Shipping phase
45
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)?;
48
49
// Delivery
50
ctx.set_state("status", &OrderStatus::Delivered)?;
51
52
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.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[task]
5
pub async fn fetch_from_source(_ctx: TaskContext, source: DataSource) -> Result<SourceData> {
6
// ...
7
}
8
9
#[workflow]
10
pub async fn data_aggregation(
11
ctx: WorkflowContext,
12
sources: Vec<DataSource>,
13
) -> Result<AggregateResult> {
14
// Initialize aggregation state
15
ctx.set_state("total_records", &0usize)?;
16
ctx.set_state("total_bytes", &0usize)?;
17
ctx.set_state("sources_completed", &0usize)?;
18
19
let mut all_data = Vec::new();
20
21
for source in sources {
22
// Fetch data from source
23
let data: SourceData = ctx
24
.execute_task(fetch_from_source, source)
25
.await?;
26
27
// Accumulate results
28
all_data.extend(data.records);
29
30
// Update aggregate state
31
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);
34
35
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
}
39
40
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.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[workflow]
5
pub 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)?;
11
12
// Register query handlers — external clients can call these
13
ctx.register_query_handler("get_status", || {
14
"processing".to_string()
15
});
16
17
ctx.register_query_handler("get_progress", || {
18
serde_json::json!({
19
"completed": 0,
20
"total": 100,
21
"percentage": 0.0
22
})
23
});
24
25
// ... workflow logic ...
26
27
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.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
4
#[tokio::main]
5
async fn main() -> Result<()> {
6
let client = OrcherClient::connect("http://localhost:50051").await?;
7
8
let workflow_id = "order-abc123";
9
10
// Query registered handlers by name
11
let status: String = client
12
.query_workflow(workflow_id, None, "get_status", ())
13
.await?;
14
15
let progress: serde_json::Value = client
16
.query_workflow(workflow_id, None, "get_progress", ())
17
.await?;
18
19
println!("Workflow status: {}", status);
20
println!("Progress: {}", progress);
21
22
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]
2
pub async fn example_workflow(
3
ctx: WorkflowContext,
4
input: Input,
5
) -> Result<Output> {
6
// State: Needs to survive crash and be queryable
7
ctx.set_state("order_id", &input.order_id)?;
8
9
// Local variable: Temporary computation, recomputed on replay
10
let tax = input.amount * 0.08;
11
let total = input.amount + tax;
12
13
// State: Progress tracking (queryable by external systems)
14
ctx.set_state("status", &"processing")?;
15
16
let result = ctx.execute_task(process, total).await?;
17
18
// Local variable: Derived from task result
19
let formatted = format!("Result: {}", result);
20
21
// State: Final result (queryable)
22
ctx.set_state("result", &result)?;
23
24
Ok(Output { result })
25
}

Next Steps