Hi, Habr! I present to your attention the translation of the article "Pattern: Saga" by Chris Richardson.
There is an application to which the Database per Service pattern was applied. Now each application service has its own database. Some business transactions cover several services at once, so a mechanism is needed to ensure consistency of data between these services.
For example: let's imagine that we are developing an online store where the client has a credit limit. The application must ensure that the new order does not exceed the customer's credit limit. Since Orders and Clients are different databases, the application cannot use local ACID transactions.
How to ensure data consistency between services?
It is necessary to implement each business transaction that covers several services as a saga.
The saga is a collection of local transactions. Each local transaction updates the database and publishes a message or event, initiating the next local transaction in the saga. If a transaction fails, for example, because of a violation of business rules, then the saga launches offsetting transactions that roll back the changes made by previous local transactions.
There are two ways to coordinate sagas:
In an online store using a saga based on choreography, creating an order will include the following steps:
Order Service ( )
creates an Order ()
in the status of pending (pending) and publishes an event OrderCreated ()
Customer Service ( )
receives the event and attempts to reserve a loan for the order. After that, it publishes one of two events: CreditReserved ()
or CreditLimitExceeded ()
Order Service ( )
receives the event and changes the status of the order to approved ( canceled ) or canceled.In an online store using an orchestration-based saga, order creation will include the following steps:
Order Service ( )
creates an Order ()
in pending (pending) status and creates CreateOrderSaga ()
CreateOrderSaga ()
sends the ReserveCredit ()
team ReserveCredit ()
to the Customer Service ( )
Customer Service ( )
tries to reserve a loan for the order and sends back an answer.CreateOrderSaga ()
receives a response and sends an ApproveOrder ()
Order Service ( )
ApproveOrder ()
or RejectOrder ()
Order Service ( )
RejectOrder ()
command in the Order Service ( )
Order Service ( )
changes the order status to approved (confirmed) or canceled.Source: https://habr.com/ru/post/427705/
All Articles