Intermediate LevelSystem Design & Architecture
How does the Saga Pattern manage distributed transactions across microservices?
β Interview Prompt: Explain the Saga Pattern, Choreography vs Orchestration, local transactions, compensating actions, and eventual consistency.
The Saga Pattern manages distributed transactions across independent microservices without holding database locks:
Saga Mechanics:
A Saga executes a sequence of local transactions. Each local transaction updates a service database and emits an event to trigger the next step:
β’
Choreography: Microservices listen to events and execute steps independently.
β’
Orchestration: A central Saga Orchestrator coordinates transaction execution flow.
β’
Compensating Actions: If step 3 fails, the Saga executes rollback compensating actions in reverse order (e.g. 'RefundPayment' $\rightarrow$ 'CancelReservation').
Code Implementation Example
typescript
// Saga Orchestrator executing compensating actions on failure
export async function executeOrderSaga(orderId: string) {
try {
await inventoryService.reserveStock(orderId);
await paymentService.chargeCard(orderId); // Fails!
} catch (error) {
// Execute Compensating Action to rollback previous step!
await inventoryService.releaseStock(orderId);
throw new Error('Saga Failed: Order cancelled and stock released');
}
}π‘Executing compensating rollback actions in a Saga Orchestrator.
π― Interview Key Takeaway
Use the Saga Pattern with compensating actions to coordinate distributed microservice transactions eventually consistently.
#System Design#Saga Pattern#Distributed Transactions#Microservices#Intermediate
Back to all System Design & Architecture Questionsβ