AlgoViz

Two-stage processing

medium 30 min

Two-stage processing, known as two-phase commit (2PC), makes several databases commit or abort together.

Video lesson · Chapter 1 of 5

Three vaults must agree on one transfer

0:00 / 3:33

Theory

Read or listen first. About 2 min.

What it is

Two-phase commit is a protocol for one transaction that touches several machines. A coordinator runs it, and each database is a participant. In phase 1 the coordinator asks: can you commit? In phase 2 it announces the decision, and everybody follows it.

The rule is simple. If all participants vote yes, the decision is commit. If even one votes no, or does not answer in time, the decision is abort. A short version: first ask everyone whether they can commit, then tell everyone to commit or to abort.

Why it exists

If you just send "commit" to three databases, one may crash or refuse while the others have committed. Nobody can take that back. Asking first removes that risk, because a yes vote is a promise: I have saved everything I need, and I can commit even after a crash.

The promise has a price. Between the yes vote and the decision, a participant may not change its mind. It keeps its locks and waits. If the coordinator disappears in that moment, the participant is in doubt and blocked.

A short history

  1. 1978

    Jim Gray's "Notes on Data Base Operating Systems" appears in Lecture Notes in Computer Science 60 and describes two-phase commit.

  2. 8 November 2005

    PostgreSQL 8.1 is released and adds two-phase commit, so that a transaction can be prepared on several computers.

  3. 2006

    Jim Gray and Leslie Lamport publish "Consensus on Transaction Commit", which uses consensus so that one failed coordinator cannot block the decision.

  4. 2012

    Google's Spanner paper appears. Its documentation describes two-phase commit for writes that touch several splits.

Words to know

Coordinator
The process that collects votes and decides.
Participant
A database or service that takes part and votes.
Prepare
Save enough to be able to commit or abort later, even after a crash.
Vote
Yes is a promise; no is a veto.
In doubt
Voted yes, and does not know the decision yet.
Write-ahead log
Records that are on disk before the change counts.
XA
A technical standard for distributed transactions between a transaction manager and databases.

How it works

Step through the idea, or press Play.

Step 1 of 3

Prepare. Ask everyone. Each saves its work, locks it and votes

Understand it

Start here

Ready? Pull!

A crew pulls heavy stones with a rope. If only two people pull, the rope burns their hands. So the captain always asks first, and calls "pull" only after hearing yes from everybody.

The rope crew and the captain
Ready?The captain asks

The last picture is the weakness of the whole protocol.

The idea

Parts and properties

One coordinator, three participants

An application asks the coordinator, which keeps its own decision log. The coordinator sends prepare and then the decision to three databases. Each database is a separate machine with its own write-ahead log.
Two kinds of log matter: the decision log of the coordinator and the write-ahead log of each participant.
  • Atomic

    All or nothing over all participants.

  • Phase 1

    Prepare and vote.

  • Phase 2

    Commit or abort.

  • Coordinator

    One place that decides.

  • Blocking

    Participants may wait with locks held.

  • Logging

    Votes and decisions survive a crash.

Phase 1

Prepare and vote

CoordinatorParticipant
Makes a transaction idTakes the locks it needs
May log that it is preparingRuns the work locally
Sends PREPARE to allWrites undo and redo records and the prepare record to its log
Waits for all votes, with a timeoutVotes yes (ready) or no (cannot)
A yes is allowed only after the prepare record is safely on disk.

Everyone says yes

The moment the coordinator's COMMIT record reaches the disk, the transaction is committed.

Phase 2

Commit or abort

All voted yes

  • Coordinator logs COMMIT
  • It sends COMMIT to all
  • Participants make the change permanent
  • They free their locks
  • They send ACK

Any no, or silence

  • Coordinator decides ABORT
  • It sends ABORT to all
  • Participants roll back using their log
  • They free their locks
  • They send ACK

One says no

The participant that voted no has already aborted. It needs no message.

Timeline

MomentWhat happens
StartThe client begins the transaction
PrepareThe coordinator sends PREPARE
VoteParticipants vote yes or no
DecisionThe coordinator decides commit or abort and logs it
ExecuteParticipants commit or roll back
CompleteAll acknowledged; the coordinator may forget

Trouble

The blocking case

