Skip to content

Distributed transactions: 2PC, sagas and the outbox

Two-phase commit and why it blocks, sagas with compensations, and the transactional outbox that fixes the dual-write problem between a database and a queue.

35 min8 steps

By the end you can
  • Explain how two-phase commit reaches atomic agreement, what it costs, and why it blocks when the coordinator fails after prepare
  • Design a saga with compensations in the right order and place irreversible steps last
  • Explain the dual-write problem and how the transactional outbox and idempotent consumers solve it
  • Choose between a local transaction, 2PC and a saga for a cross-service workflow

One business action, several databases

Atomic commit (2PC)

  • Commit or abort together
  • Locks held throughout

Saga

  • Commit each step locally
  • Undo with compensations
  • No isolation

Naive sequence

  • Flight booked, hotel call fails
  • Left half done

An order service must create an order row and its order-line rows. Both tables live in the same Postgres database. What should it use?

Answer this step to continue.

What this lesson simplifies

  • 2PC costs assume equal round trips to every participant and a fixed fsync time; real participants differ.
  • Saga isolation anomalies (other transactions seeing intermediate states) are described but not simulated.
  • The outbox is shown with a polling relay; log-based change capture behaves similarly but is not modelled.

Sources

  1. H. Garcia-Molina, K. Salem. Sagas, 1987.
  2. J. Gray, L. Lamport. Consensus on Transaction Commit, 2006.
  3. C. Richardson. Pattern: Transactional outbox.
  4. C. Richardson. Pattern: Saga.

Reviewed by T2 content review on . Revision 1.