Guides

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
1
use orcher::prelude::*;
2
use anyhow::Result;
3
use futures::future::join_all;
4
5
#[derive(Debug, Clone, Serialize, Deserialize)]
6
struct MultiServiceOrder {
7
order_id: String,
8
services: Vec<String>,
9
}
10
11
#[derive(Debug, Clone, Serialize, Deserialize)]
12
struct ParallelSagaResult {
13
order_id: String,
14
successful_services: Vec<String>,
15
failed_services: Vec<String>,
16
success: bool,
17
}
18
19
// Parallel saga with compensation
20
#[workflow(name = "parallel_saga", version = "1.0.0")]
21
pub async fn parallel_saga(
22
ctx: WorkflowContext,
23
order: MultiServiceOrder,
24
) -> Result<ParallelSagaResult> {
25
println!("Starting parallel saga for {}", order.order_id);
26
27
let mut successful = Vec::new();
28
let mut failed = Vec::new();
29
let mut compensation_ids = Vec::new();
30
31
// Execute all services in parallel
32
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
}
40
41
// Wait for all results
42
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
}
54
55
// If any failed, compensate all successful ones
56
if !failed.is_empty() {
57
println!("Parallel saga failed, compensating {} services", successful.len());
58
59
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
}
67
68
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
}
74
75
return Ok(ParallelSagaResult {
76
order_id: order.order_id,
77
successful_services: Vec::new(),
78
failed_services: failed,
79
success: false,
80
});
81
}
82
83
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
}

Next Steps