Two-stage processing
medium 30 minTwo-stage processing, known as two-phase commit (2PC), makes several databases commit or abort together.
See it run
Votes, decision, and every place where somebody can crash.
Operations
Commit
All three databases vote yes.
Step 1 of 7
Transaction request
Init
A client starts a transaction over three databases.
Step 1: Transaction request
def run(tx): votes = [p.prepare(tx) for p in participants] if all(votes): log("COMMIT", tx) tell_all("commit", tx) else: log("ABORT", tx) tell_all("abort", tx) wait_for_acks(tx)- Rounds
- 2
- Locks held
- Until commit
- Local commit
- no round trips
The commit counts from the moment it is in the coordinator's log.
In the real world
The same two-phase commit doing real jobs. Pick one and step through it.
A team keeps adding participants to one transaction.
Step 1 of 4
Two databases
About 5 ms of locks
Fast enough. Both are in the same data centre.
Step 1: Two databases
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Voting yes before the log is on disk
criticalAfter a crash the promise is gone, and the others have committed.
Wrongvote("YES")wal.write("PREPARE")Rightwal.write("PREPARE")wal.flush()vote("YES")Guessing when in doubt
criticalHalf of the databases may have the other outcome.
Wrongon_timeout: abort() # after a yesRighton_timeout: ask_coordinator() ask_others() wait()Reporting failure after COMMIT
criticalThe transaction is committed. The client retries and buys twice.
Wrongexcept SendError: return FalseRightexcept SendError: keep_retrying(tx)return TrueNot watching prepared transactions
majorA forgotten one holds locks for days and survives restarts.
Wrong# no dashboardRightalert_if(prepared_age > minutes(5))
Interview tips
How to explain it
- Ask everyone, then tell everyone.
- All yes, or abort.
- Atomic, but blocking.
Memory trick: PREP
- Prepare asks all to vote.
- Response is yes or no.
- Execute commit if all said yes.
- Persist logs.
Good fit
- Few databases.
- Close together.
- Short work.
Use something else
- Microservices: a saga.
- Long work: a saga.
- High availability: consensus groups.