Two-phase commit
Overview
Two-phase commit (2PC) coordinates one atomic transaction across participants. During prepare, each participant votes whether it can commit and durably records its prepared state if voting yes. The coordinator durably chooses commit only after all required yes votes, otherwise abort when appropriate. During the decision phase participants learn and apply that decision. A prepared participant may need to wait if the coordinator is unavailable.
First example
SELECT tx,CASE WHEN SUM(vote='no')>0 THEN 'abort' WHEN SUM(vote='yes')=2 THEN 'eligible' ELSE 'wait' END FROM dd_vote GROUP BY tx ORDER BY tx;Observed SQLite result (rows in JSON):
[ [ "t1", "eligible" ], [ "t2", "wait" ], [ "t3", "abort" ]]How it works
The vote table contains three synthetic transactions. t1 has two yes votes, t2 has a pending participant and t3 has a no vote. A trigger prevents inserting a commit decision without both yes votes. This is a local decision guard, not durable distributed prepare, a recovery protocol, an isolation guarantee or consensus. Real coordinators need durable decision records, retry-safe messaging and resolution of in-doubt transactions; after a durable commit decision, a timeout cannot turn it into abort. PostgreSQL prepared transactions can retain locks; inspect pg_prepared_xacts on an authorized server and do not abandon prepared transactions.
Practical example
BEGIN;INSERT INTO dd_decision VALUES('t1','commit');SELECT tx,decision FROM dd_decision;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ "t1", "commit" ]]Practice and mistakes
Practice: classify t2 and t3; attempt inserting a commit for t2 in a disposable database. Hint 1: count yes votes. Hint 2: pending is not yes; inspect the guard. Do not mistake PREPARE for PREPARE TRANSACTION or run unresolved prepared writes in production.
PostgreSQL 17 example — NOT RUN
SELECT gid,prepared,owner,database FROM pg_prepared_xacts ORDER BY gid;Expected result, not executed: "Read-only inspection; may be empty. No transaction is prepared or resolved by this query."