How would you handle distributed transactions in a microservices architecture? Explain the concept of the Saga pattern.

Distributed transactions in a microservices architecture are handled with the Saga pattern, which splits a transaction spanning multiple services into local transactions with compensating actions instead of relying on a two-phase commit across databases.

Key Points

Example

For a multi-service order, the Order service creates a pending order, Payment charges the customer, and Inventory reserves stock; if Inventory fails, a compensating transaction refunds the payment and cancels the order, keeping the system consistent without ever needing a lock across all three databases at once.

// Saga state is stored, so the orchestrator can resume after a crash
public enum SagaStep { STARTED, PAYMENT_DONE, STOCK_RESERVED, COMPLETED, COMPENSATING, CANCELLED }

@Service
public class OrderSagaOrchestrator {

    @Transactional
    public void run(Long sagaId) {
        OrderSaga saga = sagas.findById(sagaId).orElseThrow();
        try {
            if (saga.step() == SagaStep.STARTED) {
                payment.charge(saga.orderId(), saga.amount());
                saga.moveTo(SagaStep.PAYMENT_DONE);
            }
            if (saga.step() == SagaStep.PAYMENT_DONE) {
                inventory.reserve(saga.orderId());
                saga.moveTo(SagaStep.STOCK_RESERVED);
            }
            saga.moveTo(SagaStep.COMPLETED);
        } catch (Exception e) {
            saga.moveTo(SagaStep.COMPENSATING);
            if (saga.paymentDone()) payment.refund(saga.orderId());
            saga.moveTo(SagaStep.CANCELLED);
        }
    }
}

Interview Tip

A concise interview answer is

Since each service owns its own database, I handle cross-service transactions with the Saga pattern: break the transaction into local steps per service, and define a compensating action for anything that needs to be undone if a later step fails. It gives eventual consistency instead of true atomicity, coordinated either through events or a central orchestrator.

Last updated: 1 November 2026

Previous question: If you were tasked with deploying a microservices application, how would you decide whether to use Docker, Kubernetes, or both in your architecture?

Next question: In a microservices architecture, if a step in your Saga fails, how would you ensure data consistency across all services involved? Can you provide a specific example of a compensation action?

More Microservices - Level II interview questions

All Microservices - Level II questions