How do you handle a transaction that spans several microservices? Explain the Saga pattern.
Why not a distributed transaction (2PC)?
Two-phase commit needs every participant to support XA and hold locks until a coordinator decides; it is blocking (a coordinator failure leaves locks held), reduces availability, does not work across HTTP APIs and most NoSQL stores or brokers, and couples services tightly. Microservices therefore use sagas.
Saga
A saga is a sequence of local transactions, one per service. Each step commits locally and triggers the next. If a step fails, previously completed steps are undone by compensating transactions (semantic undo: refund a payment, release reserved stock), not by a database rollback.
Example: place an order
- Order Service creates the order as
PENDING. - Inventory Service reserves stock.
- Payment Service charges the card.
- Order Service marks the order
CONFIRMED. If payment fails: compensate by releasing the stock reservation and marking the orderCANCELLED.
Design rules
- Every step and compensation must be idempotent (messages can be redelivered) and compensations must eventually succeed (retry them).
- Use the transactional outbox so a local commit and the message that triggers the next step cannot get out of sync.
- Model intermediate states explicitly (
PENDING,PAYMENT_FAILED) so the UI and other services can reason about them. - Order the steps so the hardest-to-compensate action (charging money, sending an email) comes last.
- Add timeouts: if a reply never arrives, the orchestrator compensates or escalates.
Follow-up questions interviewers ask
Try answering each one before you open it.
Sagas give up isolation. What anomalies can happen and how do you mitigate them?
Because each local transaction commits immediately, other transactions can see intermediate state: lost updates, dirty reads (seeing a reservation that will be compensated) and fuzzy reads. Countermeasures: semantic locks (a PENDING status that other operations respect), commutative updates (increments rather than overwrites), pessimistic view (reorder steps to reduce risk), re-reading values before acting, and versioned records.
How would you implement a saga orchestrator in Java?
Either use a workflow engine (Temporal's Java SDK, Camunda, AWS Step Functions) that persists state, retries and timers for you, or build a state machine: persist a saga_instance row (current step, state, payload, version), send commands through the outbox, handle replies in idempotent consumers that advance the state, and run a scheduler to time out stuck sagas. A workflow engine is usually the better choice once flows have more than a few steps.