Distributed Transactions: Two-Phase Commit and Sagas

Two-phase commit and how it fails, the outbox pattern and sagas, then replica lag, sync vs async replication and eventual consistency.

In this chapter

Distributed transactions and reads from copies

More on Transactions: locks and production

Keep learning

Overview

chapters · transactions, isolation and locks Distributed transactions: one commit across machines, and reads from copies When data lives on several machines, both writes (commit) and reads (copies) need extra care. ✍️ Write side Take from DB A, add to DB B. Two can crash separately → need 2PC. 👀 Read side

1. Why a plain commit on each side is not enough

why naive commit fails node ok DB A: COMMIT ✓ node bad DB B: 💥 down A is committed, B never will be. Commit cannot be undone, so money was created from nothing. Commit is a one-way door Nobody walks through until everyone has promised they can.

2. Two-phase commit, and six ways to interrupt it

Phase 1: participants vote YES written to disk Coordinator logs decision Phase 2: COMMIT / ABORT to all participants Pick a failure and step through. Watch for a participant in doubt: voted YES, can't decide alone. After it Vote YES Each participant Must commit if told, even after crash. Cannot abort alone. Log the decision Committed or aborted for good. Participant A Participant B Blocking: coordinator dies in the in-doubt window vote YES locks held 💥 crash decision unknown in doubt… stalls other queries Non-blocking only with no partitions, bounded delays. Not real. Consensus commit Paxos/Raft replicate the coordinator (Spanner). Practical fix.

3. Two very different things share the name

Database-internal ✓ Same software on all nodes (Spanner, CockroachDB, Vitess). Tuned, replicated, optimised. Works well. Heterogeneous (XA) ✕ DB + message broker, app server coordinates. Lowest common denominator: slow, fragile, often avoided. C API: xa_prepare, xa_commit, xa_recover. MySQL XA START/PREPARE/COMMIT, PG PREPARE TRANSACTION. Orphaned prepared tx Inside MySQL 2PC between redo log and binlog. → logs App-server coordinator Restart without its log → lost decision, in-doubt rows.

4. Exactly-once is built from at-least-once plus idempotence

outbox pattern one local txn row + outbox row node ok dedupe by id delivered at least once, applied once Transactional outbox Business row + event row in one local tx. Relay may publish twice. Idempotent consumer Local tx steps, each with an undo (refund, release stock). Picking an approach Atomic across systems? Yes, with blocking Outbox + idempotent consumer Eventually, no loss Eventually, with compensation Avoid the split Keep related data in one DB/shard → two-phase interview · split brain

5. Consistent reads when data has copies

Consistency in data (ACID C) Your rules hold: FKs valid, counts match, no negative balance. Consistency in reads Does the next read, from anywhere, see the commit? A system property. A write sets the primary to X. A read routed by the load balancer to a replica that has not caught up still returns the old value Z. node ok primary: X node bad replica: Z (old) replication lag write commits read returns Z until it catches up Any copy has the gap Read replica, Redis/memcached cache, search index. Eventual consistency If writes stop, all copies agree in the end. Not just NoSQL PG primary + 2 replicas behind a load balancer: same. Replication mode is the trade-off Commit returns when Replica reads Replica has it too See the commit (right settings) Primary alone has it May lag: eventually consistent Withdraw 1 Withdraw 2 Stale balance read → double spend withdraw $1,000 → primary still $1,000 replica $1,000 check replica: $1,000 approved ✕ $2,000 taken Likes: stale OK 7,000 vs 7,011 for a second. Replica/cache fine. Balance: stale NOT OK Money decisions read primary, inside the writing tx. "I just saved it" Read-your-writes: route to primary briefly, or wait for catch-up. Copies catching up Eventual consistency fixes this. Corrupt data → replica lag · read replicas

Remember

phases: vote, then commit/abort Fail before vote Safe to abort. Coordinator dies after vote Participants in doubt, holding locks. Internal 2PC good Cross-vendor XA fragile, last resort. App → queue Outbox, idempotent consumer, or saga. Copies serve old data Sync replication closes gap, slower commits. Decisions on value Read the primary. Corrupt stays corrupt Eventual consistency only helps copies.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.