Two-Phase Commit (2PC) does not scale in microservices due to synchronous locking. The Saga pattern models a long-running transaction as a sequence of local transactions across individual microservices. If any step fails (e.g. Payment Declined), the Saga executes Compensating Transactions in reverse order (e.g. Unreserve Inventory, Cancel Order) to restore eventual consistency.
Booking a vacation package (Flight, Hotel, Rental Car): if the rental car is sold out, you don’t lock the entire global travel database; you invoke cancellation policies to refund the hotel and flight reservations.
Orchestrator Sagas centralize failure state management into a finite state machine (FSM), avoiding cyclical event loops inherent in complex choreography.
Distributed Transactions & Sagas • advanced
// Saga Orchestrator FSM Workflow
interface SagaStep {
name: string;
forward: () => Promise<void>;
compensate: () => Promise<void>;
}
class OrderSagaOrchestrator {
private executedSteps: SagaStep[] = [];
async executeSaga(steps: SagaStep[]) {
for (const step of steps) {
try {
await step.forward();
this.executedSteps.push(step);
} catch (err) {
console.error(`Saga failed at step: ${step.name}. Triggering compensations...`);
await this.rollback();
throw new Error(`Saga Failed: ${err.message}`);
}
}
}
private async rollback() {
// Execute compensating actions in reverse topological order
for (const step of [...this.executedSteps].reverse()) {
await step.compensate();
}
}
}