Back to roadmap
Module 3 · Consistency & ReplicationDay 02825 min

Two-Phase Commit and Sagas

Distributed transactions: the strict way and the practical way.

Day 028

Two-Phase Commit and Sagas

Charge
service
Reserve
service
Notify
service
Refund
service
Release
service
Signal path
Saga with compensations vs 2PC
Charge
service
flow
Reserve
service
Reserve
service
flow
Notify
service
Reserve
service
fail
Refund
service
Memory hook

Two-Phase Commit and Sagas: distributed transactions

Mental model

choose the failure mode you can explain

Design lens

Sagas are eventually consistent; intermediate states are visible.

Recall anchors
2PCSagas

Why it matters

Two-phase commit (2PC) coordinates a transaction across multiple services with a prepare-and-commit handshake. It's correct, but if the coordinator fails, participants can block forever. Sagas avoid coordinators by chaining local transactions with compensating actions.

Deep dive

2PC: coordinator asks all to PREPARE; if all yes, COMMIT; else ABORT. If coordinator dies after PREPARE, participants are stuck holding locks.

Sagas: do local transaction in service A, then B, then C. If C fails, undo B then undo A via compensations. No global locks.

Choreographed sagas: events trigger steps. Orchestrated sagas: a workflow engine coordinates steps. Both are common.

Demo / scenario

Booking flow: charge card, reserve seat, send confirmation.

  1. Saga path: charge → reserve → notify.
  2. If reserve fails: refund (compensation for charge).
  3. Use idempotent operations to make retries safe.
  4. Workflow engine (Temporal, Step Functions) keeps the state.

Tradeoffs

  • Sagas are eventually consistent; intermediate states are visible.
  • Compensations must exist for every step.
  • 2PC is rare in modern microservice land; sagas dominate.

Diagram

failfail
Charge
Reserve
Notify
Refund
Release
Saga with compensations vs 2PC.

Mind map

Check yourself

Loading quiz…

Sources & further reading