How to do 2 phase commit between two micro-services(Spring-boot)?

12.3k views Asked by At

I Have two mico-serives A and B where they connect to seperate database, From Mico-serives A i need to persist(save) objects of both A and B in same transtation how to achive this.

I am using Spring micro-servies with netflix-oss.Please give suggestions on best way to do achive 2 phase commit.

3

There are 3 answers

3
Touraj Ebrahimi On BEST ANSWER

you can not implement traditional transaction system in micro-services in a distributed environment.

You should you Event Sourcing + CQRS technique and because they are atomic you will gain something like implementing transactions or 2PC in a monolithic system.

Other possible way is transaction-log-mining that I think linked-in is using this way but it has its own cons and pros. for e.g. binary log of different databases are different and event in same kind of database there are differences between different versions.

I suggest that you use Event Sourcing + CQRS and string events in an event-store then try reaching eventual consistency base on CAP theorem after transferring multiple events between micro-service A and B and updating domain states in each step.

It is suggested that you use a message broker like ActiveMQ, RabbitMQ or Kafka for sending event-sourced events between different microservices and string them in an event store like mysql or other systems.

Another benefit of this way beside mimicking transactions is that you will have a complete audit log.

0
barbakini On

It is an architecture(microservices) problem. Spring boot or netflix-oss do not offer a direct solution. You have to implement your own solution. Check with event driven architecture. It can give you some ideas.

0
TXdev On

You could try the SAGA pattern https://microservices.io/patterns/data/saga.html