Guides

Saga & Compensation Pattern


The Saga pattern enables you to implement distributed transactions across multiple services without using distributed locks or two-phase commit. A saga is a sequence of local transactions where each step updates a single service. If any step fails, the saga executes compensating transactions to undo the impact of all preceding steps — maintaining eventual consistency across your system. Key concepts include forward recovery (retrying failed steps until they succeed), backward recovery (undoing completed steps on failure), idempotent compensation actions (safe to retry), and eventual consistency (the system reaches a consistent state, though not immediately). Use sagas when you need to coordinate multiple services that each own their own data, handle long-running operations spanning minutes or hours, or avoid distributed locks and two-phase commit protocols.

Success Path
all steps complete
1Reserve inventory✓
2Charge payment✓
3Ship order✓
Done
Failure Path
step 3 fails → compensate
1Reserve inventory✓
2Charge payment✓
3Ship order✗
compensate ↩
2Refund payment↩
1Release inventory↩
Rolled back

Two ways to build a saga

Orcher gives you two ways to run a saga, and you can mix them in the same workflow:

  • The Saga helper — register each step with its compensation as you go, and the helper runs the compensations in reverse order if a later step fails. Best for most sagas.
  • Manual compensation — write the try/catch (or match) yourself and undo prior steps by hand. Best when you want full control over ordering, partial rollback, or conditional compensation.

Both are built on the same foundation: every action and every compensation is an ordinary task, so each step and each rollback is durable and survives crashes.

The Saga helper

The helper tracks completed steps and their compensations. There are two ways to register a step, and the difference matters:

  • add_step(action, compensation) runs the action and registers a compensation that doesn't need the action's result.
  • add_compensation(...) registers a compensation for an action you ran yourself — use it when the compensation needs the action's output (a charge id, a booking reference).

Call commit() when every step succeeds. On failure, the registered compensations run in reverse order (LIFO). In Python and TypeScript, trigger them from your except/catch with saga.compensate() (it's idempotent); in Rust, the fluent .execute() compensates automatically.

1
use orcher::prelude::*;
2
use orcher::workflow::Saga;
3
4
#[workflow(name = "book_trip", version = "1.0.0")]
5
pub async fn book_trip(ctx: WorkflowContext, req: TripRequest) -> Result<Confirmation> {
6
let mut saga = Saga::new();
7
8
// Fluent: run the action and register a static compensation. If a later
9
// step fails, registered compensations run in reverse order automatically.
10
let hotel: Booking = saga
11
.add_step(&ctx, book_hotel, req.clone())
12
.with_compensation(cancel_hotel)
13
.execute()
14
.await?;
15
16
// Manual: the compensation needs the action's result (the charge id).
17
let charge = ctx.execute_task(charge_card, req.clone()).await?;
18
saga.add_compensation(refund_card, charge.id.clone());
19
20
saga.commit();
21
Ok(Confirmation { hotel_id: hotel.id, charge_id: charge.id })
22
}

Manual compensation

If you want full control — custom ordering, partial rollback, or conditional compensation — write the compensation yourself. Steps execute sequentially, and when one fails, each step's catch block undoes the previously completed steps in reverse order. It is more verbose than the helper, but nothing is hidden.

1
use orcher::prelude::*;
2
use anyhow::Result;
3
use serde::{Deserialize, Serialize};
4
5
#[derive(Debug, Clone, Serialize, Deserialize)]
6
struct OrderData {
7
order_id: String,
8
customer_id: String,
9
amount: f64,
10
items: Vec<String>,
11
}
12
13
#[derive(Debug, Clone, Serialize, Deserialize)]
14
struct OrderResult {
15
order_id: String,
16
success: bool,
17
payment_id: Option<String>,
18
inventory_id: Option<String>,
19
shipment_id: Option<String>,
20
}
21
22
// Basic saga workflow with compensation
23
#[workflow(name = "order_saga", version = "1.0.0")]
24
pub async fn order_saga(
25
ctx: WorkflowContext,
26
order: OrderData,
27
) -> Result<OrderResult> {
28
println!("Starting order saga for {}", order.order_id);
29
30
let mut result = OrderResult {
31
order_id: order.order_id.clone(),
32
success: false,
33
payment_id: None,
34
inventory_id: None,
35
shipment_id: None,
36
};
37
38
// Step 1: Reserve inventory
39
let inventory_id = match ctx
40
.execute_task(reserve_inventory, order.items.clone())
41
.await
42
{
43
Ok(id) => {
44
result.inventory_id = Some(id.clone());
45
id
46
}
47
Err(e) => {
48
println!("Inventory reservation failed: {}", e);
49
return Ok(result);
50
}
51
};
52
53
// Step 2: Charge payment
54
let payment_id = match ctx
55
.execute_task(charge_payment, order.amount)
56
.await
57
{
58
Ok(id) => {
59
result.payment_id = Some(id.clone());
60
id
61
}
62
Err(e) => {
63
println!("Payment failed, compensating inventory");
64
// Compensate: Release inventory
65
ctx.execute_task(release_inventory, inventory_id).await?;
66
return Ok(result);
67
}
68
};
69
70
// Step 3: Create shipment
71
let shipment_id = match ctx
72
.execute_task(create_shipment, order.order_id.clone())
73
.await
74
{
75
Ok(id) => {
76
result.shipment_id = Some(id.clone());
77
id
78
}
79
Err(e) => {
80
println!("Shipment failed, compensating payment and inventory");
81
// Compensate: Refund payment
82
ctx.execute_task(refund_payment, payment_id).await?;
83
// Compensate: Release inventory
84
ctx.execute_task(release_inventory, inventory_id).await?;
85
return Ok(result);
86
}
87
};
88
89
result.success = true;
90
println!("Order saga completed successfully");
91
Ok(result)
92
}

Next Steps