Senior LevelREST APIs & Web Services
How does the Saga Pattern manage distributed transactions across microservice REST APIs?
❓ Interview Prompt: Explain Distributed Transactions, Saga Pattern, Choreography vs Orchestration (Temporal/Zeebe), local transactions, and Compensating Actions.
In microservice architectures where each service owns its database (Database-per-Service), 2-Phase Commit (2PC) ACID transactions do not scale. The Saga Pattern manages eventual consistency using a sequence of local transactions:
Compensating Actions:
If step 3 in an order pipeline fails (e.g. Payment failed), the Saga Orchestrator automatically invokes Compensating Actions in reverse order ('CANCEL_INVENTORY_RESERVATION', 'CANCEL_ORDER_RECORD') to roll back state!
Code Implementation Example
typescript
// Saga Orchestrator Compensating Workflow
async function executeOrderSaga(orderData: OrderPayload) {
const order = await orderService.create(orderData);
try {
const inventory = await inventoryService.reserve(order.id);
await paymentService.charge(order.id, orderData.amount);
} catch (err) {
// Compensation Rollback Execution!
await inventoryService.cancelReservation(order.id);
await orderService.updateStatus(order.id, 'CANCELLED');
throw new Error('Saga Failed: Rollback Compensations Executed');
}
}💡Saga Orchestration pattern executing compensating rollback actions on failure.
🎯 Interview Key Takeaway
Use the Saga pattern with compensating actions to maintain eventual consistency across distributed microservice REST APIs.
#Saga Pattern#Distributed Transactions#Microservices#Senior
Back to all REST APIs & Web Services Questions→