Problem
When each
service has its own database and a business transaction spans multiple
services, how do we ensure data consistency across services? For example, for
an e-commerce application where customers have a credit limit, the application
must ensure that a new order will not exceed the customer’s credit limit. Since
Orders and Customers are in different databases, the application cannot simply
use a local ACID transaction.
Solution
The
Saga pattern is the solution to implementing business transactions spanning
multiple microservices.
A Saga is basically a sequence of local transactions. For every transaction performed within a Saga, the service performing the transaction publishes an event. The subsequent transaction is triggered based on the output of the previous transaction. And if one of the transactions in this chain fails, the Saga executes a series of compensating transactions to undo the impact of all the previous transactions. It can be implemented in two ways:
- Choreography
— When there
is no central coordination, each service produces and listens to another
service’s events and decides if an action should be taken or not.
- Orchestration — An orchestrator (object)
takes responsibility for a saga’s decision making and sequencing business
logic.
The
Saga pattern is one of the microservice design patterns that allow you to
manage such transactions using a sequence of local transactions. Each
transaction is followed by an event that triggers the next transaction step.
If
one transaction fails, the saga pattern triggers a rollback transaction
compensating for the failure.
Here’s
an example of an eCommerce application that consists of multiple transactions
for orders, payment, inventory, shipping, and notifications. Once an order is
generated for a specific product, the next transaction for the payment and the
inventory update is initialized.
If
the transaction for inventory update fails, for example, due to unavailability
of a product, a rollback is triggered. If the transaction for inventory update
is successful further transactions are initialized.
Moreover,
Saga transactions don’t need to know about the command or the role of other
transactions. This allows developers to build simplified business logic with
clear separation of concerns.
This
pattern is suggested for applications where ensuring data consistency is
critical without tight coupling. Likewise, it’s less suitable for applications
with tight coupling.
No comments:
Post a Comment