Microservice - Data Consistency

发布时间 2023-11-13 18:55:15作者: ZhangZhihuiAAA

To have data consistency in a distributed system, you have two options: a two-phase commit (2PC) and saga.

 

2PC coordinates all the processes that form distributed atomic transactions and determines whether they should be committed or aborted.

 

 

A saga is a sequence of local transactions that updates each service and publishes another message to trigger another local transaction on the next service. Because transaction steps are spanned across the services, they cannot be handled with an annotation or two lines of code. However, there are widely used practices with saga, so you don’t need to reinvent the wheel for your use cases. Choreography- and orchestrator-based sagas are the most popular patterns for interservice communication to have consistent data.

 

A choreography-based saga is a pattern in which each service executes its local transaction and publishes an event to trigger the next service to execute its local transaction.
Whenever a saga is created, it can be completed in the following patterns:
 Service returns the result to the client once the saga is completed. It receives an event to update its domain object’s status as succeeded or failed.
 A saga is created, and the client starts to poll the next service to get either a succeeded or failed response. The unique identifier to start polling should be directly returned when the saga is created.
 A saga is created, and the client uses a WebSocket connection in which the service sends the result back using WebSocket protocol. A saga will be completed once the succeeded or failed result is returned.

Service communications over queue can be handled in two ways:
 Command channels—The publisher sends a message directly to the next service with a replyToChannel parameter so that it can notify the consumer once it completes the operation and commits the transaction. The main drawback of this pattern is that the publisher needs to know the location of the next service.

 Pub/sub mechanism—The publisher publishes a domain event, and interested consumers can consume messages to process and commit a local transaction. The main disadvantage of this notation is that it is a possible single point of failure since all the subscribers use one broker technology and all the events are sent to consumers.

 

An orchestration-based saga consists of an orchestrator and participants, and the orchestrator tells participants what to do. The orchestrator can communicate with participants using a command channel or request/response style. It connects participants individually to tell them to execute their local transactions and decides the next step based on this response.