Data Consistency for Microservices

Under the microservice architecture, each service corresponds to a database, which means that the operation of the same library in the original monomer becomes the operation of the cross-service database.
When encountering scenarios with transaction constraints, such as transfer and remittance, order status and inventory deduction, the transition from local transactions to distributed transactions comes. 
 
Microservices solve this problem with eventual consistency
 
Final consistency: After a period of time between different service nodes, the data between the nodes will eventually reach a consistent state
There are two ways to accomplish eventual consistency:

1. Reliability time mode

Pre-order events occur, and post-order events must occur. The disadvantage of reliability events is that they cannot be rolled back. It is generally done with the help of message queues and internal tables.

An example of transferring Alipay balance to Yu'ebao balance: 
When initiating a request to the Alipay service, Alipay will execute the deduction event, record the event, and send a message to the Yu'ebao service. After that, Yu'ebao executes the add-on event and delivers the message to the Alipay service, and the Alipay service Delete the event record after getting this message. If the Yu'ebao service fails, and the Alipay service has not received the returned message, the scheduled task will detect that the event has always existed in the database, and will continue to send the message to Yu'ebao until the Yu'ebao service resumes the payment and sends a message to Alipay to delete the record.
 

2. Compensation transaction-sagsas model

A sag is a sequence of ordered local transactions, each local transaction triggers the next local transaction by updating the database or sending a message.
Each local transaction will send a message and confirm the message. If the local transaction fails, the sag will execute the compensation transaction in an orderly manner to roll back the previous operation. Its characteristic is to support rollback.
 
Every transaction has operations for sending messages and receiving confirmation messages
This scheme is relatively complex, and there is no open source framework to support it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325169636&siteId=291194637