SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • The Problem with Distributed Transactions
  • Two-Phase Commit (2PC)
  • Three-Phase Commit (3PC)
  • SAGA Pattern
  • Try-Confirm-Cancel (TCC)
  • Compensating Transactions
  • Outbox Pattern
  • Exactly-Once Processing
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Distributed Transactions

Two-Phase Commit (2PC)

A coordinator asks everyone to prepare, then tells everyone to commit or abort.

⏱ 14 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Two-Phase Commit (2PC) is a protocol that makes several databases all commit or all abort. A coordinator runs it in two steps: first it asks everyone to prepare, then it tells everyone the final decision.

  • Phase 1 (prepare / vote): the coordinator asks each participant, can you commit? Each one saves its work, keeps its locks, and votes YES or NO.
  • Phase 2 (commit / abort): if every vote is YES, the coordinator says COMMIT. If any vote is NO, it says ABORT.
  • A YES is a promise that survives crashes. That is why the protocol is safe.
  • The cost: it is slow, locks are held across the network, and if the coordinator dies at the wrong time, participants are blocked and wait.

02Concept: What is it?

We want several databases to agree on one outcome. The trick of 2PC is to split the commit into two steps, so that the point of no return comes after everyone has promised that they can finish.

Phase 1: Prepare. The coordinator sends PREPARE to every participant. Each participant does the work but does not commit. It writes everything needed to finish into its disk log (a prepare record), keeps its locks, and replies YES. If it cannot do the work, it replies NO and rolls back at once.

Phase 2: Commit or abort. The coordinator counts the votes. All YES means COMMIT, anything else means ABORT. It writes the decision to its own log first. This write is the commit point. Then it sends the decision to every participant, who obey, release their locks and reply with an ACK.

The two phases
Phase 1: Prepare
🎛️Coordinator
↓PREPARE?
🗄️Avotes YES
🗄️Bvotes YES
🗄️Cvotes YES
Phase 2: Decide
🎛️Coordinatorlogs COMMIT
↓COMMIT
🗄️Acommitted
🗄️Bcommitted
🗄️Ccommitted
Two round trips: one to collect votes, one to spread the decision.
🧠The promise is the key
After voting YES, a participant has given up its right to abort on its own. It must wait for the coordinator. That promise is what makes the protocol safe, and it is also what makes it block.

03Real-Life Example

🍵The Wedding Vows
A wedding officiant asks the first person: do you take this person? "I do." Then the second: do you? "I do." Only when both have said yes does the officiant say, "I now pronounce you married." If one of them says no, the wedding is called off for both. Nobody is half married. The weak spot: if the officiant faints right after both said yes, the couple stands there, bound by their promise, not knowing if they are married.
The wedding
Two-phase commit
The officiant
The coordinator
The two people
The participants (databases)
Asking: do you take...?
PREPARE
Saying 'I do'
Voting YES (a promise)
Saying 'I do not'
Voting NO, which aborts everything
'I now pronounce you married'
COMMIT, the final decision
The officiant faints in the middle
A coordinator crash: participants are blocked
The life of one participant
💤Workingbefore PREPARE
→↓PREPARE
🔒Preparedvoted YES, locked
→↓COMMIT
✅Committed

04Why Do We Need It?

⚛️Atomicity across machines
All databases end up with the same outcome, so no half-done order is left behind.
🔒Strong consistency
Nobody ever sees one database committed and another not, once the protocol finishes.
🧠Simple for the developer
You write 'begin, do work, commit' and the platform does the rest. No compensation code.
💥Safe through crashes
Logs on disk mean a restarted machine can find out what it promised.
🧱A base for other systems
Sharded databases and the XA standard use it to give transactions across shards.
📏A teaching example
It shows exactly why distributed agreement is hard, which leads to Paxos and Raft.
2PC gives true all-or-nothing across databases, by getting a promise from everyone before anyone commits.

05Where Do We Use It?

🧮Sharded databases
A transaction that touches rows on two shards commits with 2PC between them (Vitess, CockroachDB and Spanner all do something like this).
🗃️XA transactions
A standard interface (X/Open XA) that lets a transaction manager drive 2PC across databases and message brokers.
☕Java EE / JTA
Application servers coordinate a database and a JMS queue in one transaction.
🐘PostgreSQL
PREPARE TRANSACTION and COMMIT PREPARED expose the two phases for an outside coordinator.
🏦Core banking
Inside a trusted network where machines are close, short and rare.
📦Distributed SQL
Atomic commit across nodes in a cluster, usually with each participant replicated.

