Lesson 11 of 19
17. Transactions and Locking

17.10 What is two-phase commit?

3 min read+10 XP

Across services

On the train: A journey needs a seat from the train company, a meal from the caterer and a payment from the bank. A coordinator phones each: "Can you commit?" Only if all say yes does it phone again: "Commit." If any says no, it tells everyone "cancel".

In the system: Two-phase commit (2PC) makes one transaction span several databases or services:

  1. Prepare: the coordinator asks every participant to get ready. Each does the work, writes it durably, locks what it needs, and votes yes (promising it can commit) or no.
  2. Commit or abort: if every vote is yes, the coordinator tells all to commit; otherwise, all abort.

It's all-or-nothing across systems, and standards like XA support it.

The problems:

  • Blocking: a participant that voted yes must wait, holding its locks, until it hears the decision. If the coordinator crashes at that moment, participants can be stuck until it recovers.
  • Slow: at least two rounds of messages to every participant, with locks held throughout.
  • Everyone must support it, which many services and message brokers don't.

So 2PC is used inside some distributed databases and between a few tightly controlled systems, but rarely between independent microservices.

Memory code: "Everyone says 'ready', then everyone says 'done'; one 'no' cancels all."