Setting & Getting State
Setting and Getting State
The WorkflowContext provides set_state() and get_state() methods to store and retrieve typed values by string key. State values are JSON-serialized, so any serializable type can be stored.
1use orcher::prelude::*;2use anyhow::Result;34#[task]5pub async fn process_payment(_ctx: TaskContext, amount: f64) -> Result<PaymentResult> {6 // ...7}89#[workflow]10pub async fn order_workflow(11 ctx: WorkflowContext,12 input: OrderInput,13) -> Result<OrderResult> {14 // Set state values15 ctx.set_state("order_id", &input.order_id)?;16 ctx.set_state("status", &"processing")?;17 ctx.set_state("customer_id", &input.customer_id)?;1819 // Process order20 let payment_result: PaymentResult = ctx21 .execute_task(process_payment, input.amount)22 .await?;2324 // Update state after task completes25 ctx.set_state("payment_id", &payment_result.payment_id)?;26 ctx.set_state("status", &"paid")?;2728 // Get state value29 let current_status: Option<String> = ctx.get_state("status")?;30 println!("Current status: {:?}", current_status);3132 Ok(OrderResult {33 order_id: input.order_id,34 payment_id: payment_result.payment_id,35 status: current_status.unwrap_or_default(),36 })37}State Lifecycle
State Persistence
State is stored in-memory during workflow execution and reconstructed from the journal on replay. This means state values set before a crash are available after the workflow resumes — the replay re-executes the workflow code, and set_state() calls run again with the same deterministic values.
- After
set_state()calls — Value is stored in the in-memory state map - After task completions — The completed task result is journaled; on replay, the same result is returned and the subsequent
set_state()calls produce identical state - On crash/restart — The journal is replayed, reconstructing the same state
- During replay —
set_state()calls execute normally but produce the same values because the workflow is deterministic
State During Replay
The diagram below shows how state is consistent across first execution and replay. Since workflows are deterministic and task results are journaled, every set_state() call produces the same value on replay.
stored in memory
stored in memory
task executes → result journaled
stored in memory
stored in memory
same value · deterministic
same value · deterministic
skipped → returns journaled result
same value · from journaled result
same value · deterministic
Every set_state() produces the same value on replay — state stays consistent across crashes.