Java and Spring Level 3 This level · 22 of 56
Hard java spring

A business transaction spans multiple databases. How do you keep it consistent?

The 30 second answer

I avoid distributed two-phase commit across services and use a saga instead. It is a chain of local transactions, coordinated by events or by an orchestrator, and if a step fails, compensating transactions undo the earlier steps. The cost is that there is no isolation, so others can see in-between states. I handle that with explicit statuses like pending and with idempotent steps.

Could you say this in an interview?

Avoid distributed 2PC across services. Use a saga: a chain of local transactions where each step publishes an event or is called by an orchestrator, and a failed step triggers compensating transactions that undo earlier steps. The cost is that there is no isolation, so other readers can see in-between states; I handle that with status fields such as PENDING and with idempotent steps. Follow-up: Orchestration or choreography? (Orchestration when the flow has many steps and needs one place to see the state.)

Alternate interview scenarios

"Design a saga for Order, Payment and Inventory."

A concrete orchestrated version works like this. Order service creates the order as PENDING and starts the saga. Then Inventory reserves the stock, and Payment charges the customer. If both succeed, the order becomes CONFIRMED. If the payment fails, the orchestrator runs the compensations in reverse order: it releases the reservation and marks the order CANCELLED. Three details matter. First, every step and every compensation must be idempotent, because messages get redelivered. Second, a reservation needs a timeout, so stock does not stay locked when the saga stalls. Third, each service should publish its step result through a transactional outbox, so a database change and its event cannot get out of sync. Order the steps so that the hardest step to undo, here the payment charge, runs last, or use authorise-then-capture so that undoing it is cheap.

"What is a compensating transaction, and how is it different from a database rollback?"

A rollback throws away changes that were never committed, so nobody else ever saw them. A compensating transaction runs after an earlier step has already committed, and other users or services may have seen it or acted on it. So it is a new business action with the opposite effect: a refund instead of deleting the charge, or releasing a reservation instead of deleting the row. It also cannot just restore the old values, because concurrent work may have changed the data since. For example, it adds the reserved quantity back to stock instead of writing back the old stock number. Some steps cannot be undone at all, like a sent email or a shipped parcel. That step is the pivot, the point of no return. Steps before it must be compensable, and steps after it must be retryable until they succeed.

"Why not just use two-phase commit (2PC) across the services?"

With 2PC, every participant has to support a prepare phase and keep its locks until the coordinator decides. If the coordinator is slow or down, the participants stay blocked with those locks held. Many of the things a business flow touches can't take part at all, such as a payment provider's HTTP API or a message broker used as a queue. A saga gives up isolation and in return keeps every service available and independent. That is why most microservice designs accept eventual consistency here.

"What happens if a compensating transaction itself fails?"

I never treat that as done or as success. Compensations must be idempotent and retryable, so I retry them with exponential backoff. The orchestrator records progress after each step, so after a crash it resumes the compensation where it stopped instead of starting over. If retries run out, the saga moves to a state such as COMPENSATION_FAILED, and I raise an alert with the saga id, the failed step and the error. A person then fixes it from an operations queue. Some failures really do need manual intervention, and the important thing is that they are visible and not silently lost.

"The saga orchestrator crashes in the middle of execution. What happens?"

Nothing is lost if the orchestrator keeps its state in a database and not in memory. Each saga has a row with its id, current step, status and a version number. The orchestrator changes that row and writes the next command to an outbox table in the same local transaction. After a restart, it loads the unfinished sagas and sends the command for the current step again. That resend is safe because participants deduplicate by saga id and step. A late reply for a step that is already finished is ignored. Each step also has a timeout, so a stuck saga is found even without a crash. If several orchestrator instances run, each saga is claimed with a row lock or a lease, so only one instance drives it at a time.

"How do you stop concurrent sagas from leaving data inconsistent?"

Sagas have no isolation, so three anomalies can appear: lost updates, dirty reads of a step that is later compensated, and non-repeatable reads between steps. The standard countermeasures are design choices. A semantic lock is a status such as PENDING_PAYMENT that tells other sagas the record is in flux, so they reject or wait. Commutative updates, such as available = available - 2 instead of setting a value, give the same result in any order. A pessimistic view reorders the saga so that the risky updates happen in the retryable steps after the pivot. Reread values means checking a version column before updating and restarting the step if it changed. Inside each service I still use conditional writes, such as UPDATE inventory SET available = available - 2 WHERE sku_id = ? AND available >= 2, so a single row can never oversell. For a really high-risk update, a strongly consistent design can still be the right choice.

"An order is created, the payment is taken, inventory reservation fails, and the refund API is unavailable. How do you guarantee no duplicate refunds, reliable compensation, recovery after a restart, eventual consistency and full traceability?"

When inventory fails, the orchestrator moves the saga to COMPENSATING and writes a refund command to the outbox in the same transaction. The refund call carries an idempotency key built from the order id, such as refund-<orderId>. Payment providers like Stripe store the result for a key, so a retry after a timeout can't refund twice. A unique constraint on the refunds table by order id is the second guard. While the refund API is down, the relay retries with exponential backoff and jitter. The saga state and the outbox are in the database, so a restart just continues from there. The customer sees an honest status such as REFUND_PENDING, and the system reaches the final state once the provider is back. If the retry window runs out, the saga goes to a manual queue with an alert. For traceability, the saga id travels as a correlation id in every message, log line and trace span, and a saga log table records each step change with its time. Better still, avoid the problem: reserve stock before charging, or authorise first and capture later, so the failure only needs a cheap void of the authorisation.

Sources (5)
  1. microservices.io: Sagamicroservices.io
  2. Microsoft Azure Architecture Center: Saga design patternlearn.microsoft.com
  3. Microsoft Azure Architecture Center: Compensating Transaction patternlearn.microsoft.com
  4. Stripe API: Idempotent requestsdocs.stripe.com
  5. microservices.io: Transactional outboxmicroservices.io
Previous
Next