Distributed Systems for Backend Engineers · Data Distribution and Agreement

Distributed Transactions: 2PC vs Sagas

Atomicity across services and databases.

Two-phase commit (2PC) coordinates atomic commits across participants (prepare, then commit) but blocks if the coordinator fails, holds locks across the network and is poorly supported across heterogeneous services. Within one database (or distributed SQL like Spanner/CockroachDB), transactions are coordinated for you. Across microservices, prefer sagas (local transactions + compensations), outbox for reliable events, and idempotency — accepting eventual consistency.

Cross-boundary atomicity options

Criterion 2PC / XA Distributed SQL transaction Saga
Atomicity Yes Yes Eventual (compensations)
Isolation Yes (locks) Yes No (semantic locks needed)
Availability Blocks on coordinator failure High (consensus-backed) High
Heterogeneous systems Limited support Single database Yes
Use when Rarely (legacy XA) Data in one distributed DB Cross-service workflows
2PC failure mode:
coordinator → PREPARE → A: yes, B: yes
coordinator crashes before COMMIT → A and B hold locks, uncertain, until coordinator recovers
Saga alternative:
ReserveStock (local tx) → ChargePayment (local tx) → fail → RefundPayment, ReleaseStock (compensations)

Common pitfalls

  • XA transactions across microservices.
  • Sagas without compensations or idempotency.
  • Assuming sagas provide isolation.

Key points

  • 2PC blocks and couples
  • Distributed SQL for single-store needs
  • Sagas + outbox across services

Further reading: microservices.io: Saga

Practice questions

Why does 2PC have availability problems?

Answer

If the coordinator fails after participants prepare, they must wait (holding locks) until it recovers to learn whether to commit or abort.

What isolation problem do sagas have?

Answer

Intermediate states are visible to other transactions (no isolation), so you need countermeasures like semantic locks, commutative updates or re-reading values.

Open in the app to mark lessons complete, take notes and track your progress.