Saga Design Pattern

19 Jan 2025

[ design  development  ]

Context

Problem

Solution

Concepts

Compensable transactions

Transactions that other transactions can undo or compensate for with the opposite effect.

Pivot transaction

Once the pivot transaction succeeds, compensable transactions (which could be undone) are no longer relevant.

Retryable transactions

Idempotent and ensure that the saga can reach its final state, even if temporary failures occur. It guarantees that the saga achieves a consistent state eventually.

Choreography-based saga

Orchestration-based saga

Versioning

Benefits

Choreography

Orchestration

Drawbacks

Choreography

Orchestration

Challenges

Rolling back changes when an error happens within a Saga.

Requires compensating transactions.

Lost Updates

One saga overwrites an update made by another saga.

Dirty Reads

One saga reads data that is in the middle of being updated by another saga.

Fuzzy / Non-repeatable Reads

Two different sets of a saga read the same data and get different results because another saga has made updates.

Design considerations

Asynchronous flow

  1. The service sends back a response once the saga completes.
  2. The service sends back a response after initiating the saga and the client periodically polls to determine the outcome
  3. The service sends back a response after initiating the saga, and then sends an event to the client once the saga completes.

A service must atomically update its database and publish a message/event.

Compensating transactions

Should be designed to explicitly undo changes made earlier in a saga rather than relying on the automatic rollback feature of ACID transactions. They may not always succeed.

Semantic Lock

Use application-level locks where a saga’s compensable transaction uses a semaphore to indicate an update is in progress.

Commutative Updates

Designing the system to have more its update operations to be commutative (updates in an orderly manner). This can basically eliminate lost updates.

Pessimistic View

Reordering saga participants/services to minimize the effect of dirty reads.

Reread Values

This countermeasure reread values before updating it to further to re-verify the values are unchanged during the process. This will minimize lost updates.

Version files

Maintain a log of all operations on a record and ensure they’re executed in the correct sequence to prevent conflicts.

By Value

This strategy will select concurrency mechanisms based on the business risk. This can help to execute low-risk requests using sagas and execute high-risk requests using distributed transactions.

References