Video in progress

Order, payment and inventory are separate services with separate databases. How do you keep data consistent between them? Why not use XA/2PC?

I use a saga: each service does its own local transaction and emits an event, and on a failure the earlier steps are undone with compensation. For emitting events reliably, a transactional outbox. 2PC leaves resources locked when the coordinator dies and couples the services tightly.

📖 Answer

The problems with 2PC aren't theoretical:

  • If the coordinator disappears after the prepare phase, the participants wait with the rows locked. In PostgreSQL, max_prepared_transactions and forgotten prepared transactions hold the xmin horizon and stop VACUUM.
  • Every write runs at the speed of the slowest participant; if one service goes down, everyone stops.
  • Kafka and many cloud services don't support XA at all.

In a saga, instead of "atomicity" you get "eventual consistency + compensation":

  1. Order service: the order is PENDING, and OrderCreated goes to the outbox, all in one local transaction.
  2. Inventory: reserves the goods → StockReserved or StockRejected.
  3. Payment: charges the money → PaymentCompleted or PaymentFailed.
  4. If PaymentFailed, Inventory releases the reservation and Order becomes CANCELLED.

The outbox:

BEGIN;
INSERT INTO orders (...) VALUES (...);
INSERT INTO outbox (aggregate_id, type, payload) VALUES (:id, 'OrderCreated', :json);
COMMIT;
-- a separate relay (polling or Debezium) publishes the outbox to the broker

Things to settle up front: every consumer is idempotent (an event arriving twice is normal); compensation isn't always possible (a sent SMS can't be taken back), so I put such steps last; orchestration (a central coordinator) versus choreography (through events): once there are more than 4-5 steps I prefer orchestration, because the flow is visible in one place.

And most importantly: a saga shows intermediate states to the user ("your order is being processed"). That has to be agreed with the product team in advance.