06Types / Parts / How It Works

Step by step (when everything works)

#WhoDoes what
1CoordinatorStarts the transaction and sends PREPARE to all participants.
2Each participantDoes the work, writes a prepare record to its log, keeps its locks, votes YES (or rolls back and votes NO).
3CoordinatorCollects votes. All YES: logs COMMIT. Any NO or missing vote: logs ABORT. This log write is the commit point.
4CoordinatorSends the decision to every participant.
5Each participantCommits or rolls back, releases its locks, and replies ACK.
6CoordinatorAfter all ACKs, writes an end record and forgets the transaction.

What happens when something crashes

FailureResultWhy
A participant crashes before votingABORTThe coordinator times out, treats the missing vote as NO. No one had committed.
A participant votes NOABORTOne NO is enough. Everyone else rolls back.
A participant crashes after voting YESCOMMIT or ABORT, as decidedOn restart its log says 'prepared', so it asks the coordinator for the decision.
The coordinator crashes before decidingParticipants BLOCK until it returnsThey voted YES, so they cannot abort alone, and they do not know the outcome.
The coordinator crashes after decidingParticipants BLOCK until it returnsThe decision is in its log. Participants who did not hear it must wait for the log.
The blocking problem
🎛️Coordinator💥 crashed
⇢⇣no news
🔒Ablocked
🔒Bblocked
🔒Cblocked
Waiting with locks held
Prepared participants hold locks and cannot decide alone.
VisualizerStep through two-phase commit, with failuresPick a scenario, then press Next or Play. Compare the happy path with a NO vote, a participant crash, and the coordinator crash that blocks everyone.
What happens during the commit?
Final outcome
COMMIT
Locks held for
about 40 ms
on each prepared row
Round trips (no failure)
2
prepare + commit
🎛️CoordinatorWants to commit
🗄️Orders DBIdle
🗄️Payments DBIdle
🗄️Stock DBIdle
Step 1 of 6
Start
An order must change three databases. A coordinator will run the two-phase commit, so that all three commit or none does.

A simplified picture of the textbook protocol. Real systems keep logs on disk, retry messages and let a recovering participant ask the others. The coordinator-down slider only matters for the last scenario.

07How to Use It / Steps / Implementation

Using 2PC safely

  1. 1
    Use it only when you need it
    It is best for a small number of databases that support it, in a fast and reliable network. Not for long workflows or calls to the public internet.
  2. 2
    Keep transactions short
    Locks are held through both phases. A short transaction means shorter waits for everyone else.
  3. 3
    Write logs before you reply
    A participant must save its prepare record to disk before it says YES. The coordinator must save its decision before it sends it.
  4. 4
    Set timeouts for votes
    Before it decides, the coordinator may give up and abort. Pick a timeout so one slow database does not hold the others for long.
  5. 5
    Make the decision retryable
    Participants must be able to ask 'what was the decision?' again and again, and the coordinator must answer from its log.
  6. 6
    Make the coordinator highly available
    Replicate its log (for example with Raft or Paxos), so a single crash does not block the cluster.
  7. 7
    Monitor in-doubt transactions
    Watch for prepared transactions that are older than a few seconds. They hold locks and need attention.
💡Read-only participants can skip phase 2
A participant that changed nothing can vote READ-ONLY. It drops out and releases its locks at once, which saves a message and time. This is a common optimisation.
⚠️Forgotten prepared transactions
In PostgreSQL, a prepared transaction that nobody commits keeps its locks even across restarts, and can block cleanup of old rows. Always monitor and resolve them.

08Key Terms to Know

TermMeaning in easy words
CoordinatorThe process that runs the protocol and makes the final decision (also called the transaction manager)
ParticipantA database or resource that takes part (also called a resource manager or cohort)
Prepare / vote phasePhase 1: the coordinator asks, each participant votes YES or NO
Commit / decision phasePhase 2: the coordinator announces COMMIT or ABORT
Commit pointThe moment the coordinator durably logs its decision. After this the outcome cannot change
Prepared stateA participant has promised to commit, and now waits for the decision
In-doubt transactionA prepared transaction that has not yet heard the decision
Blocking protocolA protocol where a crash can make others wait with locks held
Write-ahead log (WAL)A log saved to disk before acting, so a restart can recover
XAA standard interface for a transaction manager to run 2PC across resources
Heuristic decisionA manual choice by an operator to commit or abort a stuck transaction, at the risk of inconsistency

