Saga Coordinator Pattern
Saga Coordinator Pattern
For complex sagas with many steps, a dedicated coordinator encapsulates the state tracking and compensation logic into separate functions. The coordinator maintains a SagaState struct that records which steps have completed and stores the IDs needed for compensation. If any step fails, the coordinator hands the current state to a compensate function that walks through completed steps in reverse order. This separation makes the saga easier to test, extend with new steps, and audit.
Saga Coordinator
tracks state ยท manages compensation
execute steps
1
state.order_idvalidate_order2
state.reservation_idreserve_inventory3
state.payment_idprocess_payment4
state.shipment_idarrange_shippingsuccess
Commit
Return result
any step fails
compensate(state)
Undo in reverse order
1use orcher::prelude::*;2use anyhow::Result;3use serde::{Deserialize, Serialize};45#[derive(Debug, Clone, Serialize, Deserialize)]6struct SagaState {7 saga_id: String,8 current_step: u32,9 completed_steps: Vec<String>,10 inventory_reserved: bool,11 inventory_id: Option<String>,12 payment_captured: bool,13 payment_id: Option<String>,14 shipment_created: bool,15 shipment_id: Option<String>,16 failed: bool,17}1819impl SagaState {20 fn new(saga_id: String) -> Self {21 Self {22 saga_id,23 current_step: 0,24 completed_steps: Vec::new(),25 inventory_reserved: false,26 inventory_id: None,27 payment_captured: false,28 payment_id: None,29 shipment_created: false,30 shipment_id: None,31 failed: false,32 }33 }34}3536// Saga coordinator workflow37#[workflow(name = "saga_coordinator", version = "1.0.0")]38pub async fn saga_coordinator(39 ctx: WorkflowContext,40 order: OrderData,41) -> Result<OrderResult> {42 let saga_id = format!("saga-{}", order.order_id);43 let mut state = SagaState::new(saga_id.clone());4445 println!("Saga {} started", saga_id);4647 // Execute saga steps48 match execute_saga_steps(&ctx, &mut state, &order).await {49 Ok(_) => {50 println!("Saga {} completed successfully", saga_id);51 Ok(OrderResult {52 order_id: order.order_id,53 success: true,54 payment_id: state.payment_id,55 inventory_id: state.inventory_id,56 shipment_id: state.shipment_id,57 })58 }59 Err(e) => {60 println!("Saga {} failed: {}, starting compensation", saga_id, e);61 state.failed = true;6263 // Execute compensation64 compensate_saga(&ctx, &state).await?;6566 Ok(OrderResult {67 order_id: order.order_id,68 success: false,69 payment_id: None,70 inventory_id: None,71 shipment_id: None,72 })73 }74 }75}7677async fn execute_saga_steps(78 ctx: &WorkflowContext,79 state: &mut SagaState,80 order: &OrderData,81) -> Result<()> {82 // Step 1: Reserve inventory83 state.current_step = 1;84 let inventory_id: String = ctx85 .execute_task(reserve_inventory, order.items.clone())86 .await?;8788 state.inventory_reserved = true;89 state.inventory_id = Some(inventory_id);90 state.completed_steps.push("inventory_reserved".to_string());9192 // Step 2: Charge payment93 state.current_step = 2;94 let payment_id: String = ctx95 .execute_task(charge_payment, order.amount)96 .await?;9798 state.payment_captured = true;99 state.payment_id = Some(payment_id);100 state.completed_steps.push("payment_captured".to_string());101102 // Step 3: Create shipment103 state.current_step = 3;104 let shipment_id: String = ctx105 .execute_task(create_shipment, order.order_id.clone())106 .await?;107108 state.shipment_created = true;109 state.shipment_id = Some(shipment_id);110 state.completed_steps.push("shipment_created".to_string());111112 Ok(())113}114115async fn compensate_saga(ctx: &WorkflowContext, state: &SagaState) -> Result<()> {116 println!("Compensating saga {}", state.saga_id);117118 // Compensate in reverse order119 if state.shipment_created {120 if let Some(ref shipment_id) = state.shipment_id {121 println!("Canceling shipment");122 ctx.execute_task(cancel_shipment, shipment_id.clone()).await?;123 }124 }125126 if state.payment_captured {127 if let Some(ref payment_id) = state.payment_id {128 println!("Refunding payment");129 ctx.execute_task(refund_payment, payment_id.clone()).await?;130 }131 }132133 if state.inventory_reserved {134 if let Some(ref inventory_id) = state.inventory_id {135 println!("Releasing inventory");136 ctx.execute_task(release_inventory, inventory_id.clone()).await?;137 }138 }139140 println!("Compensation completed for saga {}", state.saga_id);141 Ok(())142}