SAGA pattern

SAGA Pattern

Objective is to ensure data consistency across microservices that own the data and database platform.

Allows execution of distributed business transactions, executing a set of operations across multiple microservices , applying all or nothing semantics

Distributed transactions = Using Local Transactions coupled with compensating transactions

Think of SAGA like a Pipeline where each step is executed independent of the other step but in a sequence defined in/by the pipeline This continues till ALL steps have succeeded or one of the steps fails

  1. Each microservice subscribes to events from prior stage microservice
    • On receiving an event, microservice, initiates a Local Transaction (T1, T2, T3)
  2. Each microservice also builds a compensating transactions that rolls back the effect of a transaction
    • In case of local transaction failure, microservice:
      1. Initiates the compensating transaction
      2. Emits event informing prior stage of the rollback
      3. Prior stage on receiving the event initiates compensating transaction
  3. Either ALL local transactions are successful OR
    • One or more microservices initiate the compensating transactions

failed-shipment

Example

This illustration shows the SAGA implentation for an eCommerce system that uses EDA. Each microservice implements the:

  • Local transaction (T1, T2, T3)
  • Compensating transaction (C1, C2, C3)

failed-shipment

SAGA Considerations

  • Eventual consistency eventually-consistent

  • No Isolation = Intermediate state is visible. SAGA provides isolation level = READ Uncommitted

  • Transaction & Compensations must be idempotent

  • Commutative transactions

  • Transactions & Compensation MUST not be impacted by duplicate events