Data · L2Distributed transactions and two-phase commit

Distributed transactions and two-phase commit

Two-phase commit makes several databases commit as one. Learn how it works, why it can freeze when the coordinator dies, and what to use across services instead.

L2 SeniorData17 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 13 Nov 2026 · How we check content
Section 1 of 8

What broke

In April 2009, an administrator posted to the PostgreSQL admin mailing list. She had inherited a test server running PostgreSQL 8.2.9. It had 315 databases. 1

The server refused to work. Every connection got "database is not accepting commands to avoid wraparound data loss". She followed the hint and ran VACUUM in single-user mode. The server still would not start normally. 1

She started a new thread when she could not drop a database. Tom Lane, a core Postgres developer, asked one question: "Maybe you've got some prepared transactions laying about?" She checked. There were three. The oldest had been waiting since July 2008. She did not know what had created them. 2

She ran ROLLBACK PREPARED on each one. VACUUM worked again, and she was "back in business". Most of their code was Java on JBoss. Another list member suggested a likely cause: XA two-phase commit code that assumed a rollback on disconnect. Nobody confirmed it. 2

The same day, Tom Lane told the developers' list that this was "another instance" of the problem. He proposed turning the feature off by default. 3 That evening, he committed the change. The commit message said the project had seen this "several times now". 4

Section 2 of 8

The idea in simple words

A transaction in one database is all or nothing. You saw this in transactions and isolation levels. Now one action changes two databases. You want both changes, or neither. This is the atomic commit problem.

You cannot just commit one, then the other. If the second fails, the first is already committed.

Two-phase commit (2PC) solves this with a coordinator. In phase one, it asks every database, "Can you commit?" In phase two, it tells all of them the same answer. 6

The catch is in the middle. A database that says "yes" gives up its right to decide. It must wait for the coordinator, however long that takes.

The key idea. 2PC makes many machines agree, but one machine holds the decision. If that machine dies at the wrong moment, the others wait with their locks held. Modern databases avoid most of this by replicating the decision with consensus.

Section 3 of 8

How it works

The two phases

XA, a standard that many databases support, calls the coordinator a transaction manager. Each database is a resource manager. 7

  1. Prepare. The coordinator asks each database to prepare. Each one writes its changes to stable storage and votes yes or no. 7
  2. Commit or abort. If every vote is yes, the coordinator tells all of them to commit. If any vote is no, it tells all of them to roll back. 7

Every machine writes its state to disk before it sends a message. After a crash, it reads that state and carries on. 6 The coordinator's log entry is the real moment of commit. Once it says COMMIT, the transaction is committed, even if no database has heard yet. 6

Why it blocks

Step through one order that changes two databases.

Two-phase commit: both databases vote yes, the coordinator dies, and the rows stay lockedCoordinator Orders DB Stock DB PREPAREPREPARE YESYESprepared, lockedprepared, locked log: COMMITcrashed In doubt: commit or abort? Rows stay locked.Other orders wait. Neither DB may guess. ✓ Fix: replicate the coordinator's logThe replicated log still has COMMIT. SeniorPath
  1. Order 42 must change two databases. The coordinator sends PREPARE to both. Each one writes the changes to disk, but does not commit yet.
  2. Both databases vote YES. A YES is a promise: I can commit, even after a crash. To keep that promise, each one keeps its row locks.
  3. The coordinator writes COMMIT to its own log. That is the decision. Then its machine dies before it tells anyone.
  4. Both databases are now in doubt. They voted YES, so they may not abort alone. They do not know the decision, so they may not commit. Locked rows block other orders.
  5. Classic 2PC waits for the coordinator to come back. Spanner and CockroachDB store the decision in a Paxos or Raft group instead, so it survives one machine dying and the commit can still finish.
Step 1 of 5

If a database does not answer phase one, the coordinator simply aborts. 6 The bad case comes later. If the coordinator fails right after every database has voted yes, the databases cannot know whether it committed or aborted. The protocol blocks until the coordinator is repaired. 6

A transaction in this state is an in-doubt transaction. It keeps every row lock it holds. Other transactions that need those rows wait too.

The cost is also visible when nothing fails. With the coordinator on the same node as one database, a commit takes three message delays. Add disk writes for each prepare and for the decision. 6

Postgres: PREPARE TRANSACTION

Postgres gives you the database side of 2PC:

