javaspring-bootweb-servicesmicroservicesxa

Distributed transaction rollback with Spring-Boot


I am learning distributed transaction rollback with Spring-Boot. I am using spring-boot 2.2 with JPA and H2 database. In my example, I have three micro-services which are running on different ports, with their own H2 database.

MicroserviceA --- http://localhost:2222/savePersonBasicDetails
MicroserviceB --- http://localhost:3333/savePersonAddress
MicroserviceC --- http://localhost:4444/savePersonHobbies

From the MicroserviceA, I will get Person_Id, which I will send to the remaining two microservices along with their respective data. If any of the microservices fails, then I want to roll back the complete transaction.

Example:

save(PersonVO personVO) {

Integer personId = microserviceA.savePersonBasicDetails(personVO);

microserviceB.savePersonAddress(personId, personVO);

microserviceC.savePersonHobbies(personId, personVO);//If it fails in microserviceC,     

                                              //then the complete transaction should be rolled back.

}

I tried with @Transactional(rollbackFor = Exception.class) on the save() method, but the transaction is not rolling back.

Please suggestion.


Solution

  • You are mixing the terms. Distributed transaction is a term associated with RDBMS, not with webservices. There is a webservice standard for transactions over webservice WS-TRANSACTION relevant to soap webservices. But this standard is mostly unused.

    The usualy therm used in context of web services is Transaction Compensation and you can search it. A very common pattern for compensation is the Try Cancel Confirm pattern, there are also different aproaches.

    If you insist on using distributed transactions check out this link: https://www.atomikos.com/Blog/TransactionalRESTMicroservicesWithAtomikos