“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.”
Managing distributed multi-service transactions without blocking Two-Phase Commit (2PC) using compensating rollback actions.
// 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();
}
}
}Order Service creates Order in PENDING status; invokes Saga Coordinator
Step 1: Inventory Service reserves items (Local Tx 1)
Step 2: Payment Service attempts credit card charge (Local Tx 2)
Failure Occurs: Payment declined due to insufficient funds
Compensating Actions: Saga Coordinator invokes Inventory Service to release reserved stock and updates Order status to CANCELLED
Orchestrator Sagas centralize failure state management into a finite state machine (FSM), avoiding cyclical event loops inherent in complex choreography.