-- needs max_prepared_transactions > 0
BEGIN;
UPDATE stock SET qty = qty - 1 WHERE sku = 'tee-m';
PREPARE TRANSACTION 'order-42';
-- later, from any session:
COMMIT PREPARED 'order-42';  -- or ROLLBACK PREPARED

After PREPARE, the transaction no longer belongs to your session. Its state is on disk, and it can almost always still commit after a crash. Any session can finish it. 5

The docs say this command is not meant for applications. It is for an external transaction manager. 5 They also warn that leaving a transaction prepared for a long time is unwise. It keeps its locks, it stops VACUUM from reclaiming space, and in extreme cases it can force a shutdown to prevent transaction ID wraparound. 5 That is what happened to the test server above.

The fix since 2009: max_prepared_transactions defaults to 0, which turns the feature off. 4 Keep it at 0 unless a transaction manager tracks every prepared transaction. 5 You can list open ones in the pg_prepared_xacts view. 5

Making 2PC fault-tolerant

The weak point is one coordinator on one machine. So replicate it, the way Raft replicates a log.

Gray and Lamport's Paxos Commit goes a step further. It runs Paxos on each database's vote, uses 2F+1 coordinators, and makes progress while F+1 of them work. Classic 2PC is the case F = 0. 6

Spanner. Google's Spanner splits data into Paxos groups. A transaction inside one group does not need 2PC. 8 If it spans several groups, their leaders run 2PC, and one group acts as coordinator. Each prepare record and the commit record go through Paxos. So the coordinator's state is replicated. 8 The paper says "Running two-phase commit over Paxos mitigates the availability problems." 8

CockroachDB. CockroachDB also runs 2PC on top of consensus. A transaction's record is replicated the same way as its writes. 9 Each write is a write intent: "a replicated lock and a replicated provisional value". 10 The coordinator heartbeats the transaction record. If the heartbeats stop, the record is moved to ABORTED, so others stop waiting. 10 A STAGING transaction is the exception, as below.

Its older protocol needed two consensus rounds in a row: the writes, then the commit record. Parallel commits writes a STAGING record and the writes at the same time. Once every listed write has reached consensus, the transaction counts as committed. Cockroach Labs says this commits cross-range transactions in half the time. 9 If the coordinator dies, another transaction checks the listed writes. If all are there, the transaction is committed. If any is missing, it first stops that write from ever landing, then marks the transaction aborted. 9

What it still costs

Consensus removes the single point of failure. It does not remove the waiting. In Spanner's tests, a commit with 1 participant took 17 ms on average. With 50 it took 42.7 ms, and with 200 it took 150.5 ms. The paper calls up to 50 participants reasonable. 8 Participants release their locks only after the commit is applied. 8 So locks are held longer as participants grow.

Section 4 of 8

Trade-offs

OptionAtomic across all parts?Blocks if the coordinator dies?Use it when
One database transactionYes No coordinator.The data fits in one database. Prefer this.
Classic 2PC or XAYes Yes Locks stay until it returns. 6Rarely. A tested transaction manager owns recovery.
2PC over consensus (Spanner, CockroachDB)Yes Not when one machine dies. It waits only if most replicas of a group are down. 8 6You already run such a database. It handles 2PC for you.
Saga, outbox and idempotent stepsNo Each step commits alone and compensations undo.No global locks.Several services, each with its own database.

Simple rule: inside one distributed database, let the database run 2PC. Across services, use a saga.

Section 5 of 8

At work: how a senior uses this

  • When a design says "update both in one transaction", ask: "Is this one database, or two?" If it is two, the answer is 2PC or a saga, never two plain commits.
  • Across services, use a saga with an outbox. Make every step idempotent, as in idempotency, retries and timeouts.
  • Inside one Spanner or CockroachDB cluster, trust its transactions. Keep them short and touch few ranges.
  • Check max_prepared_transactions on every Postgres server. If nothing uses it, set it to 0.
  • If you do use XA, alert on prepared transactions older than a few minutes. In Postgres, query pg_prepared_xacts.
  • Write a runbook for in-doubt transactions. Say who decides commit or rollback, and how to check the coordinator's log first.
Section 6 of 8

With AI

What to ask the agent

"Here is our checkout code. List every place where one request writes to two databases or to a database and a broker. For each, say whether a crash between the writes leaves them out of step."

"Write a monitoring query for Postgres that alerts when any row in pg_prepared_xacts is older than 5 minutes. Include the gid, owner and database."

