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.
Reserve inventory✓Charge payment✓Ship order✓Reserve inventory✓Charge payment✓Ship order✗Refund payment↩Release inventory↩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
Sagahelper — 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(ormatch) 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.
1use orcher::prelude::*;2use orcher::workflow::Saga;34#[workflow(name = "book_trip", version = "1.0.0")]5pub async fn book_trip(ctx: WorkflowContext, req: TripRequest) -> Result<Confirmation> {6 let mut saga = Saga::new();78 // Fluent: run the action and register a static compensation. If a later9 // step fails, registered compensations run in reverse order automatically.10 let hotel: Booking = saga11 .add_step(&ctx, book_hotel, req.clone())12 .with_compensation(cancel_hotel)13 .execute()14 .await?;1516 // 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());1920 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.
1use orcher::prelude::*;2use anyhow::Result;3use serde::{Deserialize, Serialize};45#[derive(Debug, Clone, Serialize, Deserialize)]6struct OrderData {7 order_id: String,8 customer_id: String,9 amount: f64,10 items: Vec<String>,11}1213#[derive(Debug, Clone, Serialize, Deserialize)]14struct OrderResult {15 order_id: String,16 success: bool,17 payment_id: Option<String>,18 inventory_id: Option<String>,19 shipment_id: Option<String>,20}2122// Basic saga workflow with compensation23#[workflow(name = "order_saga", version = "1.0.0")]24pub async fn order_saga(25 ctx: WorkflowContext,26 order: OrderData,27) -> Result<OrderResult> {28 println!("Starting order saga for {}", order.order_id);2930 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 };3738 // Step 1: Reserve inventory39 let inventory_id = match ctx40 .execute_task(reserve_inventory, order.items.clone())41 .await42 {43 Ok(id) => {44 result.inventory_id = Some(id.clone());45 id46 }47 Err(e) => {48 println!("Inventory reservation failed: {}", e);49 return Ok(result);50 }51 };5253 // Step 2: Charge payment54 let payment_id = match ctx55 .execute_task(charge_payment, order.amount)56 .await57 {58 Ok(id) => {59 result.payment_id = Some(id.clone());60 id61 }62 Err(e) => {63 println!("Payment failed, compensating inventory");64 // Compensate: Release inventory65 ctx.execute_task(release_inventory, inventory_id).await?;66 return Ok(result);67 }68 };6970 // Step 3: Create shipment71 let shipment_id = match ctx72 .execute_task(create_shipment, order.order_id.clone())73 .await74 {75 Ok(id) => {76 result.shipment_id = Some(id.clone());77 id78 }79 Err(e) => {80 println!("Shipment failed, compensating payment and inventory");81 // Compensate: Refund payment82 ctx.execute_task(refund_payment, payment_id).await?;83 // Compensate: Release inventory84 ctx.execute_task(release_inventory, inventory_id).await?;85 return Ok(result);86 }87 };8889 result.success = true;90 println!("Order saga completed successfully");91 Ok(result)92}Next Steps
Saga Coordinator Pattern
Encapsulate state tracking and compensation logic into a dedicated coordinator
Parallel Saga
Execute independent saga steps in parallel to reduce total execution time
Forward Recovery
Retry failed steps with increasing delays instead of compensating
Event-Driven Saga
Coordinate saga steps through external events and confirmations
Best Practices & Pitfalls
Idempotency, compensation order, performance, and common mistakes to avoid