Key takeaways
- ✓One order that changes three databases cannot use one database transaction, so two-phase commit runs in two steps: every database prepares and promises to commit, then the coordinator logs its decision and tells all three to finish.
- ✓With nothing failing, 2PC took a median of 3.2 to 4.1 ms for three databases and finished inside the request, while the sagas answered in 2.0 to 2.6 ms and finished 22 to 29 ms later.
- ✓One hot product at 300 orders a second pushed 2PC's slowest 1 in 100 from 10 to 17 ms up to 95 ms in one round and 24 ms in the other, while its median stayed near 4 ms, because each order held the stock row from its first change to its commit.
- ✓A coordinator that died after prepare, with nothing logged, left all three databases holding their locks for 5.7 s at the median (6.2 s worst), until recovery rolled them back after 5 s; the next order for the same product waited 2.8 s.
- ✓A coordinator that died after logging commit left the locks for 2.6 s at the median, then recovery committed all three: the order was confirmed with its stock reserved and its card charged, yet its request got no answer in 10 of 10 trials.
- ✓With recovery switched off, the locks held for 64 s in one run, and the next order for that product got no answer within its 60 s client timeout, which is 2PC's blocking problem.
Three databases, one order, and no single transaction that spans all three. The stock, the payment and the order each commit on their own, so something has to make them agree. Two-phase commit is the classic answer, and it has a catch that this chapter measures: the coordinator's decision is the only thing that tells the databases what to do, and when the coordinator dies in the middle, the databases wait with their locks held.
The examples come from Lab 13 (Distributed Transactions and Event Patterns) of the system design labs, script 03_2pc_crash.py for the crash, and 01_happy_path.py for the timings with nothing failing. Three services each have their own Postgres database: inventory reserves the stock, payments charges the card (simulated), and orders records the order. The orders API is the coordinator. The setup is an Apple M4 Max with Docker Desktop and 16 virtual CPUs, one laptop, with each run recorded once.
Why one transaction can't cover three services
A database transaction is a group of writes that commit or roll back together. It works inside one database. Here the stock row lives in one Postgres, the account in another and the order in a third, so no BEGIN ... COMMIT on any one of them can cover all three.
There are only two good endings for an order: confirmed, with the stock reserved and the money taken, or rejected, with nothing reserved and nothing taken. Anything in between is a bug. Two-phase commit (2PC) is one way to force that. Its cost, which the rest of this chapter measures, is that the databases must hold their locks while they wait for the decision.
Think of booking a trip. A travel agent can put a flight, a hotel and a car on hold, then confirm all three together. A hold is a lock: nobody else can book that seat until the hold is released.
Prepare, the decision, commit
2PC runs in two phases, and the coordinator works through them in order.
- Do the work. The coordinator opens a transaction in each of the three databases and makes the changes: reserve the stock, charge the card, write the order.
- Phase one, prepare. It asks each database to prepare. In Postgres this is
PREPARE TRANSACTION: the database writes everything to disk and promises it can commit, even after a crash. A participant that has prepared cannot decide the outcome by itself. It keeps its locks until someone tells it to commit or roll back. - Log the decision. Only if every participant said yes, the coordinator writes "commit" to its decision log, a table called
tpc_login the orders database. This row is the record of the decision. Without it, a restarted coordinator could not tell "decided commit" from "never decided". - Phase two, commit. The coordinator tells each database to finish with
COMMIT PREPARED. The locks are released, and when the request returns, the order is done.
If any participant says no in phase one, the coordinator rolls everything back. The lab's code marks the phase-two step so that the recovery loop, described below, can finish it for a slow coordinator without causing an error.
What a waiting participant holds
Between prepare and commit, a participant is in doubt: it promised, and it doesn't know the outcome. Its locks cover every row the transaction touched. In the lab, that was the order row, the stock row and its index, and the customer's account row. A second order for the same product or the same customer has to wait for those locks.
The lab checked this directly. After the coordinator died, pg_prepared_xacts (a Postgres view of prepared transactions) still listed one transaction in each database, and the lock table showed locks with no process attached. Restarting the orders API changed nothing. Only COMMIT PREPARED or ROLLBACK PREPARED releases them, and only a process that knows the decision can run one.
The sourced workflow
The crash script runs one order (order A) whose coordinator exits on purpose at a chosen point, with os._exit, a hard exit with no cleanup. A second order (order B), for the same product and the same customer, arrives as soon as the API is back, about three seconds later. Ten trials per crash point, with the recovery loop on, then one 60 s run with it off.
| Crash point | In doubt (orders / stock / payments) | Locks held, median / worst | Order B waited, median / worst | Order A ended as (order / stock / payment) |
|---|---|---|---|---|
| after prepare, nothing logged | 1 / 1 / 1 | 5.7 / 6.2 s | 2.8 / 3.1 s | none / none / none |
| after the decision is logged | 1 / 1 / 1 | 2.6 / 3.1 s | 0.0 / 0.1 s | CONFIRMED / reserved / captured |
Order A's request got no answer in all 20 trials. The lock times are counted from when A was sent, and order B's wait from when B arrived.
Locks held: 5.7 s median, 6.2 s worst
- Order B waited:
- 2.8 s median, 3.1 s worst
- Order A ended as:
- none / none / none (rolled back)
Presumed abort: the loop rolled all three back after 5 s.
Locks held: 2.6 s median, 3.1 s worst
- Order B waited:
- 0.0 s median, 0.1 s worst
- Order A ended as:
- CONFIRMED / reserved / captured
The loop committed all three once the transactions were 2 s old.
Locks held: still locked at 60 s; released at 64 s when recovery came back
- Order B waited:
- no answer within its 60 s timeout
- Order A ended as:
- none / none / none, after recovery was switched back on
In doubt after 60 s: 1 / 1 / 1. Nothing moved until someone committed or rolled back.
Bars show seconds the prepared transactions held their rows, from order A's send. The thin tick marks the worst trial. The first two cases are on one scale with the 60 s run, so they look short next to it.
Crashed after prepare, nothing logged. The participants are in doubt, and no log says commit. The recovery loop rolls the three back after 5 s. This is called presumed abort: with no record of a commit, the coordinator is taken to have aborted. Order B waited on the same rows and went through about 3 s after it arrived.
Crashed after the decision was logged. The log says commit, so recovery commits all three once they have been prepared for 2 s. The order ended CONFIRMED with the stock reserved and the card charged. The customer's client saw a connection error, so the order happened, and the customer did not know. Order B, arriving as the API came back, barely waited.
The recovery loop
Recovery is a separate process that wakes every half second, looks for prepared transactions left in each database, and checks the coordinator's log for each one. The rule is short:
- If the log says commit, commit, but only once the transaction is more than 2 s old. The grace period gives a live coordinator time to finish its own commit.
- If nothing is logged, roll back once it is more than 5 s old (presumed abort).
The grace period exists because the first version of recovery had a race. It committed transactions whose coordinator was alive and about to commit, so the coordinator's own commit then failed and the customer was told the order had failed when it had succeeded. A recovery process that can run while the thing it recovers is still alive is the usual form of this bug. The fix was the 2 s grace and treating "someone already committed it" as success in phase two.
Without recovery
With the loop switched off for 60 s, all three prepared transactions were still in doubt after a minute. The locks were held for 64 s in that run, until recovery was switched back on. Order B got no answer within its client's 60 s timeout, and any other order for the same product or the same customer would have waited too.
This is 2PC's blocking problem. A participant that has prepared cannot move on alone, so if the coordinator dies at the wrong moment and nothing finishes the transaction, the data stays locked until someone steps in. The coordinator's log and the recovery that reads it are therefore part of the protocol, not an extra.
When nothing fails, and one hot product
With no failures, at 100 and then 300 orders a second for 20 seconds over 100 products (two rounds each), 2PC took a median of 3.2 to 4.1 ms for three databases, and finished inside the request. The sagas, which split the order into local transactions passed on by messages, answered in 2.0 to 2.6 ms. Their orders finished 22 to 29 ms later, because each message waits for an outbox relay that polls every 10 ms. Across a real network, each of 2PC's round trips would add more, so on one laptop, 2PC was not slow.
When every order wants the same product, 2PC's slowest 1 in 100 jumped. At 300 orders a second, it was 95 ms in one round and 24 ms in the other, against 10 to 17 ms over 100 products. Its median stayed near 4 ms. Each 2PC order holds the stock row from its first change until its commit, so orders that arrive together queue behind each other. The sagas' slowest answers stayed at 5 to 8 ms, because their inventory step holds the row only for one short local transaction.
Caveats
- One coordinator, one log. The lab's decision log is a single table in one database. The lab did not test a second coordinator, a standby, or a replicated log. A replicated log needs a consensus protocol or synchronous replication, which Chapter 17 covers.
- Crashes are injected, at named points. The coordinator exits at chosen points through the lab's code. Real failures can strike anywhere, including during the log write itself, and the lab did not test every point.
- Participant failures were not tested. The crash was the coordinator's. A participant that dies while prepared, or a network partition between the coordinator and one database, is a different case.
- Ten trials per point. The medians are from 10 trials each, on one laptop with Docker, so read the shape and the order of magnitude. The 60 s run was one run.
- Simulated card charge. The payment is a simulated step, not a real card processor.
- This chapter's runs are not the sagas' failure runs. The sagas' answer-then-finish timing is measured here with nothing failing. Their in-between state under crashes is the subject of the next chapter.
The checklist
- Use 2PC only where the answer must be final, and you can run its recovery. Its answer is final when the request returns, but a crash in the middle locks the rows until recovery runs.
- Write the decision log before phase two, and keep it durable. Without it, a restarted coordinator cannot tell commit from abort.
- Run the recovery loop with a grace period. Recovery must not touch a transaction a live coordinator is still finishing.
- Measure the lock time, not just the median. The hot product moved the slowest 1 in 100, not the median.
- Expect a crashed coordinator to block its rows until recovery runs. In the lab, that was 5.7 s with recovery and 64 s without.
Quiz
1.The coordinator logged commit, then crashed before telling the databases to finish. What does the recovery loop do with the prepared transactions?
2.A database has answered yes to prepare, then restarts. Why does it still hold its locks when it comes back?
3.At 300 orders a second for one product, 2PC's median answer stayed near 4 ms, but its slowest 1 in 100 rose to 24 to 95 ms. Why did only the tail move?
Check your understanding
Try each question before opening its answer.
The coordinator logged commit and then crashed. Why did the order end CONFIRMED, and why did the customer still see an error?
The decision was in the log, so recovery committed all three prepared transactions once they were 2 s old. The stock was reserved and the card charged. The customer's request never got an answer, because the coordinator died before it replied, so the order happened and the customer did not know.
Why does the recovery loop wait 2 s before committing a transaction that its log says to commit, instead of acting at once?
A live coordinator may still be finishing the same commit. An earlier version of recovery committed transactions it had not yet finished, and the coordinator's own commit then failed. The 2 s grace period lets a live coordinator finish first. A transaction younger than that is left alone.
Why did 2PC finish inside the request, while the sagas finished 22 to 29 ms after their answer?
2PC makes its changes and both phases inside the request, so the answer comes when the three databases have committed. The sagas answer as soon as the order is saved as pending. Each later step is a message that goes through an outbox relay polling every 10 ms, so each of their three or four hops adds about 7 to 8 ms.
Without recovery, the next order for the same product got no answer in 60 s. Could the second order have fixed it by retrying?
Not while the locks stayed held. The prepared transactions kept the stock and account rows locked with no process left to release them, so a retry waits on the same rows. Only a commit or rollback of the prepared transactions frees them, and that needs the coordinator's log or a person.
Next up: Chapter 30, sagas and reconciliation. Sagas answer at once and leave an in-between state, so the next chapter runs a thousand orders with a crash every few hundred milliseconds, and checks each order against the three databases.