How it gets stuck

  1. 1

    PREPARE is sent

    All participants receive it.

  2. 2

    Everyone votes yes

    Locks are held.

  3. 3

    The coordinator logs COMMIT

    The decision exists in one place only.

  4. 4

    It crashes before telling anyone

    No participant has heard the decision.

  5. 5

    Participants wait

    They cannot commit, because it may be abort. They cannot abort, because it may be commit.

They are stuck until the coordinator comes back or someone who knows the decision answers. That may be seconds or hours. Guessing breaks atomicity.

May I decide alone?

Asking the other participants often helps. It does not help when all of them voted yes and nobody heard the decision.

Four problems

ProblemWhyImpact
BlockingLocks are held while waiting for the decisionA coordinator crash after the votes blocks other work
Single point of failureOne coordinator decidesThe transaction hangs until it recovers
Network partitionSome participants cannot be reachedBefore the votes: abort. After them: wait
PerformanceTwo rounds and several disk flushesMore latency than a local commit, and locks held longer

Recovery

What the logs are for

The coordinator restarts

Last recordAction
No decisionAbort: nobody can have committed
COMMITSend COMMIT again until all acknowledge
ABORTSend ABORT again until all acknowledge
DoneNothing
Treating a missing decision as abort is called presumed abort.

States of a participant

PREPARED is the in-doubt state. A participant cannot leave it alone.

Numbers

What it costs

Messages

4n=4×3=12 messages for 3 participants4n = 4 \times 3 = 12\ \text{messages for 3 participants}
Prepare, vote, decision and acknowledgement, for each participant.

How long is a lock held?

t≥f+r+f2+1+2=5 ms2+80+2=84 mst \ge f + r + f \qquad 2 + 1 + 2 = 5\ \text{ms} \qquad 2 + 80 + 2 = 84\ \text{ms}
Here f is one disk flush (assume 2 ms) and r one round trip (assume 1 ms in one data centre, 80 ms between continents). One busy row can then change at most 1000 / 5 = 200 times a second, or about 12 times across continents.

Everyone must be up

0.999 5+1≈0.9940.999^{\,5+1} \approx 0.994
Five participants and one coordinator, each up 99.9% of the time and failing independently. More participants mean more aborted or blocked work.

Alternatives

Other ways to agree

WayIdeaGoodBad
Three-phase commitAdds a pre-commit phaseDoes not block for some crashes; participants may time outNot safe in a network partition, more complex
SagaLocal transactions with compensationsNo distributed locks, availableEventual consistency, undo code
Try, Confirm, CancelReserve first, then confirm or cancelBusiness-level, flexibleNeeds idempotency, more code
EventsPublish and reactLoosely coupled, scalesEventual consistency, harder to debug
2PC over consensusEach participant and the coordinator is a replicated groupOne machine cannot block itMore messages, a special database
Spanner uses the last form: splits are replicated groups. For events see pub/sub and change data capture.

What to use when

When to use it

Use cases

Good fit

  • A transfer between two databases that must be atomic
  • Stock and order rows in two databases of one team
  • One transaction over several databases
  • XA transactions between a database and a message broker that support it

Avoid it

  • Systems that must stay available: blocking reduces it
  • Many participants: one failure is likely
  • Across distant data centres: latency stretches the locks
  • Long transactions: locks are held too long

Do

  • Keep the decision log durable
  • Set a timeout for votes
  • Make commit and abort idempotent
  • Use a write-ahead log in every participant
  • Monitor prepared transactions that are stuck

Do not

  • Use it where availability comes first
  • Include many participants
  • Run it across far regions without need
  • Forget that the coordinator can fail
  • Hold locks while a person thinks

Summary

The whole topic in one minute.

Two-phase commit makes several participants commit or abort as one. Phase 1 collects votes, phase 2 spreads the decision. Commit needs every vote to be yes. One no, or one silence, means abort.

The protocol is safe, but it can block. A participant that voted yes keeps its locks until it learns the decision. Use it for short work over a few databases that are close together, replicate the coordinator's log, and watch for transactions stuck in doubt. For long processes over services, use a saga.

  • Phase 1 asks and collects votes; phase 2 spreads the decision.
  • Commit needs every yes. One no or one silence aborts.
  • A yes vote is a promise that survives a crash.
  • In doubt means blocked: wait for the decision, never guess.
  • Short work, few participants, close together. Otherwise use a saga.

Sources