Distributed transactions: 2PC, Percolator, and Spanner's clock
One commit across many machines: the protocol that blocks, the three designs that stop it blocking, and the clocks they lean on
A two-phase commit coordinator sends PREPARE to two participants. Both vote YES and wait. The coordinator then crashes before telling anyone the outcome. After 30 seconds participant P1 times out. What can P1 safely do on its own?
Every chapter so far committed a transaction in one place. Postgres writes a commit record to its WAL, flushes it, and the transaction is durable and visible all at once. One record, one flush, one moment. Sharding (in Partitioning and sharding) and splitting data between services take that away. When a sale has to decrement stock on one machine and write a ledger entry on another, there is no single record whose flush makes both happen. Something has to make two machines agree, and keep agreeing through crashes, on whether the transaction happened.
This chapter covers the classic answer and its failure, then three designs that remove the failure by changing where the decision lives: Percolator puts it in a storage row, Spanner in a Paxos group plus a clock with known error, CockroachDB in a Raft-replicated transaction record plus a hybrid clock. The lab makes Postgres 2PC block for real and then watches CockroachDB commit across two ranges and clean up after a dead gateway.
Two-phase commit
The protocol has a coordinator and several participants. Each participant can run a local transaction and can promise to commit it later.
- Prepare. The coordinator sends PREPARE to every participant. Each one does all the work of its local transaction, checks constraints, takes its locks, and forces a log record saying “prepared” to disk. Then it votes YES. A participant that cannot commit votes NO and rolls back. After voting YES a participant may not change its mind and may not decide alone.
- Commit. If every vote is YES, the coordinator forces COMMIT to its own log. That log write is the commit point. Then it sends COMMIT to everyone. If any vote is NO, or one does not arrive in time, it decides ABORT. Participants apply the decision, release locks and acknowledge. The coordinator can forget the transaction once everyone has acknowledged.
The cost is two network round trips and at least three forced log writes (each participant’s prepare, the coordinator’s decision, each participant’s commit) on the critical path, plus locks held across all of them. Inside one data centre that is a few milliseconds. Across regions it is hundreds.
The cost that matters is the uncertainty window. Between voting YES and hearing the decision, a participant is stuck. If the coordinator crashes in that window, every participant that voted YES holds its locks until the coordinator comes back and reads its log. If it never logged a decision it uses presumed abort: no record means abort, so it tells everyone to roll back. If it did log COMMIT, it resends COMMIT. Either way, the locks are held for as long as the coordinator is down. A coordinator that is down for an hour holds locks for an hour.
The ATLAS lesson Two-phase commit builds this protocol step by step. The simulation lets you crash the coordinator at each point:
// Coordinator, after collecting votes:
decision = allYes(votes) ? COMMIT : ABORT
send(decision, participants) // 1. tell everyone
log.write(decision) // 2. then make it durable
// Participant on PREPARE:
lockRows()
reply(YES) // 1. promise
log.write({ vote: YES }) // 2. then remember the promise
// A crash between 1 and 2 (either side) leaves one node
// that acted on a decision nobody else can reconstruct.// Coordinator, after collecting votes:
decision = allYes(votes) ? COMMIT : ABORT
log.write(decision) // durable FIRST (fsync)
send(decision, participants) // then tell everyone
// on restart: decision = log.read() ?? ABORT, resend
// Participant on PREPARE:
lockRows()
log.write({ vote: YES }) // durable FIRST
reply(YES) // then promise
// on restart with a YES on disk: hold locks, ask the
// coordinator, do exactly what it says. Run COORDINATOR CRASH and watch the invariant no participant holds locks forever fail: both participants voted YES, the coordinator died before logging, and the timeline fills with locks still held. Then run FIX: DURABLE LOG + RESTART. The decision is logged before it is sent, so after the restart the coordinator resends it and the participants finish. Durability of the decision makes 2PC correct. It does not make it available: the participants still wait for the restart. The exercise asks you to place the faults yourself.
Crash the coordinator at a chosen point in the clean commit. Find the window in which a crash leaves a participant holding its locks with no decision. Then try the second fault, a crash followed by a restart from the log, at the same points.
GOAL: a participant that voted YES ends with locks held and no decision
Three-phase commit adds a pre-commit round so participants can time out safely, but only if the network never partitions, which is not a promise you can buy. Real systems keep 2PC and make the coordinator itself impossible to lose: they put its log in a replicated state machine. Gray and Lamport called this Paxos Commit. Spanner and CockroachDB both do a version of it.
2PC in Postgres: PREPARE TRANSACTION
Postgres implements the participant side. It has no coordinator: that is your application, a transaction manager such as Narayana or Atomikos, or an extension like Citus.
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 42;
PREPARE TRANSACTION 'order-7-shop'; -- phase 1: durable, detached from this session
-- later, from any session:
COMMIT PREPARED 'order-7-shop'; -- or ROLLBACK PREPARED 'order-7-shop'
After PREPARE TRANSACTION the transaction belongs to no session. Its state is in the WAL and in pg_twophase/, so it survives a crash or a restart, and because it is in the WAL it is replicated to physical standbys and is still there after a failover. Any session can finish it by name.
The facts that bite in production:
- It is off by default.
max_prepared_transactionsdefaults to0, which makesPREPARE TRANSACTIONfail. Changing it needs a restart, and a standby must have a value at least as high as its primary’s. - Global ids are global to the server, not per database. Two databases on one Postgres cannot both prepare
order-7. Give each participant its own branch id (order-7-shop,order-7-ledger); XA calls this the branch qualifier. The id must be under 200 bytes. - Some things cannot be prepared. A transaction that touched temporary tables, created a
WITH HOLDcursor, or ranLISTEN,UNLISTENorNOTIFYfails to prepare. - An orphan does three kinds of damage. It holds every lock it took, so writers to those rows queue behind it with no session to cancel. It holds back the xmin horizon, so VACUUM cannot remove any tuple that died after it began, anywhere in the cluster. And if left long enough, it drives transaction id age towards wraparound, which the MVCC chapter shows ends with Postgres refusing writes.
The documentation’s own advice is to leave max_prepared_transactions at zero unless a transaction manager is tracking every prepared transaction. If you turn it on, monitor it:
SELECT gid, database, prepared, now() - prepared AS age, age(transaction) AS xid_age
FROM pg_prepared_xacts
WHERE prepared < now() - interval '1 minute';
Alert on any row. A healthy coordinator finishes a prepared transaction in milliseconds; one that is a minute old has lost its coordinator. In pg_locks its locks show an empty pid, which is how you find the culprit when writers are blocked and pg_stat_activity shows nobody holding anything.
Ending an orphan by hand is a decision, not a cleanup. ROLLBACK PREPARED on one participant while another has already committed leaves half a transaction. Find the coordinator’s log first. Citus does this for you: the coordinator records each distributed transaction in its own metadata in the same local transaction as its commit decision, and a background job compares that record with pg_prepared_xacts on every worker, committing or rolling back what it finds. MySQL’s equivalent is XA PREPARE and XA RECOVER, with the same rules.
Percolator: the decision in a row
Google’s Percolator (2010) added cross-row, cross-machine transactions on top of Bigtable, which only offered atomic writes to a single row. It is snapshot isolation, built in the client, with no coordinator process at all. TiDB’s storage layer, TiKV, uses the same design today.
Two ingredients:
- A timestamp oracle, one service that hands out strictly increasing timestamps. Every transaction takes a
start_tswhen it begins and acommit_tswhen it commits. The paper reports one oracle machine serving about 2 million timestamps a second, by batching requests. - Three extra columns per data cell:
dataholds versions by timestamp,lockholds an uncommitted transaction’s lock, andwriteholds commit records that point at the data version they make visible.
A transaction reads at start_ts, buffers its writes, and commits in two phases:
- Prewrite. Pick one written cell as the primary. For every written cell, in a single-row Bigtable transaction, check that no other transaction has committed to it after
start_ts(a write-write conflict) and that it holds no lock; then write the data atstart_tsand a lock. Every secondary lock names the primary. - Commit. Get
commit_tsfrom the oracle. In one single-row transaction on the primary, check its lock is still there, write awriterecord atcommit_ts, and delete the lock. That single-row write is the commit point. Then do the same for the secondaries, in the background if you like.
The client can die at any moment and nothing blocks for long. A reader that finds a lock older than its own snapshot goes to that lock’s primary. If the primary has a write record, the transaction committed, and the reader rolls the secondary forward. If the primary lock is gone without a write record, it aborted, and the reader removes the secondary. If the primary lock is still there and its owner is dead (Percolator checks liveness through Chubby), the reader rolls the primary back, which aborts the whole transaction atomically because the primary was the commit point. The coordinator’s decision lives in a replicated storage row, so any client can read it.
The costs are visible in the design. Two round trips to the oracle per transaction, which also makes the oracle a single point that every transaction in the system touches. Locks are discovered lazily, so a reader can stall behind a crashed writer until it cleans up. And it is snapshot isolation, so write skew is allowed, as the isolation chapter showed. TiDB has since added async commit and a one-phase path for single-region transactions to cut the latency.
Spanner: the decision in Paxos, the order from a clock
Spanner (2012) shards data into Paxos groups: each shard is replicated to several zones, and a leader orders its writes through Paxos. A transaction that touches several groups runs 2PC, with one group’s leader as coordinator. Each participant leader logs its prepare through Paxos, and the coordinator logs its decision through Paxos. If the coordinator machine dies, another replica of its group becomes leader with the log intact and finishes the job in seconds. 2PC still blocks, but only for the time it takes Paxos to elect a new leader.
The harder problem is order. Spanner promises external consistency: if transaction T1 commits before T2 starts, in real time, T1’s commit timestamp is smaller. That is what lets a read-only transaction at timestamp t see a consistent snapshot of the whole database, in every region, without locks. It needs timestamps that agree with real time across data centres.
TrueTime provides them. TT.now() does not return a time; it returns an interval [earliest, latest] that is guaranteed to contain the true time. GPS receivers and atomic clocks in every data centre keep the interval narrow. The paper reports the uncertainty, ε, as a sawtooth between about 1 and 7 ms, 4 ms on average: each machine polls a time master every 30 seconds and assumes its local clock drifts at up to 200 microseconds per second in between.
The rule that uses it is commit wait. The coordinator leader picks commit timestamp s no smaller than TT.now().latest. Then it does not release locks or acknowledge the client until TT.now().earliest is greater than s, meaning s is certainly in the past everywhere. Any transaction that starts after the client hears “committed” must get a timestamp larger than s. The wait is about twice ε, a few milliseconds, and it overlaps the Paxos round that is happening anyway, so in practice it adds little. Spanner is buying consistency with clock accuracy: a worse clock means a longer wait on every write, not a wrong answer.
CockroachDB: parallel commits and a hybrid clock
CockroachDB shards data into ranges of about 512 MiB by default, each a Raft group of three replicas, with one replica holding the lease that serves reads and orders writes. A transaction that touches several ranges uses the same idea as Percolator, with Raft in place of Bigtable rows:
- Each write is a write intent: a provisional MVCC value that also acts as an exclusive lock, replicated through Raft like any other write.
- One transaction record, stored in the range of the transaction’s first write, holds its state:
PENDING,STAGING,COMMITTEDorABORTED. Every intent points at it. - The gateway node that runs the transaction heartbeats the record. Any other transaction that runs into an intent reads the record.
COMMITTEDmeans treat the intent as a value;ABORTEDmeans ignore it;PENDINGwith a heartbeat means wait in a queue;PENDINGwithout a recent heartbeat means the gateway is dead, so abort it and carry on.
Classic 2PC on this would cost two rounds of consensus at commit: replicate the intents, then replicate a COMMITTED record. Parallel commits removes one. At commit the gateway writes the record as STAGING, with the list of writes still in flight, at the same time as the last writes. The transaction is implicitly committed the moment the record is STAGING and every listed write has succeeded at or below the transaction’s timestamp. The gateway knows that as soon as the acknowledgements arrive and replies to the client then, after one round of consensus. It marks the record COMMITTED and resolves intents afterwards, asynchronously. If the gateway dies in between, the next transaction to find a STAGING record checks each listed write: all present means committed, any missing means it can be prevented and the transaction aborted. Cockroach Labs’ measurements showed commit latency roughly halved.
Two further optimisations matter in practice. Transaction pipelining lets each statement return before its intents finish replicating, so the waiting happens once at commit instead of per statement. And a transaction whose writes all land in one range skips the record entirely: it commits with a single Raft write, the one-phase commit fast path. The lab shows both.
The clock
CockroachDB runs on ordinary servers with NTP, not atomic clocks, so it cannot afford commit wait at Spanner’s scale. It uses a hybrid logical clock (HLC): a physical component that tracks wall time and a logical counter that breaks ties and carries causality. Every message carries the sender’s HLC, and a receiver advances its own clock past it, so a transaction that happens after another, as seen through messages, gets a later timestamp even if the wall clocks disagree.
Clocks still matter for transactions with no messages between them. Each node assumes all clocks are within --max-offset of each other, 500 ms by default. A node whose clock is more than 80% of that away from at least half of the other nodes crashes itself rather than serve wrong reads. A read at timestamp t that finds a value written between t and t + max-offset cannot tell whether that write happened before or after it in real time. This is the uncertainty interval. The read moves its own timestamp above the uncertain value and refreshes its earlier reads. If the refresh fails, the client gets a retryable error, SQLSTATE 40001, and must retry the transaction.
The result is serializable transactions and no stale reads of a single key while clocks behave, but not strict serializability: two transactions on disjoint keys can appear in an order that contradicts real time. Jepsen’s 2017 analysis, which tested exactly this with injected clock offsets, found that the guarantees hold inside the offset bound and break beyond it, along with two bugs that were fixed. The consistency chapter puts that guarantee on the map.
The four designs side by side
| where the decision lives | clock assumption | commit latency | if the coordinator dies | |
|---|---|---|---|---|
| 2PC (Postgres, MySQL XA) | the coordinator’s local log | none | 2 round trips, 3+ fsyncs | participants block until it returns |
| Percolator (TiDB) | the primary lock’s row | a single timestamp oracle | 2 oracle calls + 2 phases | readers clean up after a timeout |
| Spanner | the coordinator’s Paxos group | TrueTime, ε of a few ms | Paxos + commit wait | a new Paxos leader finishes in seconds |
| CockroachDB | a Raft-replicated record | HLC, offset under 500 ms | one consensus round (parallel commits) | others abort or recover it within seconds |
What none of them does is make the cost disappear. Every cross-shard transaction pays at least one consensus or log round on every participant, holds locks or intents for that long, and conflicts with every other transaction on the same keys. On a hot row, a distributed transaction is the slowest kind of transaction there is.
When not to use one
Distributed transactions are the right tool when the data really has to change together and lives in one system that offers them. Cross-shard transactions in Citus, CockroachDB or Spanner are that case. They are the wrong tool across service boundaries, for three reasons. First, the participants rarely all speak 2PC: a card network, an email provider or a message broker cannot prepare. Second, 2PC couples the availability of every participant: the sale fails if the ledger is down. Third, it hands one team’s locks to another team’s coordinator.
Across services, the working pattern is to commit locally and make the rest eventually true. Write the business change and an outbox row in one local transaction; a relay publishes the outbox; consumers apply it idempotently, and a failure triggers a compensating action rather than a rollback. The idempotency lesson and the payment ledger lesson cover the pieces; the change data capture and outbox chapter in module D4 builds it on the shop.
Part one runs a two-database 2PC on the shop with a coordinator you write in bash, and crashes it. Part two uses labs/databases/cockroach.yaml: three CockroachDB v25.4.18 nodes, SQL on host port 26257, DB Console on http://localhost:8090.
1. Turn on prepared transactions and create the second participant.
docker compose exec db psql -U atlas -d shop -c "ALTER SYSTEM SET max_prepared_transactions = 10"
docker compose restart db
docker compose exec db psql -U atlas -d shop -c "SHOW max_prepared_transactions"
docker compose exec db psql -U atlas -d shop -c "CREATE DATABASE ledger"
docker compose exec db psql -U atlas -d ledger -c "CREATE TABLE entries (id bigserial PRIMARY KEY, gid text NOT NULL, account text NOT NULL, amount_cents int NOT NULL, created_at timestamptz NOT NULL DEFAULT now())"ALTER SYSTEM, a restart of a few seconds, then 10. The setting only takes effect at server start, which is why the restart is needed. Two databases on one server are separate participants: a transaction in shop cannot touch ledger, so committing in both needs 2PC.2. Write the coordinator. Create the directory with mkdir -p d3-2pc in labs/databases, and in it coord.sh. It sells one unit of product 42 in shop and records the sale in ledger, and it can crash itself at two points:
#!/usr/bin/env bash
# A two-phase commit coordinator: sell one unit of product 42 (shop)
# and record the sale (ledger), atomically across two databases.
# d3-2pc/coord.sh <order-id> [after-prepare|after-decision]
set -euo pipefail
# Prepared-transaction ids are global to the Postgres server, so each participant
# gets its own branch id: order-7-shop and order-7-ledger.
cd "$(dirname "$0")/.." # labs/databases, where compose.yaml lives
order=$1; crash=${2:-none}; gid="order-$order"; log=d3-2pc/coord.log
psql() { docker compose exec -T db psql -U atlas -v ON_ERROR_STOP=1 -qAt -d "$@"; }
note() { echo "$(date +%T) $gid $1" >> "$log"; sync; } # the log is the coordinator's memory
note begin
# Phase 1: ask each participant to prepare. A failure is a NO vote.
psql shop <<SQL
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1, updated_at = now() WHERE product_id = 42;
PREPARE TRANSACTION '$gid-shop';
SQL
if ! psql ledger <<SQL
BEGIN;
INSERT INTO entries (gid, account, amount_cents) VALUES ('$gid', 'stock:42', -1999), ('$gid', 'cash', 1999);
PREPARE TRANSACTION '$gid-ledger';
SQL
then
note ABORT; psql shop -c "ROLLBACK PREPARED '$gid-shop'"; echo "$gid aborted"; exit 1
fi
echo "$gid: both participants prepared"
[ "$crash" = after-prepare ] && { echo "coordinator crashed before deciding"; exit 2; }
# The decision exists when it is durable in the log, not when it is sent.
note COMMIT
[ "$crash" = after-decision ] && { echo "coordinator crashed after deciding COMMIT"; exit 2; }
# Phase 2: tell everyone. Safe to repeat until it succeeds.
psql shop -c "COMMIT PREPARED '$gid-shop'"
psql ledger -c "COMMIT PREPARED '$gid-ledger'"
note done
echo "$gid committed"And its recovery, labs/databases/d3-2pc/recover.sh:
#!/usr/bin/env bash
# Coordinator recovery: COMMIT in the log means commit; no decision means presumed abort.
set -euo pipefail
cd "$(dirname "$0")/.."
log=d3-2pc/coord.log
psql() { docker compose exec -T db psql -U atlas -v ON_ERROR_STOP=1 -qAt -d "$@"; }
for db in shop ledger; do
for gid in $(psql "$db" -c "SELECT gid FROM pg_prepared_xacts WHERE database = current_database()"); do
if grep -q " ${gid%-*} COMMIT$" "$log" 2>/dev/null; then
psql "$db" -c "COMMIT PREPARED '$gid'"; echo "$db: committed $gid (decision found in log)"
else
psql "$db" -c "ROLLBACK PREPARED '$gid'"; echo "$db: rolled back $gid (no decision: presumed abort)"
fi
done
donechmod +x d3-2pc/*.sh
d3-2pc/coord.sh 1001
docker compose exec db psql -U atlas -d shop -c "SELECT on_hand FROM inventory WHERE product_id = 42"
docker compose exec db psql -U atlas -d ledger -c "SELECT gid, account, amount_cents FROM entries"order-1001: both participants prepared, then order-1001 committed. The stock for product 42 is one lower than before and the ledger has two rows for order-1001. d3-2pc/coord.log has begin, COMMIT, done. The sync after each log line is the coordinator’s forced write: without it a power cut could lose the decision after it was sent.3. Crash the coordinator between the phases.
d3-2pc/coord.sh 1002 after-prepare
docker compose exec db psql -U atlas -d shop -c "SELECT gid, database, prepared FROM pg_prepared_xacts"
docker compose exec db psql -U atlas -d shop -c "SELECT locktype, relation::regclass, mode, pid FROM pg_locks WHERE pid IS NULL"
docker compose exec db psql -U atlas -d shop -c "SET lock_timeout = '3s'; UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 42"coordinator crashed before deciding. Two prepared transactions, order-1002-shop in shop and order-1002-ledger in ledger. pg_locks lists their locks with an empty pid: RowExclusiveLock on inventory and its primary key, the same on two relations shown by OID (they are in ledger, so regclass cannot name them from shop), and an ExclusiveLock on each transaction id. The update waits three seconds and fails with canceling statement due to lock timeout ... while updating tuple ... in relation "inventory". Without the timeout it would wait forever. Run d3-2pc/coord.sh 1003 now and it hangs in phase 1 on the same row: press Ctrl-C and run docker compose exec db psql -U atlas -d shop -c "SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE wait_event_type = 'Lock'" to clear it.4. Show that the orphan outlives a restart and holds back vacuum.
docker compose exec db psql -U atlas -d shop -c "UPDATE inventory SET updated_at = now() WHERE product_id > 100"
docker compose exec db psql -U atlas -d shop -c "VACUUM (VERBOSE) inventory" 2>&1 | grep -E "dead but not yet removable|removable cutoff"
docker compose restart db
docker compose exec db psql -U atlas -d shop -c "SELECT gid, now() - prepared AS age, age(transaction) AS xid_age FROM pg_prepared_xacts"dead but not yet removable, with a removable cutoff a few transactions old: the oldest prepared transaction’s xid. Nothing that died after it began can be removed, in any table. After the restart both prepared transactions are still there, with growing age. They are designed to survive; only a decision ends them.5. Recover, then crash after the decision.
d3-2pc/recover.sh
d3-2pc/coord.sh 1004 after-decision
d3-2pc/recover.sh
docker compose exec db psql -U atlas -d ledger -c "SELECT gid, count(*) FROM entries GROUP BY 1 ORDER BY 1"order-1002: the log has no COMMIT for it, so presumed abort applies. order-1004 crashes after logging COMMIT, and the second recovery commits both halves. The ledger has entries for 1001 and 1004 only, and the stock for product 42 moved by exactly two. That is 2PC working: correct after every crash, and blocked for as long as the coordinator is away.6. Start CockroachDB and split a table across two ranges.
docker compose -f cockroach.yaml up -d
docker compose -f cockroach.yaml exec crdb1 ./cockroach init --insecure --host=crdb1
docker compose -f cockroach.yaml exec crdb1 ./cockroach node status --insecure --host=crdb1
docker compose -f cockroach.yaml exec crdb1 ./cockroach sql --insecureIn that SQL shell:
CREATE DATABASE shop; USE shop;
CREATE TABLE inventory (product_id INT8 PRIMARY KEY, on_hand INT4 NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now());
INSERT INTO inventory (product_id, on_hand) SELECT i, 1000 FROM generate_series(1, 5000) AS i;
ALTER TABLE inventory SPLIT AT VALUES (2501);
ALTER RANGE RELOCATE LEASE TO 1 FOR SELECT range_id FROM [SHOW RANGES FROM TABLE inventory] ORDER BY range_id LIMIT 1;
ALTER RANGE RELOCATE LEASE TO 2 FOR SELECT range_id FROM [SHOW RANGES FROM TABLE inventory] ORDER BY range_id DESC LIMIT 1;
SELECT start_key, end_key, range_id, lease_holder, replicas FROM [SHOW RANGES FROM TABLE inventory WITH DETAILS];node status lists three live nodes. After the split, SHOW RANGES has two rows: one range ending at /2501 and one starting there, each with replicas {1,2,3} (three-way Raft replication on three nodes) and with lease_holder 1 and 2 after the relocations. If a relocation reports that the lease is already there, that is fine. Product 42 now lives in a range led by node 1 and product 4242 in a range led by node 2.7. Trace a cross-range transaction, then a single-range one.
SET tracing = kv;
BEGIN;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 42;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 4242;
COMMIT;
SET tracing = off;
SELECT message FROM [SHOW KV TRACE FOR SESSION] WHERE message LIKE '%sending batch%';
SET tracing = kv;
UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 43;
SET tracing = off;
SELECT message FROM [SHOW KV TRACE FOR SESSION] WHERE message LIKE '%sending batch%';r followed by a number) on n1 and n2: a read and a write to each range, then a final batch containing EndTxn sent to the range of the first write, product 42’s, because that is where the transaction record lives. That final batch is the parallel commit: the record goes in as STAGING alongside the check that the in-flight writes landed. The second trace, an implicit transaction on one row in one range, sends the write and EndTxn in the same batch: the one-phase commit fast path, with no transaction record at all. The exact wording of trace messages changes between versions; if the filter returns nothing, drop the WHERE and read the whole trace.8. Leave intents behind and kill their gateway. In terminal 2, connect through node 3 and leave a transaction open:
docker compose -f cockroach.yaml exec crdb3 ./cockroach sql --insecure --host=crdb3 -d shopBEGIN;
UPDATE inventory SET on_hand = 0 WHERE product_id = 42;
UPDATE inventory SET on_hand = 0 WHERE product_id = 4242;Back in terminal 1 (the crdb1 shell):
SET statement_timeout = '3s';
SELECT on_hand FROM inventory WHERE product_id = 4242;
SELECT range_id, lock_key_pretty, lock_strength, granted FROM crdb_internal.cluster_locks WHERE table_name = 'inventory';Then, from a third shell in labs/databases, kill the node that is running the open transaction, and re-run the read in terminal 1 without a timeout:
docker compose -f cockroach.yaml kill crdb3RESET statement_timeout;
SELECT on_hand FROM inventory WHERE product_id = 4242;query execution canceled due to statement timeout, because it found an intent from a live transaction and queued behind it. cluster_locks then shows exclusive locks in both ranges, held by one transaction id; if it lists only product 4242’s, that is because the in-memory lock table learns about a replicated intent when someone runs into it. After kill crdb3 the gateway stops heartbeating, and the second read returns 999 (1000 less the update from step 7) within a few seconds: it found the intent, saw that its transaction had stopped heartbeating, aborted it, and read past it. Node 3 also held a replica of both ranges, but two of three is still a Raft majority, so nothing else stalls. Compare step 3, where Postgres would have waited for ever. Start the node again with docker compose -f cockroach.yaml start crdb3.coord.sh, move the note COMMIT line below the two COMMIT PREPARED lines, and put [ "$crash" = mid-commit ] && { echo "crashed between commits"; exit 2; } between those two lines. Run d3-2pc/coord.sh 1005 mid-commit, then d3-2pc/recover.sh. The shop has committed its half; the log has no decision, so recovery presumes abort and rolls back the ledger half. Product 42’s stock has dropped with no ledger entry for 1005: the atomicity 2PC exists to provide is gone, and nothing reported an error. The decision must be durable before anyone acts on it. Tear down with docker compose -f cockroach.yaml down -v. Then run d3-2pc/recover.sh once more and check that SELECT count(*) FROM pg_prepared_xacts returns 0: an orphaned prepared transaction survives restarts and holds back vacuum in every later chapter. Finally docker compose exec db psql -U atlas -d shop -c "DROP DATABASE ledger" -c "ALTER SYSTEM RESET max_prepared_transactions" and docker compose restart db, so the shop is back on its default of 0 and later chapters start from the same server you had before this one.The shop has split payments into its own service with its own Postgres, owned by another team. Product asks that an order is never marked paid unless the payment is captured, and never captured without the order being marked paid. Capturing calls the card provider's API. An architect proposes XA two-phase commit across the orders and payments databases through a transaction manager. What do you do?
- PAPER Spanner: Google's Globally-Distributed Database Corbett et al., 2012
The source of TrueTime, the ε measurements, commit wait and external consistency. Section 4 is short and every sentence carries weight; the evaluation of F1 at the end can be skipped. Read: sections 3 (TrueTime) and 4.1 to 4.2 (timestamps, commit wait, 2PC over Paxos); skim section 2.
- PAPER Large-scale Incremental Processing Using Distributed Transactions and Notifications Daniel Peng, Frank Dabek, 2010
Percolator. The commit protocol fits on one page of pseudocode, including how a reader rolls a crashed writer forward or back from its primary lock. Read: section 2.2 (transactions) and its pseudocode figure; skip the notification sections.
- DOC CockroachDB: Transaction Layer
Write intents, transaction records and their four states, the HLC, max offset enforcement, uncertainty restarts, pipelining and parallel commits step by step. The reference for steps 6 to 8 of the lab.
- POST Parallel Commits: An atomic commit protocol for globally distributed transactions Nathan VanBenschoten, 2019
Why STAGING plus in-flight writes is enough to call a transaction committed, how recovery decides when the coordinator is gone, and the latency measurements. Read after the docs page.
- POST Living Without Atomic Clocks Cockroach Labs
CockroachDB's own account of what it gives up by using HLC and NTP instead of TrueTime: where it waits, where it restarts, and why it is serializable but not strictly serializable.
- PAPER Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases Kulkarni, Demirbas et al., 2014
The hybrid logical clock: how it stays close to physical time while capturing causality, and the bound on its drift. Skip the snapshot-reading application in the later sections. Read: sections 1 to 3; the HLC algorithm is one figure.
- DOC PostgreSQL 17: PREPARE TRANSACTION and Two-Phase Transactions
The short chapter on Postgres's participant side, linking to PREPARE TRANSACTION, COMMIT PREPARED and pg_prepared_xacts. The caution box about leaving prepared transactions open is the part to take to your team.
- POST Jepsen: CockroachDB beta-20160829 Kyle Kingsbury, 2017
A careful test of what HLC-based transactions guarantee, with injected clock offsets, and the two bugs it found. Read the introduction and the comments test for the strict serializability gap.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.