Sobes.tech
Junior

Is it normal to make a synchronous call to an external service inside a transaction?

sobes.tech AI

Answer from AI

Synchronous calls to external services within a transaction are generally considered bad practice. Reasons:

  • The transaction locks resources (such as tables or rows in a database) until it completes, and an external call can be slow or unreliable.
  • If the external service is slow or unavailable, the transaction will hang, which can degrade performance and lead to deadlocks.
  • In case of a transaction rollback, it is difficult to undo or compensate for the external service call.

Better:

  • Minimize transaction time by performing external calls outside the transaction.
  • Use asynchronous mechanisms, message queues, or compensation patterns.

Example of bad practice:

@Transactional
public void process() {
    // update data in DB
    repository.update(...);
    // synchronous call to external service
    externalService.call();
}

It is better to split into two parts: first the transaction with the update, then the service call.