Module 5 - Architecture Patterns

Saga Pattern

Manage distributed transactions across microservices without 2PC.

1The Travel Booking Analogy

Simple Analogy
Booking a trip: you reserve flight, hotel, car. If the car fails, you cancel hotel and flight (compensating actions). Each step is independent but coordinated. A saga is a sequence of local transactions with compensations for rollback.

A Saga is a sequence of local transactions. Each transaction updates a service and publishes an event. If one fails, compensating transactions undo previous steps.

2Why Not 2PC?

Two-Phase Commit (2PC)

  • ✗ Locks resources across services
  • ✗ Single coordinator is SPOF
  • ✗ Doesn't scale well
  • ✗ High latency

Saga

  • ✓ No distributed locks
  • ✓ Each step is local transaction
  • ✓ Scales with microservices
  • ✓ Eventual consistency

3Two Saga Types

Choreography

Each service publishes events that trigger the next step. No central coordinator. Decentralized but can get complex.

Orchestration

Central orchestrator tells each service what to do. Easier to understand but single point of coordination.

4Compensation

Each saga step has a compensating transaction that undoes its work. If step 3 fails, run compensations for steps 2, 1 in reverse order.

1. Reserve InventoryRelease Inventory
2. Charge PaymentRefund Payment
3. Ship OrderCancel Shipment

5Key Takeaways

1Saga = sequence of local transactions with compensations
2Avoids distributed locks of 2PC
3Choreography: event-driven, decentralized
4Orchestration: central coordinator
5Each step needs a compensating transaction for rollback

?Quiz

1. Order saga: inventory reserved, payment fails. What happens?

2. Orchestration saga has: