ealeng

Episode 29 of 55 · Distributed transactions

Two-phase commit: the coordinator died mid-commit, and the stock stayed locked for a minute without recovery

An order changes three databases, the stock, the payment and the order, and no single transaction can cover all three. Two-phase commit (2PC) makes them agree in two steps. Crashed on purpose between the steps, the coordinator left the stock and the customer's account locked for 5.7 s with a recovery loop, and for 64 s without one, while the next order for that product got no answer. How prepare, the decision log and commit work, what a waiting participant holds, and why recovery is part of the protocol.

Lab 13 · Distributed Transactions and Event Patterns10 min read
Video transcript10:01

0:00Cold open

0:01

One order changes three databases: the stock, the payment, and the order itself. I made all three commit together, with a protocol called two-phase commit. Then I made its coordinator, the part that tells the databases when to commit, crash on purpose, right after all three had said “ready”.

0:21

The stock and the customer’s account stayed locked for almost six seconds, until a recovery loop cleaned up.

0:29

With that recovery switched off, they were still locked after a minute.

0:35

And with recovery off, the next order for the same product got no answer within a minute.

0:42

So when is two-phase commit worth it, and what do the alternatives do instead?

0:49Intro

0:50

Hands-on system design, part twenty-nine.

0:54

Today: one order across three databases, with two-phase commit or with a saga.

1:01Meet Lucía

1:02

I’m Lucía, a platform engineer.

1:05

An order needs three services, each with its own Postgres database: inventory reserves the stock, payments charges the card, simulated here, and orders confirms the order. No single database transaction can cover all three.

1:22

And yet there are only two good endings. Confirmed, with the stock reserved and the money taken. Or rejected, with nothing reserved and nothing taken. Anything in between is a bug.

1:35

Think of booking a trip: a flight, a hotel and a car. A travel agent can put all three on hold and then confirm them together. Or you book each one yourself, and cancel the others if one fails. A hold means nobody else can book that seat. In a database, that hold is a lock: other transactions that want the row must wait.

1:5801 · What you need

1:59

To run it yourself: Docker for three Postgres databases, Kafka, and the services. The quick tests run in a couple of seconds, without Docker.

2:10

No cloud, and nothing to pay for.

2:1502 · Two-phase commit

2:16

Two-phase commit, or 2PC. The orders service acts as the coordinator.

2:23

It opens a transaction in each of the three databases, and does the work: reserve the stock, charge the card, write the order.

2:32

Phase one: it asks each database to prepare, the “ready” from the cold open. Each one writes everything to disk and promises it can commit. From here, it keeps its locks, even across a restart, until it’s told what to do.

2:48

Then the coordinator writes its decision, commit, to its own log.

2:54

Phase two: it tells all three to commit, and the locks are released. When the request returns, the order is done.

3:0303 · A saga

3:05

The other way is a saga: a chain of small, local transactions, one per service, linked by messages through Kafka. Reserve the stock, then charge the card, then confirm.

3:17

If a step fails, the earlier steps are undone by their own transactions: refund the card, release the stock. Those are called compensations.

3:28

There are two ways to run one. Choreography: each service reacts to the others’ events, and no one is in charge. Orchestration: one orchestrator sends each step and keeps the state.

3:42

Either way, the caller gets an answer as soon as the order is saved as pending, together with its first message. The stock, the card and the confirmation come afterwards. For those twenty-odd milliseconds the order says pending: an in-between state, but a visible, temporary one that always ends in one of the two good endings.

4:0404 · When nothing fails

4:05

First, with nothing failing: a hundred and then three hundred orders a second, for twenty seconds, over a hundred products. Two rounds each.

4:15

Two-phase commit took three to four milliseconds, typically, for three databases. And the order was finished when the request returned. Here, on one laptop, two-phase commit wasn’t slow. Across a real network, each of its round trips would add more.

4:33

The sagas answered sooner: two to two and a half milliseconds, one local transaction. But they finished later: twenty-two to twenty-five milliseconds with choreography.

4:45

And twenty-eight to twenty-nine with orchestration. Choreography passes three messages, or hops, between services, orchestration four, each through an outbox relay that checks every ten milliseconds. That’s about seven or eight milliseconds a hop: most likely about five waiting for the relay, plus Kafka.

5:0705 · One hot product

5:08

Now a hot product: every order wants the same one, three hundred a second, all for one stock row. Two-phase commit’s slowest answer in every hundred was ten to seventeen milliseconds with a hundred products. What happens now?

5:25

Ninety-five milliseconds in one round. Twenty-four in the other.

