skip to content

two-phase commit

prepare everywhere, then commit everywhere. PREPARE TRANSACTION, and the coordinator that dies at the worst moment.

address
everything.scale.two_phase_commit
part
part 17, scale and distribution
chapter
chapter 8 of 10
reading time
7 min

two-phase commit makes one transaction atomic across several databases. phase one: the coordinator asks every participant to prepare (make the work durable and promise to commit on request), and each votes. phase two: if all voted yes, it tells them all to commit, otherwise to roll back. in postgres that's PREPARE TRANSACTION and COMMIT PREPARED. the weak spot: a participant that prepared and then lost its coordinator can't decide alone, and it waits, holding its locks, possibly forever.

the picture

you know how a transfer between two banks has to debit one and credit the other, and doing one without the other is the one outcome nobody accepts? each bank's database can make its own half atomic. nothing makes the two halves atomic together, unless someone coordinates.

think of a wedding (the coordinator is the officiant). "do you?" to each partner, separately: that's phase one, and a "yes" is binding. only when both have said yes does the officiant declare it done, and that declaration is phase two. if the officiant collapses between the vows and the declaration, the couple is stuck in a strange state: neither can declare it done, and neither can walk away.

run =
coordinatorbank Abank B
beginsworkingworking

step 1the transfer runs on both servers: bank A debits, bank B credits. nothing is committed anywhere.

step 1/5
drawn by hand · the textbook protocol: one coordinator, two participants
a coordinator and two participants. step through the happy path, a no vote, and a coordinator that dies after everyone voted. the state to watch is prepared: promised, not finished.

in postgres

postgres provides the participant's half. PREPARE TRANSACTION 'gid' ends the current transaction's session involvement: the work is written to WAL and to disk, the session is free to do other things, and the transaction waits, under its global id, for someone to say COMMIT PREPARED 'gid' or ROLLBACK PREPARED 'gid', from any session. the coordinator (a transaction manager, an application, a sharding layer such as postgres_fdw or citus) is not postgres's job.

it's off by default, because a forgotten prepared transaction is dangerous. max_prepared_transactions is 0, and in the browser that's what you get:

sqlempty db
SHOW max_prepared_transactions;
BEGIN;
CREATE TABLE t (id int);
PREPARE TRANSACTION 'transfer-7';
output, from postgres 18.6
#1 · SHOW
max_prepared_transactionstext
0
(1 row)
#2 · BEGIN
#3 · CREATE TABLE
#4 · ERROR 55000
ERROR 55000: prepared transactions are disabled
HINT: Set "max_prepared_transactions" to a nonzero value.

on a real server with max_prepared_transactions = 10, here's one participant whose coordinator never comes back. T1 prepares half a transfer; then the whole server crashes and restarts; then other sessions try to get on with their day:

T1
·
T2
·
1
BEGIN

T1 starts the local half of a transfer: alice pays 50.00.

step 1/15
real output, a postgres 18.6 server · orphan-prepared
a real postgres 18.6. the prepared transaction survives T1's session, a crash and a restart. T2 gives up waiting for alice's row, and VACUUM can't remove dead rows anywhere until someone runs COMMIT PREPARED.

three things in that run are worth staring at.

it outlives everything. after the restart, recovery logs recovering prepared transaction 761 from shared memory, and pg_prepared_xacts lists it again: a transaction with no session, no process and no client.

gidtextxidtextownernamedatabasename
transfer-7761postgrespostgres
(1 row)
locktypetextrelationregclassmodetextgrantedbool
relationaccountsRowExclusiveLockt
relationaccounts_pkeyRowExclusiveLockt
transactionidnullExclusiveLockt
(3 rows)
real output, a postgres 18.6 server · orphan-prepared
pg_prepared_xacts after the restart, and the locks it still holds. the lock rows have no pid: no process is behind them.

it keeps its locks. T2 wants alice's row and waits for a transaction nobody is running. here T2 had lock_timeout = '200ms' and gave up with 55P03; without one it would wait until a human intervenes. and since the lock isn't held by a backend, the usual tools for killing a blocker (pg_terminate_backend) have nothing to terminate.

it pins the xmin horizon. a prepared transaction counts as running, so its xid holds back the xmin horizon like any long transaction: no dead row created after it can be removed, in any table of the cluster. three updates to an unrelated counters table, then VACUUM:

server log
  1. tuples: 0 removed, 4 remain, 3 are dead but not yet removable
  2. removable cutoff: 761, which was 5 XIDs old when operation ended

after COMMIT PREPARED 'transfer-7', the same VACUUM:

server log
  1. tuples: 3 removed, 1 remain, 0 are dead but not yet removable
  2. removable cutoff: 766, which was 0 XIDs old when operation ended

and the final balances show the prepared half committed, and T2's update never happened: alice 50.00, bob 100.00.

predict the output
a prepared transaction has been sitting in pg_prepared_xacts for a week. nobody remembers what it was. what's happening to the database?
sql
SELECT gid, prepared, age(transaction) FROM pg_prepared_xacts;

why it blocks, and what fixes that

once a participant votes yes, it has given away its right to abort: the coordinator may already have told someone else to commit. and it can't commit either: someone else may have voted no. only the coordinator's decision settles it, so while the coordinator is down, the participant waits. that's not a postgres bug, it's the protocol. the classic textbook answer is three-phase commit, which avoids blocking only under timing assumptions real networks break. what real systems do instead:

  • make the coordinator's decision durable and replicated. if the decision is stored with consensus, a new coordinator can read it and finish the job. spanner and CockroachDB do roughly this: 2PC across shards, with every participant and the decision itself replicated by Paxos or Raft.
  • monitor and resolve. in plain postgres, alert on any row in pg_prepared_xacts older than a few seconds, and have the transaction manager's recovery log say which way each gid went.
  • avoid it. design so that one business operation touches one database (shard by the key that keeps it local), or replace atomic commit with a saga: a sequence of local transactions with compensating actions when a later step fails.

keylines

  • phase one: prepare and vote. phase two: commit if all said yes, else roll back.
  • a prepared participant has promised; it can't decide alone.
  • coordinator down = participants stuck, holding locks.
  • in postgres, prepared transactions survive restarts and pin the xmin horizon.
  • keep max_prepared_transactions at 0 unless a transaction manager owns them.