"Explain what our XA transaction manager does on restart with in-doubt transactions. Point me to its recovery log settings."

What to check yourself

  • The agent did not "fix" a cross-service write by adding PREPARE TRANSACTION in app code. The Postgres docs say not to. 5
  • Any ROLLBACK PREPARED in a runbook first checks the coordinator's decision. Rolling back a transaction that the coordinator committed breaks atomicity.
  • Timeouts do not abort a transaction that already voted yes. That is the coordinator's job.
  • Claims about Spanner or CockroachDB match their own docs, not a blog summary.
Section 7 of 8

Check yourself

1. In two-phase commit, a database has voted YES. Then the coordinator stops answering. What may the database do?

Show answer

Neither. It must wait for the decision and keep its locks. The coordinator may have decided either way before it died. A YES voter that guessed could disagree with the others.

2. Your Postgres server has max_prepared_transactions = 10, and nobody knows why. What is the safest first step?

Show answer

Check pg_prepared_xacts for old prepared transactions, then plan to set the value to 0. Prepared transactions survive restarts. The Postgres docs say to keep the feature off unless a transaction manager closes them out.

3. How do Spanner and CockroachDB stop 2PC from blocking when a coordinator machine dies?

Show answer

They keep the transaction state in a Paxos or Raft group, so another replica can finish the commit. The decision is replicated like the data. Losing one machine does not lose the decision.

4. Orders, Stock and Payments each own a database, and one checkout touches all three. Which design avoids holding locks across the three services while a checkout runs?

Show answer

A saga with an outbox and idempotent steps. Each step commits locally, and compensations undo earlier steps. No service holds locks while it waits for another.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 10 sources and related lessons
  1. pgsql-admin mailing list, “postgres 8.2.9 transaction id wraparound failure” (April 2009) (opens in a new tab)
    The first report. A test server with 315 databases refuses commands to avoid wraparound, and vacuuming one database does not help.
  2. pgsql-admin mailing list, “postgres 8.2.9 can't drop database in single user mode” (April 2009) (opens in a new tab)
    The follow-up thread. Tom Lane finds old prepared transactions, ROLLBACK PREPARED clears them, and VACUUM works again.
  3. Tom Lane, “Prepared transactions vs novice DBAs, again,” pgsql-hackers (22 April 2009) (opens in a new tab)
    Tom Lane tells the developers' list about the pgsql-admin case and proposes turning prepared transactions off by default.
  4. Tom Lane, “pgsql: Change the default value of max_prepared_transactions to zero,” pgsql-committers (23 April 2009) (opens in a new tab)
    The commit that turned prepared transactions off by default, and why.
  5. PostgreSQL documentation: PREPARE TRANSACTION (opens in a new tab)
    What a prepared transaction keeps, and the warning about leaving one open.
  6. Jim Gray and Leslie Lamport, “Consensus on Transaction Commit”, Microsoft Research MSR-TR-2003-96 (2004, revised 2005) (opens in a new tab)
    Section 3 explains two-phase commit, its cost and why it blocks. Section 4 runs the decision through Paxos instead.
  7. MySQL 8.4 Reference Manual: XA Transactions (opens in a new tab)
    The XA roles (transaction manager and resource managers) and the two phases, in plain words.
  8. James C. Corbett et al. (Google), “Spanner: Google's Globally-Distributed Database”, OSDI 2012 (opens in a new tab)
    Section 2.1 and 4.2.1 show two-phase commit across Paxos groups. Table 4 shows how latency grows with participants.
  9. Nathan VanBenschoten, “Parallel Commits: An atomic commit protocol for globally distributed transactions”, Cockroach Labs blog (November 2019) (opens in a new tab)
    Why 2PC blocks, how CockroachDB runs it on consensus, and how it cut commit time from two consensus rounds to one.
  10. CockroachDB documentation: Transaction Layer (opens in a new tab)
    Write intents, transaction records, heartbeats, and what happens when a coordinator dies.

Real incident: PostgreSQL user (pgsql-admin mailing list), 20 Apr 2009: Forgotten prepared transactions stop a PostgreSQL server

Case studies: Google: Spanner: a global database built on known clock error

Related: Transactions and isolation levels · Consensus and Raft · Sagas, outbox and CDC · Time, clocks and ordering · Leader election and leases · Exactly-once and effectively-once

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper