Skip to content
Commitwise
Menu

How do you keep data consistent across microservices without distributed transactions?

System designSenior

In shortUse a saga: a sequence of local transactions, each publishing an event or command, with compensating actions to undo earlier steps when a later one fails. Combine it with the transactional outbox for reliable messaging and idempotent consumers, and accept intermediate states.

Model answer

Why not distributed transactions: two-phase commit couples availability of all participants, holds locks across network calls, and isn’t supported by most message brokers and managed databases. Microservices instead accept eventual consistency with explicit coordination.

Saga: an order that needs payment and inventory:

  1. Order service creates the order as PENDING (local transaction) and emits OrderCreated.
  2. Payment service charges and emits PaymentSucceeded or PaymentFailed.
  3. Inventory service reserves stock and emits StockReserved or StockUnavailable.
  4. On failure, compensations run in reverse: refund the payment, cancel the order.

Choreography (services react to each other’s events) is simple for two or three steps but hard to follow as flows grow. Orchestration (a saga orchestrator, or a workflow engine such as Temporal) keeps the flow in one place with explicit state, timeouts and retries; it’s easier to reason about and observe.

Making it reliable:

  • Transactional outbox: each local transaction writes its event to an outbox table, relayed to the broker, so state and event can’t diverge.
  • Idempotent consumers: dedupe by message id; at-least-once delivery is a given.
  • Semantic compensations: a refund, not a deleted charge; a cancellation email, not an unsent one.
  • Intermediate states are real: model PENDING, show them in the UI, and add timeouts that trigger compensation when a step never answers.

What they're looking for

Why two-phase commit is avoided, saga choreography vs orchestration, compensations (semantic undo), the outbox pattern, idempotency, visible intermediate states and how to model them, and timeouts.

Common mistakes

  • Proposing two-phase commit across services and databases.
  • Publishing events outside the database transaction.
  • Compensations that assume they can restore the exact previous state.

More system design questions

Esc

Type to search the whole site.