Parallel Saga with Compensation
Parallel Saga with Compensation
When saga steps are independent of each other, you can execute them in parallel to reduce total execution time. If any branch fails, all successful branches are compensated. This pattern is ideal when you need to reserve resources across multiple services simultaneously — such as booking a flight, hotel, and car rental at the same time — where none of the services depend on the others' results.
Book Trip
parallel execution
Flight
✓ Reserve seat
Hotel
✗ Reserve room
Car
✓ Reserve rental
hotel failed → compensate
Cancel flight
↩ refund
Cancel car
↩ refund
1use orcher::prelude::*;2use anyhow::Result;3use futures::future::join_all;45#[derive(Debug, Clone, Serialize, Deserialize)]6struct MultiServiceOrder {7 order_id: String,8 services: Vec<String>,9}1011#[derive(Debug, Clone, Serialize, Deserialize)]12struct ParallelSagaResult {13 order_id: String,14 successful_services: Vec<String>,15 failed_services: Vec<String>,16 success: bool,17}1819// Parallel saga with compensation20#[workflow(name = "parallel_saga", version = "1.0.0")]21pub async fn parallel_saga(22 ctx: WorkflowContext,23 order: MultiServiceOrder,24) -> Result<ParallelSagaResult> {25 println!("Starting parallel saga for {}", order.order_id);2627 let mut successful = Vec::new();28 let mut failed = Vec::new();29 let mut compensation_ids = Vec::new();3031 // Execute all services in parallel32 let mut task_futures = Vec::new();33 for service in &order.services {34 let task = ctx.execute_task(35 execute_service,36 (service.clone(), order.order_id.clone()),37 );38 task_futures.push((service.clone(), task));39 }4041 // Wait for all results42 for (service, task) in task_futures {43 match task.await {44 Ok(result_id) => {45 successful.push(service.clone());46 compensation_ids.push((service, result_id));47 }48 Err(e) => {49 println!("Service {} failed: {}", service, e);50 failed.push(service);51 }52 }53 }5455 // If any failed, compensate all successful ones56 if !failed.is_empty() {57 println!("Parallel saga failed, compensating {} services", successful.len());5859 let mut compensation_tasks = Vec::new();60 for (service, result_id) in compensation_ids {61 let task = ctx.execute_task(62 compensate_service,63 (service, result_id),64 );65 compensation_tasks.push(task);66 }6768 let results = join_all(compensation_tasks).await;69 for result in results {70 if let Err(e) = result {71 println!("Compensation failed: {}", e);72 }73 }7475 return Ok(ParallelSagaResult {76 order_id: order.order_id,77 successful_services: Vec::new(),78 failed_services: failed,79 success: false,80 });81 }8283 println!("Parallel saga completed successfully");84 Ok(ParallelSagaResult {85 order_id: order.order_id,86 successful_services: successful,87 failed_services: failed,88 success: true,89 })90}