Best Practices & Performance
Best Practices
1. Use Descriptive Keys
Choose clear, descriptive state keys that communicate the value's purpose. This makes workflows easier to debug and query handlers easier to write.
1// Good: Clear, descriptive keys2ctx.set_state("payment_id", &payment_id)?;3ctx.set_state("shipping_status", &status)?;4ctx.set_state("total_items_processed", &count)?;56// Bad: Vague keys — hard to query, debug, or understand7ctx.set_state("id", &payment_id)?;8ctx.set_state("s", &status)?;9ctx.set_state("n", &count)?;2. Initialize State Early
Set all state keys at the beginning of the workflow so query handlers and monitoring tools always have values to return, even if the workflow hasn't progressed far.
1#[workflow]2pub async fn order_workflow(3 ctx: WorkflowContext,4 input: OrderInput,5) -> Result<OrderResult> {6 // Initialize all state upfront — queries always return a value7 ctx.set_state("order_id", &input.order_id)?;8 ctx.set_state("status", &"pending")?;9 ctx.set_state("total_amount", &0.0)?;10 ctx.set_state("items_count", &input.items.len())?;1112 // Process workflow...13 Ok(result)14}3. Use Typed State
Define structured types for complex state values instead of storing many individual keys. This provides compile-time safety and makes it easier to serialize, deserialize, and query state as a unit.
1// Define a typed struct for state2#[derive(Serialize, Deserialize, Clone)]3struct OrderState {4 order_id: String,5 status: OrderStatus,6 payment_id: Option<String>,7 tracking_number: Option<String>,8}910// Store as a single typed value11let state = OrderState {12 order_id: input.order_id.clone(),13 status: OrderStatus::Processing,14 payment_id: None,15 tracking_number: None,16};17ctx.set_state("order_state", &state)?;1819// Retrieve with type safety20let current: Option<OrderState> = ctx.get_state("order_state")?;4. Don't Store Sensitive Data
Workflow state is stored in the database and may be queryable by external systems. Never store sensitive information like credentials, credit card numbers, or personal identifiers directly — use tokenized references instead.
1// Bad: Storing sensitive data in queryable state2ctx.set_state("credit_card_number", &card_number)?;3ctx.set_state("ssn", &ssn)?;45// Good: Store only tokenized references6ctx.set_state("payment_token", &token_id)?;7ctx.set_state("card_last_four", &"1234")?;5. Update State Atomically
When multiple state values are logically related, store them as a single struct instead of individual keys. This prevents inconsistent state if the workflow crashes between two separate set_state() calls.
1// Bad: Multiple related updates — can be inconsistent if crash occurs between them2ctx.set_state("processed", &processed)?;3ctx.set_state("failed", &failed)?;4ctx.set_state("total", &total)?;56// Good: Single atomic state object7#[derive(Serialize, Deserialize)]8struct ProcessingStats {9 processed: usize,10 failed: usize,11 total: usize,12}1314let stats = ProcessingStats { processed, failed, total };15ctx.set_state("processing_stats", &stats)?;6. Clean Up State
Remove large temporary state values after they are no longer needed. This reduces storage footprint and speeds up serialization during replay.
1#[workflow]2pub async fn cleanup_example(3 ctx: WorkflowContext,4 input: Input,5) -> Result<Output> {6 // Set temporary state for intermediate processing7 ctx.set_state("temp_data", &large_data)?;89 // Use it10 let result = process_data(&large_data)?;1112 // Clean up — set to None to free storage13 ctx.set_state("temp_data", &Option::<String>::None)?;1415 Ok(result)16}Performance Considerations
State Size
Keep state values small to minimize serialization overhead and database storage. Store references (IDs, keys) rather than full objects — fetch the full data in a task when you need it.
1// Bad: Storing full object in state (10KB per entry)2ctx.set_state("full_user_data", &user_object)?;34// Good: Store only the ID (36 bytes), fetch the rest in a task5ctx.set_state("user_id", &user.id)?;State Frequency
Minimize the number of set_state() calls in tight loops. Accumulate values in local variables and write the final result to state once. Each set_state() call involves serialization, so batching reduces overhead.
1// Bad: State write on every iteration2for item in items {3 let count: usize = ctx.get_state("count")?.unwrap_or(0);4 ctx.set_state("count", &(count + 1))?; // N serialization calls5}67// Good: Accumulate locally, write once8let mut count = 0;9for item in items {10 count += 1;11}12ctx.set_state("count", &count)?; // 1 serialization callTroubleshooting
State Not Persisting
Symptom: State values are lost after workflow restart.
Solutions:
- Verify that
set_state()is called before the crash point — state set after a failed task may not be reached - Check for serialization errors in logs — if the value can't be serialized to JSON, the state write silently fails
- Ensure the workflow is deterministic — non-deterministic code paths may skip
set_state()calls on replay
State Type Errors
Symptom: Deserialization errors when calling get_state().
Solutions:
- Use consistent types for the same key across
set_state()andget_state()calls - Handle
None/undefinedcases for keys that may not be set yet - Use explicit type annotations to catch mismatches at compile time
1// Handle missing state gracefully2let status: String = ctx3 .get_state("status")?4 .unwrap_or_else(|| "unknown".to_string());State Too Large
Symptom: Slow workflow performance, high serialization overhead.
Solutions:
- Store IDs and references instead of full objects — fetch the data in a task when needed
- Clean up temporary state with
set_state("key", None)after use - Use external storage (S3, database) for large blobs and store only the reference in state