The first sentence of the article: “This article has participated in the weekend learning plan, click to view the details”


This article is a study of Mr. MAO’s notes on distributed transactions.

Under singleton, a single service encapsulates operations on multiple database tables in a transaction by operating on the local database:

begintransaction; update a set... ; update b set... ;end transaction
Copy the code

A single database, guaranteed by the ACID of the database itself.

In microservice architecture, each microservice monopolizes a database, and an operation spans multiple services, and it is difficult to guarantee the success of calling the services of multiple systems at the same time, which is the problem of cross-service distributed transactions.

Solve distributed transaction problems through transaction messages. “Sacrificing consistency for increased concurrency”

How do I save message credentials reliably?

  • Transactional outbox
  • Polling publisher
  • Transaction log retailing
  • 2PC Message Queue

Transactional outbox

A records the message data while completing the deduction. Message data and business data are stored in the same database instance:

BEGIN TRANSACTION
    UPDATE A SET amount = amount - 10000 WHERE user_id = 1;
    INSERT INTO msg(user_id, amount, status) VALUES(1.10000.1);
END TRANSACTION
COMMIT;
Copy the code

In a transaction can be guaranteed as long as the alipay account deducted money, the message can be saved.

All that remains is that B must consume the message, reply with a success message (callback), and then delete the message data (is_delete=1).

Polling publisher

Polling publisher, we regularly train the MSG table and take out all the messages with status = 1 for consumption. We can sort them according to the self-increased ID to ensure the consumption order.

Here we have a separate pay_task service that publishes the dragged messages to our message queue, and the Balance service either consumes the queue itself or sends RPC directly to the Balance service.


To be continued… In the next article, there are several other ways to do this…