Microservices REST call and database transaction

49 Views Asked by At

Recently I got into the following situation. My two services are calling each other using REST call. Let's name it: ServiceA and ServiceB.

Scenario is following:

  1. ServiceA receives some input from user.
  2. ServiceA saves this info into database.
  3. ServiceA performs REST call to ServiceB to get some more details about received data previously from user.
  4. ServiceA waits for the response from ServiceB
  5. ServiceA receives data from ServiceB and saves into the database

All above operations are performed under method annotated with Spring @Transactional annotation

If serviceB does not respond to the request (it fails), I expect my transaction in ServiceA will fail and previous data will be reverted

I'm struggling if this approach is good or not. Making a REST call may take some time, f.e. I'm using retry backoff mechanism. I'm not sure how transaction will behave.

Thank you for help and clarification.

1

There are 1 best solutions below

0
Youness Tizi On

As you mentioned, the above operations are handled under a @Transactional, which means that all tasks are handled under one or more transactions.

Here is a solution for your case:

Ensure that the mentioned operations are treated under one transaction (using @Transactional(propagation = Propagation.REQUIRED) that supports the existing transactions and creates a new one if no transaction exists).

In case a problem occurs while waiting for the serviceB (an exception thrown, for example), the transaction will rollback for a specified exception (for example, define a WebServiceException and make use of @Transactional(rollbackFor = WebServiceException.class).