How to ensure atomicity of a method execution in spring boot?

Viewed 593

I have a method which calls some other methods too. These operations are NOT related to DB in any way. I am just executing some logic, making few API calls to some other external services and all. I want that all the operations must be rolled back if any exception occurs in any of the operation. How can I achieve that?

2 Answers

This might sound like an innocent question, but is in fact very tricky. What your asking for a is a distributed transaction among your API calls. For that the API counterparts would need to support something like "two-phased commit". The bottom line is: if your API providers don't support distributed transactions, you'll have to build something yourself. (Post some code, describe the method in more detail, and we'll help)

See eg. for more details: https://developers.redhat.com/blog/2018/10/01/patterns-for-distributed-transactions-within-a-microservices-architecture/, or just Google "distributed transaction service calls"

I am sorry that you have to handle it manually. For example, if exception happens , manually apply a compensation action to undo .

A pattern called saga pattern is intended for solving such problems , I quote its basic idea from this as below:

The Saga pattern describes how to solve distributed (business) transactions without two-phase-commit as this does not scale in distributed systems. The basic idea is to break the overall transaction into multiple steps or activities. Only the steps internally can be performed in atomic transactions but the overall consistency is taken care of by the Saga. The Saga has the responsibility to either get the overall business transaction completed or to leave the system in a known termination state. So in case of errors a business rollback procedure is applied which occurs by calling compensation steps or activities in reverse order.

Related