📜 ⬆️ ⬇️

Pattern: Saga

Hi, Habr! I present to your attention the translation of the article "Pattern: Saga" by Chris Richardson.


Situation


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.


Problem


How to ensure data consistency between services?


Decision


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:



Example: a saga based on choreography



In an online store using a saga based on choreography, creating an order will include the following steps:


  1. Order Service ( ) creates an Order () in the status of pending (pending) and publishes an event OrderCreated ()
  2. 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 ()
  3. Order Service ( ) receives the event and changes the status of the order to approved ( canceled ) or canceled.

Example: Orchestrated Saga



In an online store using an orchestration-based saga, order creation will include the following steps:


  1. Order Service ( ) creates an Order () in pending (pending) status and creates CreateOrderSaga ()
  2. CreateOrderSaga () sends the ReserveCredit () team ReserveCredit () to the Customer Service ( )
  3. Customer Service ( ) tries to reserve a loan for the order and sends back an answer.
  4. CreateOrderSaga () receives a response and sends an ApproveOrder () Order Service ( ) ApproveOrder () or RejectOrder () Order Service ( ) RejectOrder () command in the Order Service ( )
  5. Order Service ( ) changes the order status to approved (confirmed) or canceled.

The saga has the following advantages



The saga has the following disadvantages



')

Source: https://habr.com/ru/post/427705/


All Articles