2 years ago

#13536

test-img

Deepak Sharma

Spring boot @Transactional and @Async not working together

I am trying to make a function transactional by using the spring's @Transactional annotation. The function is something like this

@Transactional
public void doSomething() {
   recordActionInDb();
   updateThirdPartyApi();
}

recordActionInDb: is responsible for inserting some action events in db like the user details and his action

updateThirdPartyApi: is responsible for posting the user's action to a third party server.

Both of these functions are Asynchronous (@Async annotation) in nature and the only dependency is the transaction should happen properly i.e if the updateThirdPartyApi function fails then rollback should happen for recordActionInDb.

We can't allow the recordActionInDb to be called after updateThirdPartyApi because if recordActionInDb function fails then we don't have the privilege to rollback the updateThirdPartyApi as it is managed by someone else.

For @Async annotation, I came to know that spring initiates a different transaction as it is on a separate thread, hence I am not able to rollback for recordActionInDb if updateThirdPartyApi fails, but If I remove @Async from recordActionInDb it is working fine. I cannot let this happen synchronously as it is quite time consuming operation. Hence what I want is to let the parent transaction even control the Async function recordActionInDb. Any suggestions here?

spring-boot

transactions

spring-transactions

spring-async

0 Answers

Your Answer

Accepted video resources