Saga Distributed Transactions Pattern
Saga Distributed Transactions Pattern
Azure
The Saga design pattern is a way to manage data consistency across microservices in
distributed transaction scenarios. A saga is a sequence of transactions that updates
each service and publishes a message or event to trigger the next transaction step. If
a step fails, the saga executes compensating transactions that counteract the
preceding transactions.
In multiservices architectures:
Distributed transactions like the two-phase commit (2PC) protocol require all
participants in a transaction to commit or roll back before the transaction can
proceed. However some participant implementations, such as NoSQL databases and
message brokering, don't support this model.
Another distributed transaction limitation is interprocess communication
(IPC) synchronicity and availability. Operating system-provided IPC allows separate
processes to share data. For distributed transactions to commit, all participating
services must be available, potentially reducing overall system availability.
Architectural implementations with IPC or transaction limitations are candidates for
the Saga pattern.
Solution
The Saga pattern provides transaction management using a sequence of local
transactions. A local transaction is the atomic work effort performed by a saga
participant. Each local transaction updates the database and publishes a message or
event to trigger the next local transaction in the saga. If a local transaction fails, the
saga executes a series of compensating transactions that undo the changes that were
made by the preceding local transactions.
In Saga patterns:
Choreography
Benefits
Good for simple workflows that require few participants and don't need
a coordination logic.
Doesn't require additional service implementation and maintenance.
Doesn't introduce a single point of failure, since the responsibilities are
distributed across the saga participants.
Drawbacks
Workflow can become confusing when adding new steps, as it's difficult
to track which saga participants listen to which commands.
There's a risk of cyclic dependency between saga participants because
they have to consume each other's commands.
Integration testing is difficult because all services must be running to
simulate a transaction.
Orchestration
Benefits
Drawbacks
Lost updates, when one saga writes without reading changes made by
another saga.
Dirty reads, when a transaction or a saga reads updates made by a saga
that has not yet completed those updates.
Fuzzy/nonrepeatable reads, when different saga steps read different data
because a data update occurs between the reads.
Example
Orchestration-based Saga on Serverless is a saga implementation reference using the
orchestration approach that simulates a money transfer scenario with successful and
failed workflows.
Related patterns
The following patterns might also be useful when implementing this pattern: