Guides

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
1validate_order
state.order_id
2reserve_inventory
state.reservation_id
3process_payment
state.payment_id
4arrange_shipping
state.shipment_id
success
Commit
Return result
any step fails
compensate(state)
Undo in reverse order
1
use orcher::prelude::*;
2
use anyhow::Result;
3
use serde::{Deserialize, Serialize};
4
5
#[derive(Debug, Clone, Serialize, Deserialize)]
6
struct 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
}
18
19
impl 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
}
35
36
// Saga coordinator workflow
37
#[workflow(name = "saga_coordinator", version = "1.0.0")]
38
pub 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());
44
45
println!("Saga {} started", saga_id);
46
47
// Execute saga steps
48
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;
62
63
// Execute compensation
64
compensate_saga(&ctx, &state).await?;
65
66
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
}
76
77
async fn execute_saga_steps(
78
ctx: &WorkflowContext,
79
state: &mut SagaState,
80
order: &OrderData,
81
) -> Result<()> {
82
// Step 1: Reserve inventory
83
state.current_step = 1;
84
let inventory_id: String = ctx
85
.execute_task(reserve_inventory, order.items.clone())
86
.await?;
87
88
state.inventory_reserved = true;
89
state.inventory_id = Some(inventory_id);
90
state.completed_steps.push("inventory_reserved".to_string());
91
92
// Step 2: Charge payment
93
state.current_step = 2;
94
let payment_id: String = ctx
95
.execute_task(charge_payment, order.amount)
96
.await?;
97
98
state.payment_captured = true;
99
state.payment_id = Some(payment_id);
100
state.completed_steps.push("payment_captured".to_string());
101
102
// Step 3: Create shipment
103
state.current_step = 3;
104
let shipment_id: String = ctx
105
.execute_task(create_shipment, order.order_id.clone())
106
.await?;
107
108
state.shipment_created = true;
109
state.shipment_id = Some(shipment_id);
110
state.completed_steps.push("shipment_created".to_string());
111
112
Ok(())
113
}
114
115
async fn compensate_saga(ctx: &WorkflowContext, state: &SagaState) -> Result<()> {
116
println!("Compensating saga {}", state.saga_id);
117
118
// Compensate in reverse order
119
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
}
125
126
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
}
132
133
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
}
139
140
println!("Compensation completed for saga {}", state.saga_id);
141
Ok(())
142
}

Next Steps