Saga

  • https://learn.microsoft.com/en-us/azure/architecture/patterns/saga
  • Sequence of Local transactions
  • Use events b/w microservices
  • Assume a transaction has to happen involving 3 microservices with their own 3 different DBs
    • For each microservice if the operations succeeds, it sends a success event to the next microservice
    • If some microservice fails in Tx then failure event is sent back to previous microservices
    • Failure event causes rollback of the operations (compensation Tx) done so far
  • Concepts
    • Compensating Tx
      • a new Tx to undo changes of original Tx
    • Pivot Tx:
      • Point of no return
      • Last undoable Tx
      • First Retryable Tx
    • Retryable Tx:
      • Follow the Pivot Tx
      • They are idempotent
      • Help the saga eventually achieve a consistent state.
  • Types of SAGA implementation
    • Choreography
    • Orchestrator
  • Data Anomalies
    • Lost Updates
    • Dirty Reads
    • Non-repeatable reads
  • Use cases:
    • Payment Systems
      • debit from one account, credit to another, rollback on failure
    • Flight Reservation
      • reserve seat, charge payment, confirm booking; if payment fails → cancel seat
    • Hotel Booking
      • book room, charge payment, confirm; if cancel → refund & release room

Choreography

  • exchange events without a centralized controller
  • each local Tx publishes domain events that trigger local Tx in other services

Orchestrator

  • A centralized controller, or orchestrator, handles all the Tx
  • It tells the participants which operation to perform based on events
  • It stores the states of each task, and handles failure recovery by using compensating transactions.
ChoreographyOrchestrator
Useful for simpler workflowsBetter for complex workflows
No other service required for coordinationSeparate Orchestrator required
No Single Point of failureIntroduces a single point of failure
Risk of cyclic dependencyAvoid cyclic dependencies

Saga vs Two Phase Commit

Two Phase Commit (2PC)Saga
CoordinationCentral CoordinatorChoreographed or Orchestrated
CommunicationSyncAsync
AtomicityStrongEventual Consistency,
uses compensating Tx
FlexibilityLess FlexibleMore Flexible
PerformanceSlower, Participants waitFaster, independent operations