Search code examples
springspring-bootmicroservicesspring-transactions

@transactional in service class with microservices


I was working under microservices and using @transactional and came across a doubt that suppose I have write @transactional over service class which internally calling different microservices for the database operations. Now suppose one of the microservice fails the what will be happen to database state of other microservices as they already commit their database or how rollback will happen?

Sample code is like

@Transactional
@Service
class MySerivce{
    public void method(){
        // call microservice1
        // call microservice 2 (fails or give error)
    }
}

Please share knowledge. Thanks!


Solution

  • Those two microservices and your application are separate systems. @Transactional only manages the transaction local to your application. It does not know how to manage the transaction of other microservice that it calls (Also impossible to do that otherwise you will end up like a hacker to hack other microservices..)

    So if microservice2 fails , it will not help to rollback all the things that are already done on microservice1. You have to handle it manually. Microservice1 needs to provide the API to undo such thing and then you need to manually catch the exception thrown by microservice1 and call this API to apply the compensation action.

    A pattern called saga pattern is intended for solving such issue. You can google more about it.