Guides

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 keys
2
ctx.set_state("payment_id", &payment_id)?;
3
ctx.set_state("shipping_status", &status)?;
4
ctx.set_state("total_items_processed", &count)?;
5
6
// Bad: Vague keys — hard to query, debug, or understand
7
ctx.set_state("id", &payment_id)?;
8
ctx.set_state("s", &status)?;
9
ctx.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]
2
pub async fn order_workflow(
3
ctx: WorkflowContext,
4
input: OrderInput,
5
) -> Result<OrderResult> {
6
// Initialize all state upfront — queries always return a value
7
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())?;
11
12
// 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 state
2
#[derive(Serialize, Deserialize, Clone)]
3
struct OrderState {
4
order_id: String,
5
status: OrderStatus,
6
payment_id: Option<String>,
7
tracking_number: Option<String>,
8
}
9
10
// Store as a single typed value
11
let state = OrderState {
12
order_id: input.order_id.clone(),
13
status: OrderStatus::Processing,
14
payment_id: None,
15
tracking_number: None,
16
};
17
ctx.set_state("order_state", &state)?;
18
19
// Retrieve with type safety
20
let 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 state
2
ctx.set_state("credit_card_number", &card_number)?;
3
ctx.set_state("ssn", &ssn)?;
4
5
// Good: Store only tokenized references
6
ctx.set_state("payment_token", &token_id)?;
7
ctx.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 them
2
ctx.set_state("processed", &processed)?;
3
ctx.set_state("failed", &failed)?;
4
ctx.set_state("total", &total)?;
5
6
// Good: Single atomic state object
7
#[derive(Serialize, Deserialize)]
8
struct ProcessingStats {
9
processed: usize,
10
failed: usize,
11
total: usize,
12
}
13
14
let stats = ProcessingStats { processed, failed, total };
15
ctx.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]
2
pub async fn cleanup_example(
3
ctx: WorkflowContext,
4
input: Input,
5
) -> Result<Output> {
6
// Set temporary state for intermediate processing
7
ctx.set_state("temp_data", &large_data)?;
8
9
// Use it
10
let result = process_data(&large_data)?;
11
12
// Clean up — set to None to free storage
13
ctx.set_state("temp_data", &Option::<String>::None)?;
14
15
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)
2
ctx.set_state("full_user_data", &user_object)?;
3
4
// Good: Store only the ID (36 bytes), fetch the rest in a task
5
ctx.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 iteration
2
for item in items {
3
let count: usize = ctx.get_state("count")?.unwrap_or(0);
4
ctx.set_state("count", &(count + 1))?; // N serialization calls
5
}
6
7
// Good: Accumulate locally, write once
8
let mut count = 0;
9
for item in items {
10
count += 1;
11
}
12
ctx.set_state("count", &count)?; // 1 serialization call

Troubleshooting

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() and get_state() calls
  • Handle None/undefined cases for keys that may not be set yet
  • Use explicit type annotations to catch mismatches at compile time
1
// Handle missing state gracefully
2
let status: String = ctx
3
.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

Next Steps