5:31

The sagas barely noticed: their slowest answers stayed at five to eight milliseconds, and they still finished in twenty-two to twenty-nine. The answer doesn’t touch the stock row at all, and the inventory step holds it only for its own tiny transaction.

5:49

Each two-phase order keeps the row locked from its first change until its commit. At three hundred a second, a new order arrives every three point three milliseconds, and each holds the row for part of that. Usually it’s free. When several bunch up, they queue behind each other. The typical answer stayed about four milliseconds; only the slowest waited.

6:1206 · The coordinator dies

6:14

Now the cold open, properly. Order A’s coordinator exits on purpose, between the phases. Order B, for the same product and the same customer, arrives as soon as the service is back. Ten tries at each crash point.

6:30

Crashed right after prepare, with nothing in the log yet: the locks stayed for five point seven seconds, typically, counted from when order A was sent. The service took about three seconds to restart. Order B arrived then, and waited the remaining two point eight.

6:48

Meanwhile, all three databases kept their prepared transaction: the order row, the stock row, and the customer’s account, all locked, with no process left that owned them. Restarting the service doesn’t release them. Only an explicit commit or rollback does.

7:06

Crashed right after logging “commit”: locks held two point six seconds, already gone by the time order B arrived. Order A ended confirmed, the stock reserved and the card charged. In both cases order A’s request never got an answer, ten tries out of ten. But here, the order had gone through.

7:27

In the trip picture: the agent put all three on hold, then disappeared. If his notes say confirm, someone can finish the booking, but nobody calls you back. If the notes are empty, the holds stay until someone gives up and cancels them.

7:4407 · Recovery

7:45

That cleanup is a recovery loop, in a separate process. It looks for prepared transactions left in each database.

7:54

If the coordinator’s log says commit, it commits them, once they’re two seconds old, to leave a live coordinator time to finish its own.

8:04

If nothing was logged, it rolls them back after five seconds: presumed abort. The loop looks every half second, so five to five and a half seconds, plus about two tenths for my own check: five point seven. Two plus the same: two point six.

8:2208 · Without recovery

8:23

And with that loop switched off for sixty seconds? All three prepared transactions were still there after a minute.

8:31

The locks were held for sixty-four seconds in all, until I switched recovery back on.

8:38

Order B got no answer within its client’s sixty-second timeout. With those locks held, any other order for that product, or from that customer, would have had to wait too.

8:51

That’s two-phase commit’s blocking problem. The coordinator’s log and its recovery aren’t an extra. They’re part of the protocol.

9:01Back to Lucía

9:02

So, three lessons.

9:05

Two-phase commit is fast, until one row gets hot. Then the slowest orders queue for it.

9:12

Its log and its recovery are part of it. Without them, a crash between the phases locks the data until someone steps in.

9:22

And sagas answer at once and finish a little later, with an in-between state you can see. So: two-phase commit when the answer must be final, no row is hot, and you run its recovery. A saga when you can show pending for a moment, and want no locks across services.

9:40

Next time: a thousand orders, and a crash every few hundred milliseconds.

9:46

For today: plan for the crash.Lucía: Plan for the crash.

9:50Summary

9:52

Fast until a row gets hot, a log and recovery to finish the job, and sagas that finish later.

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.

  1. 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.
  2. 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.
  3. Log the decision. Only if every participant said yes, the coordinator writes "commit" to its decision log, a table called tpc_log in the orders database. This row is the record of the decision. Without it, a restarted coordinator could not tell "decided commit" from "never decided".
  4. 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.

Try it · Locks after the coordinator diesLab 13 · 03_2pc_crash.py · 10 trials per crash point
Crash after prepare, nothing loggedRecovery on

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.

Crash after the commit is loggedRecovery on

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.

Crash after prepare, recovery switched offRecovery off, 60 s

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.

0 s10 s20 s30 s40 s50 s60 s

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

  1. 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.
  2. Write the decision log before phase two, and keep it durable. Without it, a restarted coordinator cannot tell commit from abort.
  3. Run the recovery loop with a grace period. Recovery must not touch a transaction a live coordinator is still finishing.
  4. Measure the lock time, not just the median. The hot product moved the slowest 1 in 100, not the median.
  5. 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

Try it · Check your understanding0 of 3 answered
  1. 1.The coordinator logged commit, then crashed before telling the databases to finish. What does the recovery loop do with the prepared transactions?

  2. 2.A database has answered yes to prepare, then restarts. Why does it still hold its locks when it comes back?

  3. 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.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.