09Pros, Cons and Trade-offs

✅ Pros
  • Gives true atomic commit across databases
  • Strong consistency: no visible half-done state at the end
  • Safe through crashes thanks to logs
  • Simple for developers: no compensation code
  • Standardised (XA) and built into many databases
⚠️ Cons
  • Blocking: a coordinator crash can freeze participants
  • Slow: two round trips plus disk writes on each side
  • Locks are held over the network, which hurts throughput
  • A single slow participant slows everyone
  • Poor fit for the internet, long tasks and many services
  • The coordinator is a bottleneck and a single point of failure

Trade-offs

ChoiceWe gainWe lose
2PCAll-or-nothing correctnessLatency, locks, availability
SAGA insteadSpeed, no global locks, independent servicesTemporary inconsistency, and compensations to write
Replicated coordinatorNo single point of failureMore complexity and more messages
Short vote timeoutLocks released soonerMore transactions abort when one node is slow
Fewer participantsFaster and more reliableServices must share databases or be merged

10Common Problems and Mistakes

Common mistakes

  1. Ignoring the blocking case. The design works in a demo and freezes in production when the coordinator restarts.
  2. Long transactions. Locks held through two network round trips and a slow participant reduce throughput for everyone.
  3. Using it across services on the internet. Third-party APIs do not offer prepare and commit.
  4. Not writing the prepare record to disk. A YES that is lost in a crash breaks the promise, and the data can become inconsistent.
  5. Leaving prepared transactions around. They keep locks and block other work until someone resolves them.
  6. A single coordinator with no backup. It becomes the single point of failure of the whole system.
  7. Forcing a heuristic decision by hand without checking. The operator may commit on one database and abort on another.

Things to watch

⏳Lock wait
Time that rows stay locked. Long waits show as slow queries elsewhere.
🔒In-doubt count
Prepared transactions with no decision. This should be near zero.
🐢Slowest participant
Your commit is as slow as the slowest voter.
📉Abort rate
Many aborts point to timeouts that are too tight or an unhealthy node.

11Real-World Examples

🌍Google Spanner
Uses 2PC across shards, but every participant is a Paxos group, so a single machine crash does not block.
🪳CockroachDB
Uses an optimised atomic commit protocol with transaction records stored in the replicated database.
🧰Vitess and shard managers
Support cross-shard transactions with a prepare and commit flow, but advise avoiding them when possible.
☕Java application servers
JTA with XA lets a database update and a message queue write succeed or fail together.
🐘PostgreSQL
Gives PREPARE TRANSACTION for external transaction managers.
🏢Enterprise systems
Older banking and ERP systems rely on XA inside a single data centre.
📝Note
Product details change between versions. Check the current documentation of any system before depending on this behaviour.
Mini case: a cross-shard money transfer
🎛️Coordinator
→↓PREPARE
🗄️Shard 1-$50, YES
🗄️Shard 2+$50, YES
→↓COMMIT
✅Both done
Move $50 from an account on shard 1 to an account on shard 2.

12Related Topics to Read Next

The Problem with Distributed Transactions→

Why we needed a protocol like this at all.

Three-Phase Commit (3PC)→

An attempt to remove the blocking problem with an extra phase.

SAGA Pattern→

The popular alternative that avoids global locks.

ACID Transactions→

The single-database promises that 2PC extends.

Consensus Algorithms→

How to make the coordinator itself fault tolerant.

Paxos→

Used by Spanner to replicate each participant.

Sharding→

The main reason cross-shard transactions appear.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a protocol so several databases all commit or all abort.
  • ✔Phase 1: PREPARE. Participants save work, keep locks, vote YES or NO.
  • ✔Phase 2: all YES means COMMIT, any NO or timeout means ABORT.
  • ✔Commit point: the coordinator's durable log write of its decision.
  • ✔YES is a promise: a prepared participant cannot abort alone.
  • ✔Weakness: blocking. A coordinator crash leaves participants waiting, locks held.
  • ✔Cost: 2 round trips, disk writes, long locks. Keep it short and local.
  • ✔One line: “Ask everyone to promise first, and only then tell everyone to commit.”
← Previous
The Problem with Distributed Transactions
Next →
Three-Phase Commit (3PC)