QA
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→

More System Design & Architecture Interview Questions

Beginner LevelSystem Design & Architecture

Explain the CAP Theorem and PACELC Theorem with real-world database examples.

Beginner LevelSystem Design & Architecture

What is Vertical Scaling (Scale Up) vs Horizontal Scaling (Scale Out)?

Beginner LevelSystem Design & Architecture

How do Load Balancers distribute traffic (Round Robin, Least Connections, IP Hash)?