liveBook · Manning

Two-phase commit

As explained in PostgreSQL Mistakes and How to Avoid Them

Two-phase commit is a distributed transaction protocol in which participants first prepare to commit and then commit or abort based on a coordinator decision.

Two-phase commit (2PC) coordinates an atomic transaction across database nodes: participants prepare first, then commit or abort according to the coordinator’s decision. PostgreSQL can protect each local transaction while an application still violates atomicity across nodes. section 5.6

The split account update

Suppose alpha debits an account from 100 to 90 while beta applies a gift and records 150. The business loses 10 while the customer receives an unintended 50: local ACID guarantees did not make the cross-node operation atomic. PREPARE TRANSACTION and its associated commands provide the two-phase mechanism, but prepared transactions should remain short-lived. section 5.6

Treat 2PC as a constrained operational tool:

  • Expect latency and replication lag to complicate prepared transactions. section 5.6
  • Run prepared transactions exclusively on the primary, potentially eliminating read-replica benefits. section 5.6
  • Clean up incomplete transactions because they retain locks and may delay applications after crashes or restarts. section 5.6

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Defines the prepare-and-decision protocol and operational hazards, but does not provide a complete implementation procedure.
Examples
Uses alpha and beta account updates, PostgreSQL account fixtures, and a lost-money versus unexpected-gift scenario.
What it assumes
Assumes database and transaction fundamentals while grounding the problem in ACID properties and distributed transactions.
What you can do after
Evaluate cross-node atomicity failures and judge when prepared transactions’ locking and recovery costs outweigh their benefits.
How it connects
Connects distributed transactions with ACID atomicity, replication lag, read replicas, locking, and serialization anomalies.

Also explained in

Compare how 4 books explain two-phase commit →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.