Video in progress

Why can't `@Transactional` combine changes in two different services into one transaction?

@Transactional manages a transaction on one database connection inside one application. Another service is another process and another database; you can't roll back its HTTP call.

📖 Answer

A frequently seen piece of bad code:

@Transactional
public void placeOrder(OrderRequest req) {
    orderRepo.save(order);                 // the order database
    paymentClient.charge(req.amount());    // HTTP -> payment-service
    inventoryClient.reserve(req.items());  // HTTP -> inventory-service, the error happens here
}

If inventory fails, Spring rolls back orderRepo.save. But payment-service has already charged the money and committed to its own database. No annotation will undo that.

The classic solution for a distributed transaction is 2PC (two-phase commit, XA). But it's almost never used in microservices: every participant has to support XA, locks are held for a long time, and if the coordinator goes down everything hangs. Kafka and many REST APIs don't know XA at all.

So in microservices you take a different path: each service makes its own local transaction, and if something fails, operations that compensate for the earlier steps run. That's the saga pattern.