Sub topic 16
Distributed transactions and two-phase commit
Prerequisites
This chapter assumes you know what atomicity and durability mean, how COMMIT and ROLLBACK work, and how write-ahead logging lets a database recover after a crash. It uses PostgreSQL syntax in its examples. Earlier chapters covered transactions inside one database. Here the transaction spans several.
Why one database is not always enough
Everything so far relied on a single database engine. One engine has one log and one commit point, so it can make a group of changes atomic. A distributed transaction is a transaction whose changes land in more than one independent resource manager. A resource manager is any system that can hold transactional state: a second database, a message broker, or a different PostgreSQL server.
Here are common situations that need one:
- An order service writes to its own database, and a payment service writes to another.
- Data is split across shards, and one transfer touches accounts on two shards.
- An application writes a row and publishes a message, and both must happen or neither.
Suppose account 1 lives on server A and account 2 lives on server B. The transfer from the first chapter now needs two COMMITs, one per server. Nothing makes those two commits happen together.
-- Connection to server A
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
COMMIT; -- succeeds
-- The application crashes here, before it talks to server B.
-- Connection to server B (never executed)
BEGIN;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;The 30 units have left account 1 and never arrived in account 2. Each server is internally consistent, yet atomicity across the two is lost. Reordering the statements only moves the problem: you would create money instead of destroying it.
The core problem: agreeing on one outcome
All participants must reach the same decision, commit or abort, even if processes and networks fail at any moment. This is the atomic commitment problem. A participant cannot commit on its own, because another participant might be unable to. It also cannot wait forever, because it holds locks and resources while it waits.
Two-phase commit (2PC) is the classic protocol for it. It introduces a coordinator, which drives the decision, and the participants, which each hold part of the transaction.
How two-phase commit works
Phase 1: prepare (the voting phase)
The coordinator sends PREPARE to every participant. Each participant checks that it can commit. It verifies constraints, takes its locks, and writes all its changes and a "prepared" record to its write-ahead log, then flushes the log to disk. After that it replies YES or NO.
A YES vote is a promise. The participant has made the transaction durable enough that it can commit later even after a crash and restart. It gives up the right to abort on its own. It keeps its locks until it hears the final decision.
Phase 2: commit or abort
If every participant voted YES, the coordinator writes a COMMIT decision to its own durable log and then sends COMMIT to all participants. If any participant voted NO, or did not answer in time, the coordinator decides ABORT and sends ROLLBACK to all of them.
The coordinator's log write is the commit point. Once the decision is on disk, the transaction is committed, even if no participant has been told yet.
Two-phase commit in PostgreSQL
PostgreSQL exposes the participant side as prepared transactions. The commands are PREPARE TRANSACTION, COMMIT PREPARED and ROLLBACK PREPARED. PostgreSQL does not include a coordinator. Your application, or a transaction manager, plays that role.
The feature is off by default. Set max_prepared_transactions to a value greater than zero in postgresql.conf and restart the server.
-- On server A
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
PREPARE TRANSACTION 'transfer-1001-a';
-- On server B
BEGIN;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
PREPARE TRANSACTION 'transfer-1001-b';
-- Both prepares succeeded, so the coordinator decides to commit.
-- On server A
COMMIT PREPARED 'transfer-1001-a';
-- On server B
COMMIT PREPARED 'transfer-1001-b';After PREPARE TRANSACTION, the session no longer owns the transaction. It is stored on disk under the global identifier you chose, and it survives a restart. Any later session can finish it with COMMIT PREPARED or ROLLBACK PREPARED. If either prepare had failed, the coordinator would run ROLLBACK PREPARED on the one that succeeded.
You can list unfinished prepared transactions with a query:
SELECT gid, prepared, owner, database
FROM pg_prepared_xacts;Failure modes
2PC handles crashes correctly, but some failures leave participants waiting. The trade-offs below are the reason many systems avoid it.
| Failure | What happens | Consequence |
|---|---|---|
| A participant crashes before voting | The coordinator times out and aborts | Safe. The transaction rolls back. |
| A participant crashes after voting YES | On restart it reads its log, sees it is prepared, and asks the coordinator for the outcome | Safe, but the transaction waits for recovery. |
| The coordinator crashes before logging a decision | Participants are prepared and do not know the outcome | They block, holding locks, until the coordinator returns. |
| The coordinator crashes after logging COMMIT but before telling everyone | Participants block until the coordinator recovers and resends the decision | Safe in the end, but with a delay. |
| The network drops messages | Timeouts fire. Before voting, a participant may abort. After voting YES, it must wait. | Blocking again. |
The central weakness is the blocking behavior in the prepared state. A participant that voted YES cannot safely commit or abort by itself. If it aborts and the coordinator had decided to commit, atomicity breaks. It can only wait. During that time its locks stay in place, so other transactions that need the same rows wait too.
A third phase (three-phase commit) reduces blocking in theory, but it assumes a network that does not partition and is rarely used in practice. Systems that need non-blocking commit usually replicate the coordinator's state with a consensus protocol such as Raft or Paxos. Google Spanner does this, running 2PC across replicated groups.
Why it is costly
- Latency. Each commit needs at least two network round trips and several forced disk writes: one per participant at prepare, one at the coordinator, and one per participant at commit.
- Lock duration. Locks are held across the whole protocol, not just the local work. A slow participant extends the wait for everyone.
- Availability. The transaction can commit only if all participants are reachable. With more participants, the chance that at least one is down grows.
- Operational burden. You must run and monitor a coordinator, handle in-doubt transactions after failures, and sometimes resolve them by hand.
Alternatives
Many systems avoid distributed commit and accept weaker guarantees instead.
- Keep the data together. If two pieces of data must change atomically, store them in the same database. This is often the best answer.
- Saga. Split the work into a series of local transactions. If a later step fails, run compensating transactions that undo the earlier steps, for example refunding a payment. A saga gives eventual consistency but not isolation: other readers can see intermediate states.
- Transactional outbox. Write the business change and a message row in one local transaction. A separate process reads the outbox table and publishes the messages. Delivery is at least once, so consumers must tolerate duplicates.
- Idempotent operations. Give each operation a unique key so that retrying it after a failure has no extra effect.
The next table compares the approaches.
| Approach | Atomic across systems | Isolation | Cost |
|---|---|---|---|
| Two-phase commit | Yes | Yes, through locks held until commit | High latency, blocking on failure |
| Saga | No, eventually consistent | No | Needs compensation logic |
| Transactional outbox | Eventually | Local only | Needs a relay and duplicate handling |
| Single database | Yes | Yes | Limits how you split the system |
Decision criteria
Choose 2PC when all of these hold: the participants are few, they are in a reliable network, you control all of them, and you need strong atomicity and isolation. Typical cases are a database plus a transactional message queue inside one data center, or a database engine that uses 2PC internally across its own shards. Avoid it across services owned by different teams, across slow or unreliable links, or on hot rows where long lock holding hurts throughput.
Exercise
A coordinator sends PREPARE to two participants. Both reply YES. The coordinator writes COMMIT to its log and then crashes before sending any COMMIT message. What should the participants do, and why can't they simply abort?
Show answer
They must wait for the coordinator to recover (or for another process to read its log) and learn the decision. They cannot abort because a YES vote is a promise to commit if told to, and the coordinator has already recorded COMMIT as the outcome. If they aborted on their own, they would contradict the committed decision and break atomicity. Meanwhile they keep their locks, which is the blocking problem of 2PC.
Exercise
In PostgreSQL, what happens to a transaction after PREPARE TRANSACTION 'x' when the server restarts, and what must you do to avoid harm if the coordinator never comes back?
Show answer
The prepared transaction survives the restart because its state is written to disk. It still holds its locks. You must find it in pgpreparedxacts and finish it manually with COMMIT PREPARED 'x' or ROLLBACK PREPARED 'x', after checking what the other participants did. Otherwise it blocks writers and holds back vacuum.