Distributed SQL, Consensus & 2PC
"The classic Two-Phase Commit protocol blocks if the coordinator fails. Fault-tolerant consensus algorithms also reach agreement, but do not block whenever any majority of the processes are working." — Jim Gray & Leslie Lamport, "Consensus on Transaction Commit", Microsoft Research MSR-TR-2003-96, revised 19 April 2004
Summary: Atomic commit (2PC) makes several machines agree on one transaction; consensus (Paxos, Raft, Zab) makes several copies agree on every write; distributed SQL (Spanner, CockroachDB, TiDB, YugabyteDB) runs the first on top of the second. Focus: 2PC and why it blocks, XA and PostgreSQL PREPARE TRANSACTION, quorum, Paxos and Raft in operational detail, linearizable reads, split brain and fencing, clocks (TrueTime, HLC), and how each product turns all this into latency, retries and placement decisions. Learning goal: Predict what a cross-node write costs and what happens when any node dies, recover a stuck prepared transaction, write the 40001 retry loop, and decide honestly between one PostgreSQL primary with replicas, a distributed SQL cluster, or a saga with an outbox.
This page is the complete reference for agreement between machines in a database: the atomic commit protocols (two-phase commit, presumed abort, three-phase commit, X/Open XA, PostgreSQL PREPARE TRANSACTION and MySQL XA), the consensus protocols (the consensus problem, FLP, quorums, Paxos, Multi-Paxos, Raft with terms, elections, log replication, commit index, membership changes, snapshots, pre-vote and leader leases, Zab in ZooKeeper, etcd), linearizable reads (read index, lease reads, follower reads), split brain and fencing tokens, clocks (Spanner TrueTime and commit wait, hybrid logical clocks), and the distributed SQL designs built from them (Spanner, CockroachDB, TiDB with Percolator, YugabyteDB with DocDB, Calvin). It does not re-teach its neighbours: streaming replication, read replicas and failover tooling such as Patroni are in Replication, Read Replicas & Failover; isolation levels and the anomalies behind 40001 are in Isolation Levels; hand-built sharding is in Partitioning & Sharding in PostgreSQL; weaker consistency models (bounded staleness, causal, quorum reads in Dynamo-style stores) are in Eventual Consistency in Database Systems; and the application-level alternatives are in Transactional Outbox and Saga Pattern.
Page map
| If you are looking for | Go to |
|---|---|
| Three tables you can memorise in one minute | Everything in one minute |
| Why agreement between machines is hard, and the trade-off | Why this exists |
| Gray & Lamport, Paxos, Raft, Spanner: where the vocabulary comes from | Where it comes from |
2PC phases, coordinator failure, presumed abort, 3PC, XA, PREPARE TRANSACTION | Atomic commit, one by one |
| Consensus, FLP, quorum, Paxos, Multi-Paxos | Consensus, one by one |
| Raft terms, election, log replication, commit index, membership, snapshots, pre-vote, leases | Raft in operational detail |
| Read index, lease reads, follower reads, split brain, fencing, Zab, etcd | Reads, leases and split brain |
| TrueTime, commit wait, HLC, Percolator, ranges, DocDB, Calvin | Distributed SQL designs |
| Spanner, CockroachDB, TiDB, YugabyteDB, etcd, ZooKeeper, PostgreSQL, MySQL, MongoDB, SQLite, Redis | What each product really does |
| Write latency = RTT math, knobs, error codes | Mechanics |
| SQL + Go + Laravel for cross-database payments, orphaned prepares, retries, stale reads, fencing | Solving the classic problems |
40001 retry loop in Go and Laravel | Retries and failure handling |
| Single PostgreSQL + replicas vs distributed SQL vs saga | Choosing |
| Monolith to multi-region | In architecture |
| Kill the leader of a 3-node CockroachDB cluster; recover an orphaned PostgreSQL prepare | Lab |
| Wrong beliefs, a cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The two problems and their protocols.
| Problem | In plain words | Protocol | What it costs | What breaks it |
|---|---|---|---|---|
| Atomic commit | One transaction touched several machines: all commit or none | Two-phase commit (2PC), XA, PREPARE TRANSACTION | Two message rounds and three forced log writes per transaction | Coordinator dies after the votes: participants block holding locks |
| Consensus (replication) | Several copies agree on one ordered log of writes | Paxos, Multi-Paxos, Raft, Zab | One round trip from the leader to a majority per write | Losing a majority: writes stop (safety kept, availability lost) |
| Both together | Atomic commit whose participants are themselves replicated | 2PC over Paxos (Spanner), Parallel Commits over Raft (CockroachDB), Percolator over Raft (TiDB) | Quorum RTT per range touched, plus clock waits | Clock offset beyond the configured bound; hot keys; cross-region quorums |
The key terms.
| Term | In plain words | Tiny example | Where you meet it |
|---|---|---|---|
| Quorum (majority) | More than half of the voters | 2 of 3, 3 of 5 | Raft, Paxos, Zab, etcd, CockroachDB ranges |
| Term / ballot / epoch | A numbered "reign"; higher number wins | Raft term 7 deposes term 6 | Raft term, Paxos ballot, Zab epoch, ZooKeeper zxid |
| Commit index | Highest log position stored on a majority | Leader has 6 entries, majority has 5: commit index 5 | Raft |
| Leader lease | Time-bounded promise that no other leader exists | Spanner leader lease 10 s | Spanner, CockroachDB Leader leases, etcd ReadOnlyLeaseBased |
| Read index | Confirm leadership with a heartbeat round, then read | Linearizable read without writing the log | etcd ReadOnlySafe, TiKV, Raft paper §8 |
| Follower read | Read a nearby replica at a slightly old timestamp | AS OF SYSTEM TIME follower_read_timestamp() | CockroachDB, Spanner stale reads, TiDB stale read |
| Commit wait | Wait out clock uncertainty before showing a commit | Spanner waits ~2ε (single-digit ms) | Spanner TrueTime |
| Fencing token | A number that rises with every new leader; storage rejects old numbers | ZooKeeper zxid as a token | Distributed locks, leader election in your own services |
40001 | "Restart transaction": retry the whole transaction | CockroachDB RETRY_WRITE_TOO_OLD | CockroachDB, YugabyteDB, PostgreSQL Serializable |
The three things to do.
| Situation | Do this |
|---|---|
| Two services, two databases, one business action | Do not reach for 2PC: commit locally with an outbox row and compensate with a saga |
You do run PREPARE TRANSACTION / XA | Keep a durable decision log, run a recovery job over pg_prepared_xacts / XA RECOVER, alert on any prepare older than a minute |
| You run distributed SQL | Retry 40001 around the whole transaction, keep leaseholders near writers, use follower reads for anything that tolerates seconds of staleness |
Why this exists
One machine is easy: a transaction is atomic because one write-ahead log decides it, and one CPU orders all writes. Once data lives on several machines, two questions appear that one machine never had to ask. Did everyone involved commit, or nobody? (atomic commit). Do all copies agree on what was written, in which order, even while some are dead or unreachable? (consensus). Both have to be answered in a network where a slow machine and a dead machine look identical.
| Single PostgreSQL primary + replicas | Distributed SQL (consensus-replicated ranges) |
|---|---|
| Commit = one local WAL flush (sub-millisecond on good disks) | Commit = a quorum round trip per range (1 ms in one zone, tens of ms across regions) |
| All writes on one machine: vertical scaling only | Writes spread over many leaders: horizontal scaling |
| Failover by external tooling; async replicas can lose the last commits | Failover is automatic and loses no committed write while a majority survives |
| Split brain possible if fencing is wrong | Split brain prevented by quorum (one leader per term) |
| Full PostgreSQL feature set, Read Committed default | PostgreSQL wire protocol, a subset of features, Serializable default (CockroachDB), retries are normal |
Cross-database atomicity only via PREPARE TRANSACTION | Cross-range atomicity built in (Parallel Commits, Percolator, 2PC over Paxos) |
The analogy we reuse on this page: a wedding and a registry office. At a wedding the officiant asks each partner "do you?", and each says "I do". That is the prepare phase: after it neither partner can back out alone. Then the officiant pronounces them married: the commit. If the officiant collapses after both vows but before the pronouncement, the couple and the guests are stuck; nobody present has the authority to declare the outcome. That is 2PC blocking. Now put five registrars in the room and agree that any three of them can record the pronouncement in the register. One fainting registrar changes nothing. That is two-phase commit run over consensus. The register itself, where every page is numbered and only the chief registrar of the current shift writes, is the Raft log; a registrar who wakes up thinking she is still chief, and stamps a page with last shift's number, is rejected because the shift number has moved on: that is a term, and a fencing token.
Three common misunderstandings, up front
- "Two-phase commit makes a system fault tolerant." It makes the commit atomic. It makes the system less available: any one participant or the coordinator failing at the wrong moment blocks everyone else, with locks held.
- "Consensus means every replica has the latest data." It means a majority has it. A minority of followers can lag, which is why reads need a read index, a lease, or an explicit staleness bound.
- "PostgreSQL-compatible distributed SQL is a faster PostgreSQL." Each write pays a quorum round trip, the default isolation is often Serializable,
40001retries are routine, and only a subset of PostgreSQL features exists. It scales out and survives failures; it is not faster per transaction.
Where it comes from
Atomic commit. Gray and Lamport call two-phase commit "the classical transaction commit protocol". A transaction manager (TM, the coordinator) asks every resource manager (RM, the participant) to prepare; each RM makes its changes durable and votes; if all vote Prepared, the TM records a commit decision and tells everyone. Their paper states the flaw precisely:
"In particular, if the TM fails after every RM has sent a Prepared message, then the other RMs have no way of knowing whether the TM committed or aborted the transaction."
They count the cost too: in the normal case 2PC "incurs the delays associated with three writes to stable storage" (the first RM's prepare, the other RMs' prepares, the TM's decision). Their fix, Paxos Commit, replaces the single TM with 2F + 1 acceptors that agree on the decision; "The classic Two-Phase Commit algorithm is obtained as the special F = 0 case of the Paxos Commit algorithm." The industry standard for 2PC between products is X/Open XA, which PostgreSQL's manual names when it says PREPARE TRANSACTION is "intended for use by external transaction management systems, some of which are covered by standards (such as X/Open XA)". Presumed abort and presumed commit are the R* optimisations by Mohan, Lindsay and Obermarck that reduce log writes and messages; three-phase commit is Skeen's non-blocking protocol. Neither paper is quoted on this page; their content is summarised from the standard literature.
Consensus. Lamport's Paxos Made Simple (2001) retells his Part-Time Parliament algorithm: proposers, acceptors, learners, and a value is chosen once a majority of acceptors accepts it, because "any two majorities have at least one acceptor in common". Fischer, Lynch and Paterson (1985, Journal of the ACM) proved that no deterministic asynchronous algorithm can guarantee termination with even one crash; every practical protocol therefore keeps safety unconditionally and uses timeouts for progress. Ongaro and Ousterhout designed Raft (extended version, 2014) because Paxos was hard to learn and to build; Raft produces "a result equivalent to (multi-)Paxos" but separates leader election, log replication and safety. ZooKeeper's Zab (atomic broadcast) and etcd's Raft library brought consensus into everyday infrastructure.
Distributed SQL. Google's Spanner (OSDI 2012) sharded data into many Paxos groups across datacenters, ran two-phase commit between groups ("Running two-phase commit over Paxos mitigates the availability problems"), and used TrueTime to make transactions externally consistent. Google's Percolator (OSDI 2010) added snapshot-isolation transactions on Bigtable with a timestamp oracle and a primary lock per transaction; TiDB adopted that model. Calvin (SIGMOD 2012) went the other way: agree on the order of transactions first, then execute deterministically, so no distributed commit protocol is needed. CockroachDB and YugabyteDB are open-source descendants of the Spanner design that replace TrueTime with hybrid logical clocks.
Atomic commit, one by one
Two-phase commit (2PC) Must-know
In plain words: before anyone commits, the coordinator asks every participant "can you definitely commit this?". Each one makes its work crash-proof and answers yes or no. Only if every answer is yes does the coordinator decide "commit" and tell everyone.
Common misunderstanding: "2PC means two commits in a row." Two commits in a row is the bug 2PC fixes (see the before snippet). The two phases are vote and decide, and nobody commits until every vote is in.
Definition: a protocol with a coordinator (transaction manager, TM) and participants (resource managers, RMs). Phase 1 (prepare/voting): the TM sends PREPARE; each RM writes all its changes and a prepare record to durable storage, keeps its locks, and votes YES (prepared) or NO. A YES is a promise: the RM can no longer abort on its own. Phase 2 (commit/decision): if all votes are YES, the TM forces a COMMIT decision to its log (the commit point) and sends COMMIT to every RM; any NO or timeout leads to ABORT. RMs apply the decision, release locks and acknowledge; the TM can then forget the transaction.
Coordinator (TM) Wallets DB (RM A) Billing DB (RM B)
1 BEGIN on A and B
2 UPDATE wallets ... (row lock) UPDATE invoices ... (row lock)
3 PREPARE -> PREPARE TRANSACTION 'pay-17' -- fsync, vote YES
4 PREPARE TRANSACTION 'pay-17' -- fsync, vote YES
5 INSERT decision('pay-17','commit'); fsync -- commit point
6 COMMIT -> COMMIT PREPARED 'pay-17' -- locks released
7 COMMIT PREPARED 'pay-17'
8 forget 'pay-17'Real scenarios: moving money between a wallet database and a billing database owned by the same team; a Java EE / Spring application server writing to an Oracle or PostgreSQL database and a JMS broker in one XA transaction; Spanner and CockroachDB committing a transaction that touched several ranges (internally); a migration that must update a legacy MySQL and a new PostgreSQL atomically during a cut-over window.
| Where | 2PC primitive | Notes |
|---|---|---|
| PostgreSQL | PREPARE TRANSACTION 'gid', COMMIT PREPARED, ROLLBACK PREPARED, pg_prepared_xacts | Disabled by default: max_prepared_transactions = 0 |
| MySQL / InnoDB | XA START, XA END, XA PREPARE, XA COMMIT [ONE PHASE], XA ROLLBACK, XA RECOVER | XA RECOVER needs the XA_RECOVER_ADMIN privilege |
| SQLite | No 2PC between processes; one transaction over several ATTACHed files is atomic via a super-journal | Single host only |
| Spanner | 2PC between Paxos groups, coordinator leader chosen among participant groups | Coordinator state is replicated, so it does not block on one machine |
| CockroachDB | Parallel Commits with a STAGING transaction record | Internal; the client sees one COMMIT |
| TiDB | Percolator-style prewrite + commit of a primary key | Internal; PD supplies start_ts / commit_ts |
| MongoDB | Multi-document transactions on sharded clusters ("distributed transactions") | Internal to mongos; the driver sees one commit |
Fix / how to use it: in application code, almost never directly (see Choosing). If you must, follow the PostgreSQL 2PC solution: a durable decision log, PREPARE TRANSACTION per participant on a pinned session, COMMIT PREPARED from any session, and a recovery job.
Coordinator failure and blocking Must-know
In plain words: once a participant has said "yes, I can commit", it must wait for the coordinator's answer. If the coordinator dies right then, the participant waits, possibly for hours, holding its locks.
Common misunderstanding: "A timeout fixes it: if I hear nothing, I abort." A prepared participant cannot abort on a timeout, because the coordinator may already have decided COMMIT and told the other participant, which committed. Aborting would break atomicity. Only unprepared participants may abort on a timeout.
Definition: 2PC is a blocking protocol: there is a window (after the RM votes YES, before it learns the outcome) in which the failure of the coordinator leaves the RM unable to decide. Gray and Lamport define the property 2PC lacks: "A non-blocking commit protocol is one in which the failure of a single process does not prevent the other processes from deciding if the transaction is committed or aborted."
TM RM A RM B
1 PREPARE -> prepared, vote YES prepared, vote YES
2 writes COMMIT to its log
3 sends COMMIT to A -> COMMIT PREPARED (done)
4 ** crashes before sending to B **
5 waits... holds row locks on invoices
6 cannot abort: A has committed
7 cannot commit: does not know A voted YES
8 TM restarts, reads log -> COMMIT PREPARED -- unblocked after hoursReal scenarios: an application server acting as XA coordinator is OOM-killed during phase 2 and its transaction log is on the container's ephemeral disk: the prepared transactions are orphaned forever; checkout requests time out because UPDATE invoices waits on a row lock held by a prepared transaction; PostgreSQL autovacuum cannot advance the xmin horizon past an orphaned prepare, so tables bloat and, in the extreme, the server shuts down to prevent transaction ID wraparound; a MySQL replica stops applying because an XA PREPAREd transaction holds locks the next event needs.
| Who decides after a crash | Classic 2PC | Paxos Commit / Spanner / CockroachDB |
|---|---|---|
| Coordinator crashes before decision | Participants block until it returns (or an operator decides) | Another replica of the coordinator group takes over with the replicated state |
| Coordinator crashes after decision | Decision is in its log; participants block until it restarts | Decision is replicated by consensus; any replica can finish |
| A participant crashes after voting | Its prepare record survives; on restart it asks the coordinator | Participant is a consensus group; a new leader continues |
Fix: make the coordinator's state durable and replicated (Spanner, CockroachDB), or at least durable plus a recovery job that any operator can run (orphan recovery). Monitor pg_prepared_xacts and XA RECOVER for anything older than your longest transaction.
Presumed abort and presumed commit Good to know
In plain words: a coordinator that has no record of a transaction answers "it aborted". That lets it skip writing abort records and forget aborted transactions immediately.
Common misunderstanding: "Presumed abort makes 2PC non-blocking." It only saves log writes and acknowledgements. A prepared participant still waits for the coordinator to come back and answer.
Definition: in basic 2PC the coordinator must remember every transaction until all participants acknowledge the outcome. Presumed abort (R*, Mohan, Lindsay & Obermarck) adopts the rule no information means abort: the coordinator does not force-write abort decisions, participants do not acknowledge aborts, and read-only participants vote READ-ONLY and drop out of phase 2. Presumed commit inverts the rule for systems where commits dominate: the coordinator force-writes a "collecting" record before phase 1, commits need no acknowledgements, and missing information means commit. Most XA implementations, and the decision-log design on this page, are presumed-abort: the Go coordinator writes only a commit decision on the happy path, and its recovery job writes "abort" for any old prepare without one.
TM (presumed abort) RM
1 PREPARE -> prepared, vote YES
2 TM crashes before writing anything
3 TM restarts: no record of 'pay-17'
4 asks: outcome of 'pay-17'?
5 "unknown means abort" -> ROLLBACK PREPARED 'pay-17'Real scenarios: XA transaction managers in Java application servers; the twopc_decisions table in this page's Go and Laravel code; any recovery script that rolls back prepares with no matching commit record.
Three-phase commit (3PC) Good to know
In plain words: 3PC adds a "get ready to commit" round between voting and committing, so that participants can finish the protocol among themselves if the coordinator dies.
Common misunderstanding: "3PC solves 2PC's blocking, so production systems use it." It avoids blocking only under assumptions that real networks break: bounded message delay and no network partitions. With a partition, two halves can time out into different decisions. Production systems replicated the coordinator with consensus instead (Paxos Commit, Spanner, CockroachDB).
Definition (Skeen, summarised): phase 1 CanCommit/vote; phase 2 PreCommit (the coordinator tells everyone that all voted YES; participants acknowledge); phase 3 DoCommit. The invariant: no participant commits while any other could still be uncertain whether all voted YES, so survivors can elect a new coordinator and finish by timeout. Gray and Lamport's criticism is that the classic treatment of non-blocking commit "fails to explain what a process should do if it receives messages from two different processes, both claiming to be the current TM" — which is exactly the problem consensus solves with ballots and terms.
Partition splits {TM, A} from {B, C}; A, B and C have all voted YES
1 TM sends PreCommit to A only, then the partition happens
2 {B, C} time out uncertain -> elect C as new TM -> nobody saw PreCommit -> ABORT
3 {TM, A} -> A is PreCommitted -> COMMIT
-- atomicity violated: 3PC is not safe under partitionsWhat prevents the problem in practice: consensus on the decision. Paxos Commit uses 2F + 1 acceptors; any majority decides, and ballots resolve the case of two processes both claiming to be the current TM.
X/Open XA and PostgreSQL PREPARE TRANSACTION Important
In plain words: XA is the standard interface that lets one transaction manager drive 2PC across products. PostgreSQL implements the participant side as PREPARE TRANSACTION; MySQL implements it as XA statements.
Common misunderstanding: "PREPARE TRANSACTION is a PostgreSQL feature for my application." The manual says the opposite: "Unless you're writing a transaction manager, you probably shouldn't be using PREPARE TRANSACTION." It is a building block for a coordinator, and a forgotten prepare is a production incident.
Definition (PostgreSQL): inside a BEGIN block, PREPARE TRANSACTION 'gid' makes the transaction durable and detaches it from the session: "its state is fully stored on disk, and there is a very high probability that it can be committed successfully, even if a database crash occurs before the commit is requested." The gid must be a string literal of fewer than 200 bytes. From the session's point of view it is like ROLLBACK (there is no current transaction any more); if PREPARE fails, it becomes a ROLLBACK. Any session of the same user (or a superuser) can later run COMMIT PREPARED 'gid' or ROLLBACK PREPARED 'gid', which "cannot be executed inside a transaction block". Transactions that touched temporary tables, created WITH HOLD cursors, or ran LISTEN/UNLISTEN/NOTIFY cannot be prepared. pg_prepared_xacts lists every prepared transaction with transaction (xid), gid, prepared (timestamptz), owner and database. The feature is off until max_prepared_transactions (default 0, restart required) is set; the manual suggests "at least as large as max_connections" if you use it.
Definition (MySQL/InnoDB): XA {START|BEGIN} xid, the work, XA END xid, XA PREPARE xid, then XA COMMIT xid or XA ROLLBACK xid; XA COMMIT xid ONE PHASE skips the prepare when there is one participant. XA RECOVER "returns information for those XA transactions on the MySQL server that are in the PREPARED state", and "A given TM must be able to recognize its own xid values" in that list.
Session 1 (coordinator's worker) Session 2 (recovery job, an hour later)
1 BEGIN;
2 UPDATE wallets SET balance_cents = balance_cents - 1500 WHERE customer_id = 42;
3 PREPARE TRANSACTION 'twopc-pay-17';
4 -- worker is killed here
5 SELECT gid, prepared FROM pg_prepared_xacts;
6 -- twopc-pay-17 | 2026-11-25 10:00:03+00
7 SELECT outcome FROM twopc_decisions WHERE gid = 'twopc-pay-17';
8 -- 'commit'
9 COMMIT PREPARED 'twopc-pay-17'; -- locks releasedReal scenarios: an XA-capable JDBC pool (Atomikos, Narayana) coordinating PostgreSQL and a message broker; pg_dump and VACUUM showing an unexpectedly old xmin horizon traced to a prepare from last week; a blue/green migration that dual-writes MySQL and PostgreSQL via XA; logical replication of prepared transactions (PostgreSQL can decode PREPARE for subscribers that enable two_phase).
| Product | Participant API | Recovery list | Default |
|---|---|---|---|
| PostgreSQL | PREPARE TRANSACTION, COMMIT PREPARED, ROLLBACK PREPARED | pg_prepared_xacts | Off (max_prepared_transactions = 0) |
| MySQL / InnoDB | XA START/END/PREPARE/COMMIT/ROLLBACK | XA RECOVER [CONVERT XID] | Available |
| CockroachDB, TiDB, YugabyteDB | Not offered as a participant API; distributed commit is internal | Internal transaction records | n/a |
Fix: code in orphaned prepared transactions (SQL query, Go Recover, Laravel twopc:recover command).
Consensus, one by one
The consensus problem and FLP Must-know
In plain words: several machines must pick one value (or one next log entry), never two, even though messages are late and machines crash. A replicated database repeats this for every write.
Common misunderstanding: "FLP says consensus is impossible, so these systems are lying." FLP says no deterministic, fully asynchronous algorithm can guarantee termination with one crash. Real protocols are always safe (never two values) and are live (eventually decide) only when the network behaves for long enough, which they detect with timeouts and randomness.
Definition: consensus requires agreement (no two processes decide differently), validity (the decided value was proposed) and termination (every correct process eventually decides). Gray and Lamport summarise FLP: "a deterministic, purely asynchronous algorithm cannot satisfy the stability and consistency conditions and still guarantee progress in the presence of even a single fault." Lamport's practical answer is that leader election "must use either randomness or real time—for example, by using timeouts". A replicated state machine runs consensus once per log slot: every replica applies the same commands in the same order, so all reach the same state.
A (proposes x=1) B (proposes x=2) C
1 send to B, C send to A, C
2 receives A's message first: leans x=1
3 A pauses (GC, 2 s) B times out on A is A dead or slow? cannot tell
4 B tries again with a higher number (a new ballot/term)
5 A wakes, tries again with a higher number ... -- this can repeat forever (FLP),
-- randomised timeouts make it end in practiceReal scenarios: a Raft cluster that keeps re-electing during a network flap (liveness lost, no data lost); a 5-node etcd losing 3 nodes and refusing writes (safety over availability); an operator "fixing" a stuck cluster by forcing a single node to be leader and losing acknowledged writes (safety thrown away by hand).
| System | Safety rests on | Liveness rests on |
|---|---|---|
| Paxos | Ballot numbers + majority intersection | A distinguished proposer, timeouts |
| Raft | Terms + majority votes + log up-to-date check | Randomised election timeout |
| Zab (ZooKeeper) | Epochs + quorums of size n/2+1 | Leader election with timeouts |
| Spanner, CockroachDB | Paxos/Raft per group, plus bounded clock offset for leases and reads | Leases, timeouts |
Quorum Must-know
In plain words: a decision counts once more than half of the voters agree. Any two "more than halves" share at least one member, so two conflicting decisions cannot both get a quorum.
Common misunderstanding: "Four nodes are safer than three." For a majority quorum, 4 nodes tolerate one failure, exactly like 3, but need 3 votes instead of 2. etcd's FAQ: "For a cluster with n members, quorum is (n/2)+1", and adding a node to an odd-sized cluster leaves fault tolerance unchanged while there "are more nodes that can fail". Use odd sizes.
Definition: a quorum system is a set of subsets of voters in which any two subsets intersect. Majority quorums (size ⌊n/2⌋ + 1) are the standard; ZooKeeper's internals guide puts it as "any pair of quorum must have at least one server in common", ensured by "requiring that all quorums have size ( n/2+1 )". With n voters, the cluster tolerates f = ⌊(n − 1)/2⌋ failures. Non-voting copies (CockroachDB non-voting replicas, etcd learners, Raft learners) receive the log without counting toward the quorum: they add read capacity and locality without adding write latency.
| Voters (n) | Quorum | Failures tolerated | Typical use |
|---|---|---|---|
| 1 | 1 | 0 | Development only |
| 3 | 2 | 1 | Default range replication (CockroachDB, TiKV, YugabyteDB), small etcd |
| 4 | 3 | 1 | Never: same tolerance as 3, slower |
| 5 | 3 | 2 | Survive a zone and a node, or a region with 5 regions/zones; etcd recommended size |
| 7 | 4 | 3 | Rare; more replication traffic per write |
5 voters across 3 regions: A A | B B | C
1 region C is cut off -> {A,A,B,B} still has 3 of 5: writes continue
2 region A is cut off instead -> {B,B,C} has 3 of 5: writes continue (leader moves to B)
3 regions A and B both cut off -> {C} has 1 of 5: no writes; reads only if stale reads allowedReal scenarios: a CockroachDB database with SURVIVE REGION FAILURE needing voters in at least three regions; a Kubernetes control plane on 3 etcd members that survives a node drain but not two; a ZooKeeper ensemble of 5 for Kafka (legacy) or HBase.
Paxos: proposers, acceptors, learners, ballots Important
In plain words: a proposer first reserves a numbered slot of attention with a majority ("promise not to listen to anyone with a lower number"), learns whether a value may already have been chosen, and then asks that majority to accept a value, reusing the old one if there was one.
Common misunderstanding: "Paxos needs a leader to be safe." Paxos is safe with any number of competing proposers; the numbers (ballots) guarantee that at most one value is chosen. A leader (distinguished proposer) is only needed for progress, because two proposers can keep pre-empting each other.
Definition (from Paxos Made Simple): roles are proposers, acceptors and learners; a proposal is a pair (number n, value v), where the number is the ballot. Phase 1a (prepare): a proposer picks n and asks a majority for "(a) A promise never again to accept a proposal numbered less than n, and (b) The proposal with the highest number less than n that it has accepted, if any." Phase 1b (promise): an acceptor answers if n is the highest it has seen. Phase 2a (accept): with promises from a majority, the proposer sends accept(n, v), where v is the value of the highest-numbered proposal reported, or its own value if none. Phase 2b (accepted): an acceptor accepts unless it has promised a higher number; acceptors must remember promises and acceptances across restarts. A value is chosen when a majority has accepted it; learners find out from the acceptors.
Proposer P (ballot 1) Acceptors A1 A2 A3 Proposer Q (ballot 2)
1 prepare(1) -> A1, A2 promise(1), none accepted
2 accept(1, x=5) -> A1 accepts
3 prepare(2) -> A2, A3 promise(2)
4 A2 rejects accept(1): promised 2
5 A2 reports nothing accepted; Q may pick its own value x=9
6 accept(2, x=9) -> A2, A3 accept: CHOSEN x=9
7 P retries prepare(3) -> A1 reports (1,5), A2 reports (2,9): P must propose 9, never 5Lamport's own example of the liveness problem: proposer p completes phase 1 for n1, q for n2 > n1, p's accepts are ignored, p completes phase 1 for n3 > n2, "causing the second phase 2 accept requests of proposer q to be ignored", and so on. Hence a distinguished proposer.
Real scenarios: Spanner's per-shard replication; Google Chubby; Paxos Commit for the transaction decision; Cassandra's lightweight transactions (IF NOT EXISTS) run a Paxos round per conditional write.
Multi-Paxos Important
In plain words: run Paxos for every slot of a log, but let one stable leader do phase 1 once for all future slots. After that, each write needs only phase 2: one round trip to a majority.
Common misunderstanding: "Paxos needs two round trips per write." Single-decree Paxos does; Multi-Paxos with a stable leader does one, the same as Raft.
Definition: a leader runs phase 1 with a ballot that covers every slot from i onwards; while its ballot is not pre-empted, it sends only accept messages for slots i, i+1, …. Lamport describes the state-machine version in Paxos Made Simple §3. Spanner adds leader leases: "Our Paxos implementation supports long-lived leaders with time-based leader leases, whose length defaults to 10 seconds." Raft is, in effect, Multi-Paxos with stricter rules about which log a leader may have.
| Single-decree Paxos | Multi-Paxos | Raft | |
|---|---|---|---|
| Round trips per write (stable leader) | 2 | 1 | 1 |
| Leader | Optional, for liveness | Distinguished proposer | Mandatory, one per term |
| Log holes | n/a | Allowed (slots decided out of order) | Not allowed (log matching property) |
| Leader catch-up | n/a | Phase 1 learns accepted values per slot | Only up-to-date candidates can win |
Leader L (ballot 7, phase 1 done for slots >= 40) Acceptors (majority)
1 accept(7, slot 40, "x=1") -> accepted
2 accept(7, slot 41, "y=2") -> accepted -- one RTT per write
3 new leader M runs prepare(8) for slots >= 40 -> L's next accept(7, ...) is rejectedRaft in operational detail
Terms and leader election Must-know
In plain words: time is divided into numbered terms. A follower that hears nothing from a leader for a random while becomes a candidate, bumps the term and asks for votes. Whoever gets a majority leads that term. Anyone who sees a higher term steps down.
Common misunderstanding: "The node with the most data, or the oldest node, becomes leader." Any node can win, but only if its log is at least as up-to-date as the logs of a majority of voters (the election restriction). A node missing committed entries cannot win.
Definition: each server is a follower, candidate or leader. Leaders send periodic heartbeats (empty AppendEntries). A follower whose randomised election timeout elapses (the paper's example is 150–300 ms) increments currentTerm, votes for itself and sends RequestVote(term, lastLogIndex, lastLogTerm). Each server grants at most one vote per term, and only to a candidate whose last log term is higher, or equal with an index at least as high. Raft "ensures that there is at most one leader in a given term". A new leader commits a blank no-op entry at the start of its term to learn which entries are committed.
S1 (leader, term 4) S2 (follower) S3 (follower)
1 heartbeat -> S2, S3
2 S1 partitioned away
3 timeout 212 ms: term 5, votes for self
4 RequestVote(5, lastIndex 41, lastTerm 4) -> S3
5 grants vote (log not ahead of S2's)
6 leader of term 5 (2 of 3), appends no-op
7 partition heals: S1 sends AppendEntries(term 4) -> rejected, S1 sees term 5, steps downReal scenarios: a leader's long GC pause or a full disk causes a re-election; CockroachDB moves leases (and Raft leadership) when a node dies; an etcd cluster under heavy disk latency shows frequent leader changes (etcd_server_leader_changes_seen_total rising).
| Knob | etcd | CockroachDB | TiKV / YugabyteDB |
|---|---|---|---|
| Heartbeat / election timing | --heartbeat-interval, --election-timeout | Internal; tied to Leader leases and store liveness | raft-base-tick-interval, raft-election-timeout-ticks (TiKV); leader_failure_max_missed_heartbeat_periods (YugabyteDB) |
| Leader placement | n/a | Lease preferences, zone configs, --locality | PD scheduling (TiKV), preferred zones (YugabyteDB) |
Fix / how to use it: keep fsync latency low and stable (Raft persists votes and entries before answering), size election timeouts well above the network RTT, and expect writes to pause for roughly one election timeout plus a lease handover when a leader dies.
Log replication and the commit index Must-know
In plain words: the leader appends each write to its log and sends it to followers. Once a majority has stored it, the entry is committed: it will never be lost, and the leader can apply it and answer the client.
Common misunderstanding: "An entry stored on a majority is committed, whatever its term." Not for entries from earlier terms: Raft commits an old-term entry only indirectly, once an entry from the leader's current term is replicated on a majority (Figure 8 of the paper shows how counting replicas of old entries can lose data).
Definition: the leader sends AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries[], leaderCommit). A follower accepts only if its log has an entry at prevLogIndex with prevLogTerm (the log matching property); otherwise the leader decrements nextIndex for that follower and retries, overwriting conflicting uncommitted entries. "A log entry is committed once the leader that created the entry has replicated it on a majority of the servers"; the leader tracks the highest such index as commitIndex and piggybacks it in leaderCommit, and each server applies entries up to commitIndex to its state machine (lastApplied). Clients that retry after a leader crash can cause a command to run twice; Raft's fix is client serial numbers so the state machine can answer duplicates without re-executing.
Client Leader S1 (term 3) S2 S3 S4 (slow) S5 (down)
1 INSERT -> append #6 (fsync)
2 AppendEntries #6 -> append #6 append #6 (queued)
3 ack ack
4 3 of 5 have #6: commitIndex = 6, apply #6
5 <- OK
6 next heartbeat: leaderCommit = 6 -> S2, S3 apply #6Real scenarios: a CockroachDB write that touches one range is acknowledged after the leaseholder (the Raft leader) and one other replica of three have it; YugabyteDB: "After receiving a replication successful callback from the Raft subsystem, the leader applies the write batch to its local DocDB"; a TiKV write "succeeds" "only when the data is written to the majority of replicas of a Region".
| Product | Unit of replication | Default replicas | Leader name |
|---|---|---|---|
| CockroachDB | Range | 3 ("at least 3 nodes by default") | Raft leader = leaseholder |
| TiKV (TiDB) | Region (256 MiB default size limit) | 3 peers | Region leader |
| YugabyteDB | Tablet | 3 (replication factor) | Tablet leader |
| etcd | Whole keyspace | Cluster size (3 or 5) | Leader |
| Spanner | Paxos group per split | Configuration-dependent | Paxos leader |
Membership changes and joint consensus Important
In plain words: you cannot flip from the old member list to the new one in one step, because during the flip some servers use the old list and some the new, and each group could elect its own leader. Raft passes through a combined configuration where decisions need a majority of both.
Common misunderstanding: "Replacing a dead node is just adding a new one." If you add before removing in a 3-node cluster with one dead node, you have 4 members and need 3 votes from the 2 live ones plus the newcomer; if the newcomer is slow to catch up, writes stall. Remove the dead member first (or add as a non-voting learner first, then promote).
Definition: the leader replicates a Cold,new entry; once committed, it replicates Cnew. While Cold,new is active, elections and commits need separate majorities of the old and the new configurations, so two disjoint majorities cannot exist. New servers first join as non-voting members to catch up. Removed servers can disrupt the cluster with higher-term RequestVotes; Raft's guard is that servers ignore a RequestVote "within the minimum election timeout of hearing from a current leader". etcd's FAQ notes that peer URL changes "must go through quorum to avoid membership configuration split brain".
Config {A,B,C} -> {A,B,D}
1 leader A appends C_old,new = {A,B,C}+{A,B,D}
2 commit needs 2 of {A,B,C} AND 2 of {A,B,D}
3 C_old,new committed -> A appends C_new = {A,B,D}
4 C_new committed -> C may shut down; if A is not in C_new it steps downReal scenarios: etcdctl member add --learner then member promote; CockroachDB rebalancing a range from one node to another (adds a learner, sends a snapshot, promotes, removes the old replica); a cluster stuck after someone removed two members of five at once while one other was down.
Snapshots and log compaction Important
In plain words: the log cannot grow forever. Each server periodically saves its current state and throws away the log before it. A follower that fell too far behind receives the saved state instead of old entries.
Common misunderstanding: "Snapshots are backups." A Raft snapshot is a compaction point and a catch-up mechanism for one replica; it is not a point-in-time backup you can restore a cluster from. Backups are a separate feature (Backup, PITR & DR).
Definition: "Snapshotting is the simplest approach to compaction." The snapshot records the last included index and term, so that AppendEntries consistency checks still work for the next entry. The leader sends InstallSnapshot to a follower whose nextIndex points into the discarded prefix. CockroachDB uses MVCC to snapshot a replica "as of a specific timestamp", sends snapshots when rebalancing, and since v23.1 can send delegated snapshots from a follower closer to the recipient, to save WAN bandwidth.
Leader log: [snapshot up to #10 000][#10 001 ... #10 250]
1 follower F was down 2 hours; its last index is #7 900
2 leader: nextIndex[F] = 7 901 < first log index 10 001
3 InstallSnapshot(lastIncludedIndex 10 000, lastIncludedTerm 12, data) -> F
4 F replaces its state, then receives #10 001 ... by AppendEntriesReal scenarios: a replaced disk triggers a full snapshot of every range on that node; snapshot transfers saturate a cross-region link (CockroachDB can throttle snapshot ingest via admission control); etcd's --snapshot-count controls how often it snapshots; a bloated etcd needs compaction and defragmentation of its MVCC store, which is a different, application-level compaction.
Pre-vote and CheckQuorum Good to know
In plain words: before a follower starts a real election, it asks "would you vote for me?" without bumping the term. A node that was isolated cannot then come back and depose a healthy leader just because its term number grew while it was alone.
Common misunderstanding: "Pre-vote is in the Raft paper." It is in Ongaro's PhD thesis (§9.6); the extended paper only has the narrower rule for removed servers. etcd's Raft library documents both options.
Definition (etcd go.etcd.io/raft/v3): "When Config.PreVote is true, a pre-election is carried out first (using the same rules as a regular election), and no node increases its term number unless the pre-election indicates that the campaigning node would win." CheckQuorum makes a leader step down if it has not heard from a quorum within an election timeout, so a partitioned leader stops believing it leads. YugabyteDB lists "leader leases and pre-voting state during learner mode" among its Raft enhancements.
Without pre-vote With pre-vote
1 S3 isolated, times out repeatedly: term 9, 10, 11 S3 sends PreVote(term 9): nobody grants
2 rejoins: RequestVote(term 11) forces leader (term 8) to step down term stays 8, leader stays
3 election storm, writes pause no disruptionLeader leases Important
In plain words: a lease is a time-limited guarantee that no other leader can exist. While it holds, the leader can answer reads from local state without asking anyone.
Common misunderstanding: "A lease is free consistency." It trades a network round for an assumption about clocks. The Raft paper: the leader "could rely on the heartbeat mechanism to provide a form of lease [9], but this would rely on timing for safety (it assumes bounded clock skew)."
Definition: a leader obtains lease votes from a quorum; each voter promises not to support another leader until the lease expires (by its own clock, with a safety margin). Spanner: "Spanner's Paxos implementation uses timed leases to make leadership long-lived (10 seconds by default)", and it depends on the invariant that each Paxos leader's lease interval "is disjoint from every other leader's". CockroachDB: "CockroachDB ensures that the leaseholder is also the Raft group leader via the Leader leases mechanism"; Leader leases (the leasing regime since v25.2) superseded epoch-based leases, which "are vulnerable to leader-leaseholder splits". In etcd's library, ReadOnlyLeaseBased relies on the leader lease for linearizable reads (per its doc comment), and "CheckQuorum MUST be enabled if ReadOnlyOption is ReadOnlyLeaseBased."
Old leader L1 (lease until 10:00:10.000 by its clock) New leader L2
1 10:00:09.900 local read served from L1's state (OK, lease valid)
2 L1 is partitioned; voters' promises expire at 10:00:10.000 (+ max offset)
3 10:00:10.600 elected, starts serving
4 if L1's clock ran 1 s slow, it believes it still holds the lease at 10:00:10.600
-- stale read: the reason every lease system bounds clock offset (CockroachDB --max-offset)Real scenarios: CockroachDB serves consistent reads at the leaseholder without a Raft round; Spanner leaders assign timestamps only inside their lease interval; TiKV "lease read" on the Region leader; a VM live-migration that froze a leader's clock is the classic way leases fail.
Reads, leases and split brain
Linearizable reads: read index and lease reads Must-know
In plain words: a read is linearizable if it sees every write that finished before the read started. In a replicated system, the danger is asking a node that thinks it is leader but was replaced a second ago.
Common misunderstanding: "Reading from the leader is always fresh." A deposed leader that has not noticed yet will happily serve stale data. The Raft paper: a read-only request without extra measures "would run the risk of returning stale data, since the leader responding to the request might have been superseded by a newer leader of which it is unaware."
Definition: three ways to serve a linearizable read in Raft. (1) Log read: put the read through the log like a write (simple, costs a write round and an fsync). (2) Read index: the leader records its commitIndex as the read index, confirms it is still leader by exchanging heartbeats with a majority, waits until it has applied up to the read index, then reads locally; the paper prescribes the two precautions (commit a no-op at term start; "exchange heartbeat messages with a majority of the cluster before responding to read-only requests"), and etcd calls this ReadOnlySafe, which its doc comment says guarantees linearizability by communicating with the quorum. (3) Lease reads: skip the heartbeat round while a leader lease is valid (ReadOnlyLeaseBased in etcd; CockroachDB leaseholder reads; Spanner leader reads). Followers can also serve a read index: they ask the leader for the current commit index, wait until they have applied it, then read.
Client Leader L (term 6) Majority
1 GET k -> readIndex = commitIndex = 812
2 heartbeat round -> acks for term 6 -- still leader
3 wait until lastApplied >= 812
4 <- v read k from local state machine
-- lease read: skip step 2 while the lease is valid (assumes bounded clock offset)Real scenarios: Kubernetes reads from etcd are linearizable by default ("etcd ensures linearizability for all other operations by default"; serializable reads are opt-in); a feature flag service that must never show a flag as off after it was turned on; a leader-election lock read that must not see a stale holder.
| Product | Default read | Cheaper read |
|---|---|---|
| etcd | Linearizable (read index through the leader) | --consistency=s / serializable reads from any member, possibly stale |
| CockroachDB | Leaseholder read at the transaction timestamp (no Raft round) | Follower reads (AS OF SYSTEM TIME), stale |
| Spanner | Strong read at a current timestamp from any replica that is "sufficiently up-to-date" | Stale reads (exact or bounded staleness) |
| TiDB / TiKV | Region leader (ReadIndex or lease read) | Follower read, stale read (AS OF TIMESTAMP) |
| YugabyteDB | Tablet leader (with leader leases) | Follower reads with a staleness bound |
| ZooKeeper | Reads served locally by any server: may be stale | sync before read to catch up |
Follower reads Important
In plain words: read from the replica in your own region, at a timestamp slightly in the past that the replica is guaranteed to have complete. You trade a few seconds of staleness for a local, fast read.
Common misunderstanding: "Follower reads return whatever the follower has." They return a consistent snapshot at a chosen timestamp; if the follower is not yet complete up to that timestamp, the read goes to the leaseholder or waits. You get stale but never torn data.
Definition (CockroachDB): each range tracks a closed timestamp, "a promise by the range's leaseholder to its follower replicas that it will not accept writes below that timestamp". A follower that has applied the Raft log up to the leaseholder's indicated position can serve reads at or below it. Exact staleness: AS OF SYSTEM TIME follower_read_timestamp() (or a fixed timestamp); bounded staleness: with_max_staleness('10s') / with_min_timestamp(...), which picks the freshest timestamp a local replica can serve. GLOBAL tables in multi-region databases make strong reads local everywhere by writing with a future timestamp (slower writes). Spanner's equivalents are snapshot reads with a client-provided timestamp or staleness bound, which "proceeds at any replica that is sufficiently up-to-date".
Client in eu-west Follower (eu-west) Leaseholder (us-east)
1 SELECT ... AS OF SYSTEM TIME follower_read_timestamp() -- a few seconds in the past
2 closed ts >= read ts? yes
3 <- rows (2 ms, no transatlantic RTT)
-- without AS OF SYSTEM TIME the read would go to us-east: + ~80 ms RTTReal scenarios: product catalogue and search pages in a multi-region shop; analytics dashboards; a "recently viewed" list; never for "did my payment go through?" right after paying.
Split brain and fencing tokens Must-know
In plain words: split brain is two nodes both believing they are the leader and both accepting writes. Fencing makes the storage reject the old leader, so even a confused old leader cannot do damage.
Common misunderstanding: "A lock with a TTL in Redis (or any lease) prevents two leaders." A process can pause (GC, VM freeze, swap) after checking its lease, wake after the lease expired and another holder took over, and still write. Kleppmann: "you need to include a fencing token with every write request to the storage service."
Definition: split brain occurs when failover tooling promotes a new primary while the old one still accepts writes (classic async PostgreSQL or MySQL failover without fencing, Redis Sentinel during a partition). Consensus prevents it inside the replicated system because a term needs a majority. Fencing extends that protection to outside resources: every leader gets a monotonically increasing token (Raft term, ZooKeeper zxid, etcd revision, a database sequence), sends it with each write, and the resource rejects any token lower than the highest it has seen. Kleppmann: with ZooKeeper "you can use the zxid or the znode version number as fencing token"; Redis Redlock "does not have any facility for generating fencing tokens". STONITH ("shoot the other node in the head") is the infrastructure version: power off the old primary.
Worker A (lease token 33) Lock service Storage
1 acquires lock, token 33
2 GC pause 15 s ... lease expires
3 Worker B acquires, token 34
4 B writes with token 34: accepted, max=34
5 A wakes, writes with token 33 -> rejected: 33 < 34Real scenarios: two PostgreSQL primaries after a Patroni misconfiguration both accept orders (see Replication & Failover); two cron "leaders" both send the monthly invoices; a Kubernetes controller pair both reconcile; a Redis-lock-protected job runs twice during a GC pause.
Fix: use a consensus-backed lock (etcd lease, ZooKeeper ephemeral node, a database row) and pass its token to the resource; in SQL, a write that re-checks the current token under FOR SHARE in the same statement makes the database the fence. Code in fencing.
Zab (ZooKeeper) and etcd Good to know
In plain words: ZooKeeper and etcd are small consensus-replicated key-value stores that other systems use for configuration, leader election, locks and membership. ZooKeeper runs its own protocol, Zab; etcd runs Raft.
Common misunderstanding: "ZooKeeper reads are linearizable because writes go through consensus." ZooKeeper reads are served from the local server and may lag; you call sync first when you need the latest value. etcd reads are linearizable by default.
Definition: Zab (ZooKeeper Atomic Broadcast) has a leader that stamps every proposal with a zxid: "The zxid has two parts: the epoch and a counter", the high 32 bits epoch and the low 32 bits counter, so a new leader's epoch makes its zxids larger than anything before. Proposals are "committed when a quorum of them acknowledge the proposal". Zab differs from Raft in its recovery phase (the new leader synchronises followers before broadcasting) and in being designed as primary-backup atomic broadcast rather than a general log. etcd stores a single MVCC keyspace replicated by Raft, with leases (TTL'd keys), watches, and transactions (If/Then/Else compare-and-swap); "linearized requests must go through the Raft consensus process."
| ZooKeeper (Zab) | etcd (Raft) | |
|---|---|---|
| Ordering id | zxid = epoch + counter | Raft term + index; MVCC revision |
| Default reads | Local, possibly stale (sync to catch up) | Linearizable |
| Locks / election | Ephemeral sequential znodes | Leases + concurrency.Election / Mutex |
| Fencing token | zxid or znode version | Revision of the lock key |
| Used by | HBase, older Kafka (pre-KRaft), Solr | Kubernetes, CoreDNS, Patroni (DCS option) |
Distributed SQL designs
Spanner: TrueTime, commit wait and external consistency Important
In plain words: Spanner's clocks report an interval ("it is now somewhere between 10:00:00.003 and 10:00:00.010"), not an instant. A transaction takes the top of the interval as its commit timestamp and then waits until that timestamp is certainly in the past before anyone may see the write. After that, every later transaction anywhere gets a larger timestamp.
Common misunderstanding: "Spanner has perfectly synchronised clocks, so it needs no waiting." It has bounded-uncertainty clocks (GPS and atomic clocks keep ε small) and it does wait: "the expected wait is at least 2 ∗ϵ". Small ε makes the wait short, not zero.
Definition: TT.now() returns TTinterval: [earliest,latest]; TT.after(t) is true if t has definitely passed. In the paper, ε ranged "from about 1 to 7 ms over each poll interval". Start rule: "The coordinator leader for a write Ti assigns a commit timestamp si no less than the value of TT.now().latest". Commit wait: "The coordinator leader ensures that clients cannot see any data committed by Ti until TT.after(si) is true." Together these give external consistency (strict serializability):
"if a transaction T1 commits before another transaction T2 starts, then T1's commit timestamp is smaller than T2's." — Corbett et al., Spanner: Google's Globally-Distributed Database, OSDI 2012
Read-write transactions use two-phase locking at Paxos leaders and 2PC across groups; read-only transactions are lock-free at a chosen timestamp and can run "on any replica that is sufficiently up-to-date"; snapshot reads take a client timestamp or staleness bound.
T1 (transfer, coordinator leader in us-central) T2 (balance check, starts after T1 returns)
1 locks acquired, prepare on participant groups
2 TT.now() = [100.003, 100.010] -> s1 = 100.010
3 Paxos-replicate commit record (overlaps with the wait)
4 commit wait until TT.now().earliest > 100.010 (~7 ms)
5 release locks, reply OK
6 TT.now() = [100.012, 100.019] -> read ts 100.019 > s1
7 sees T1: external consistencyReal scenarios: global ledgers that must never show a later transfer without an earlier one; Spanner-backed systems that let any region read "now" consistently; the reason CockroachDB, which lacks TrueTime, offers serializability plus uncertainty-interval restarts rather than the same guarantee.
| Spanner (TrueTime) | CockroachDB (HLC) | TiDB (PD timestamp oracle) | |
|---|---|---|---|
| Clock source | GPS + atomic clocks, bounded ε | NTP-synced wall clock + logical counter | Central timestamp service (PD) |
| Write cost from clocks | Commit wait ≈ 2ε | None on commit; reads may restart inside the uncertainty interval | One round trip to PD for start_ts and commit_ts |
| Guarantee | External consistency | Serializable; single-key linearizable while offsets stay within --max-offset | Snapshot isolation (default pessimistic mode) |
CockroachDB: ranges, leaseholders, HLC, Serializable and Read Committed Must-know
In plain words: CockroachDB chops all data into small sorted key ranges, each copied to three nodes by Raft. One copy of each range, the leaseholder, handles its reads and writes. Transactions that touch several ranges commit with a protocol built on a transaction record and provisional "intents".
Common misunderstanding: "Any node I connect to holds my data." The node you connect to is just the gateway; it routes each key's request to that range's leaseholder, which may be in another region. Latency depends on where leaseholders are, not on which node you connect to.
Definition: the keyspace "is divided into contiguous chunks called ranges", each "replicated to at least 3 nodes by default", each a Raft group whose leader is the leaseholder ("the only node that can serve reads or propose writes to the Raft group leader"). Writes create write intents, "a combination of a provisional value and an exclusive lock", pointing to a transaction record whose state is PENDING, STAGING, COMMITTED or ABORTED. Parallel Commits writes the STAGING record in parallel with the last intents, so a cross-range transaction usually commits after one round of consensus; intents are resolved asynchronously afterwards. Timestamps come from hybrid logical clocks (HLC), "composed of a physical component (always close to local wall time) and a logical component". CockroachDB "requires moderate levels of clock synchronization"; the bound is --max-offset, and a read that finds a value inside its uncertainty window may restart (ReadWithinUncertaintyIntervalError). The default isolation is SERIALIZABLE, with client-side retry of 40001; READ COMMITTED is available (the sql.txn.read_committed_isolation.enabled cluster setting is true by default) and "READ COMMITTED transactions do not return serialization errors that require client-side handling" because each statement takes a fresh snapshot and can be retried internally.
Gateway (txn T) Range 7 leaseholder (wallets) Range 12 leaseholder (invoices)
1 BEGIN; ts = HLC 100.0
2 UPDATE wallets -> write intent k1 (Raft) -> creates txn record PENDING
3 UPDATE invoices -> write intent k2 (Raft)
4 COMMIT -> txn record STAGING (in parallel with k2's replication)
5 <- COMMIT OK once all intents and STAGING are replicated (implicitly committed)
6 async: record -> COMMITTED, intents resolved into MVCC valuesReal scenarios: a payments service moved from PostgreSQL to CockroachDB to survive a zone failure; RETRY_WRITE_TOO_OLD on a hot counter row; a migration from PostgreSQL Read Committed code that is not ready for 40001 retries (use CockroachDB Read Committed); SHOW RANGES used to find which node holds a table's leaseholders.
Retry error (all SQLSTATE 40001, message contains "restart transaction") | Meaning |
|---|---|
RETRY_WRITE_TOO_OLD | Another transaction with a higher timestamp already wrote the row you are writing |
RETRY_SERIALIZABLE | Your timestamp was pushed and your earlier reads are no longer valid at the new one |
ReadWithinUncertaintyIntervalError | A value within the clock-offset window might be in your past; restart above it |
RETRY_ASYNC_WRITE_FAILURE | A pipelined write failed to replicate (often a node problem) |
ABORT_REASON_* (e.g. ABORT_REASON_ABORTED_RECORD_FOUND) | Another transaction aborted yours to resolve a conflict |
Percolator and TiDB Important
In plain words: Percolator does 2PC without a separate coordinator log: one of the transaction's own keys is the primary, and the commit status of the whole transaction is "whatever the primary key's record says". Anyone who finds a stale lock can look at the primary to decide.
Common misunderstanding: "TiDB transactions are optimistic and fail at commit." TiDB 3.0.8 and later default new clusters to the pessimistic mode ("the same as MySQL"); optimistic mode, where COMMIT can return a write conflict, is opt-in.
Definition: Percolator (Peng & Dabek, OSDI 2010) provides snapshot isolation on Bigtable with "two small services: the timestamp oracle and the lightweight lock service". TiDB's version: get start_ts from PD; buffer writes; at commit pick the first key as primary, prewrite (lock + write data) the primary and then all secondaries in parallel per Region, get commit_ts from PD, commit the primary (this is the commit point), then commit secondaries asynchronously. TiKV stores data in Regions with "Typically there are 3 peers in a Region", each a Raft group, and offers "Snapshot Isolation level isolation by default".
TiDB PD TiKV Region A (primary k1) TiKV Region B (k2)
1 get start_ts -> ts 400
2 prewrite(k1 primary, 400) -> lock k1 -> primary, data@400
3 prewrite(k2, primary=k1, 400) -> lock k2 -> points to k1
4 get commit_ts -> ts 405
5 commit(k1, 405) -> write record k1@405, unlock -- COMMIT POINT
6 async commit(k2, 405) -> (if TiDB crashes now, a reader
of k2 checks k1 and rolls forward)Real scenarios: MySQL-compatible OLTP at scale on TiDB; hot PD becomes a bottleneck or a cross-region hop for timestamps; large transactions hitting txn-total-size-limit; stale reads with AS OF TIMESTAMP for reports.
YugabyteDB: tablets, Raft and DocDB Good to know
In plain words: YugabyteDB reuses PostgreSQL's query layer (YSQL) on top of its own distributed storage, DocDB. Tables split into tablets; each tablet is a Raft group storing data in RocksDB.
Common misunderstanding: "YSQL is PostgreSQL with replication." The SQL layer is PostgreSQL code, but storage, transactions, locking and replication are DocDB's, so performance characteristics and some features differ.
Definition: "The tablet data is optimally stored and managed by DocDB, a document store that has been built on top of RocksDB". Raft in YugabyteDB "is based on Apache Kudu's implementation of Raft but has several enhancements, such as leader leases and pre-voting state during learner mode". Writes: "The leader appends the batch to its Raft log and chooses a hybrid timestamp as the timestamp for the batch", and data is durable once "the log entry has been replicated on a majority of participants". APIs: YSQL (PostgreSQL-compatible) and YCQL (Cassandra-compatible).
YSQL backend Tablet leader (Raft) Followers
1 INSERT ... -> DocDB write
2 lock key (in-memory), build RocksDB batch, hybrid ts
3 append to Raft log -> append, ack (majority)
4 apply to local DocDB, ack client
5 next heartbeat -> followers apply to their RocksDBCalvin: deterministic ordering instead of 2PC Good to know
In plain words: instead of executing first and agreeing at commit, Calvin agrees on the order of a batch of transactions first (by replicating an input log), and then every replica executes them deterministically in that order. Nobody can vote no at the end, so no 2PC is needed.
Common misunderstanding: "Deterministic databases can run any SQL." They need to know a transaction's read/write set before execution (or discover it with a reconnaissance step), which rules out arbitrary interactive transactions with BEGIN ... think ... COMMIT.
Definition: Calvin (Thomson et al., SIGMOD 2012) is "a practical transaction scheduling and data replication layer that uses a deterministic ordering guarantee to significantly reduce the normally prohibitive contention costs associated with distributed transactions." Its argument against 2PC: "all of a transaction's locks must be held for the full duration of this agreement protocol, which is typically two-phase commit." A sequencer layer batches requests every few milliseconds and replicates the batch (Paxos or async), a scheduler acquires locks in the global order, and execution is deterministic. FaunaDB was the best-known commercial descendant.
Sequencer (epoch 10 ms) Replica R1 Replica R2
1 batch [T5, T6, T7] replicated by Paxos
2 lock in order T5,T6,T7 lock in order T5,T6,T7
3 execute -> same state execute -> same state
-- no commit vote: a crash replays the input logWhat each product really does
| Product | Consensus | Cross-shard commit | Clock | Default isolation | Reads |
|---|---|---|---|---|---|
| Google Spanner | Multi-Paxos per split, 10 s leader leases | 2PC over Paxos groups | TrueTime + commit wait | Serializable with external consistency | Strong from any up-to-date replica; stale reads |
| CockroachDB | Raft per range (3 replicas default), Leader leases | Parallel Commits (transaction record + write intents) | HLC, --max-offset bound | SERIALIZABLE (READ COMMITTED available) | Leaseholder; follower reads via closed timestamps |
| TiDB / TiKV | Raft per Region (3 peers) | Percolator (primary key, prewrite, commit) | PD timestamp oracle | Snapshot isolation; pessimistic mode default since v3.0.8 | Region leader; follower/stale read |
| YugabyteDB | Raft per tablet (Kudu-based, leader leases, pre-vote) | Distributed transactions in DocDB | Hybrid time | YSQL: Read Committed on new v2025.2+ universes (yugabyted, Anywhere, Aeon); otherwise effectively Snapshot; Serializable available | Tablet leader; follower reads |
| etcd | Raft, whole keyspace | Single group (no cross-shard) | n/a | Serializable transactions (Txn) | Linearizable by default; serializable opt-in |
| ZooKeeper | Zab, zxid = epoch + counter | Single group (multi ops) | n/a | n/a | Local, possibly stale; sync |
| PostgreSQL | None built in (streaming replication + external failover) | PREPARE TRANSACTION (participant only) | n/a | Read Committed | Primary; replicas can lag |
| MySQL / InnoDB | Group Replication uses a Paxos variant; classic replication none | XA statements (participant only) | n/a | Repeatable Read | Primary; replicas can lag |
| MongoDB | Replica-set elections, protocol version pv1 (default) | Multi-document "distributed transactions" across shards | Cluster time | Snapshot for transactions | Primary by default; read preference and read concern |
| SQLite | None | Multi-file atomic commit across ATTACHed databases on one host | n/a | Serializable | Local file |
| Redis | None for data (Sentinel/Cluster failover is not consensus on writes) | MULTI/EXEC per node only | n/a | n/a | Primary; replicas async |
Notes worth remembering. MongoDB's pv1 "guarantees the preservation of confirmed w: "majority" writes" but not of w:1 writes on failover. A Redlock-style lock in Redis gives no fencing token. MySQL Group Replication and PostgreSQL extensions such as Citus are covered in Replication & Failover and Partitioning & Sharding; this page treats them only as reference points.
Mechanics
Write latency = RTT math Must-know
A consensus write is acknowledged when the leader has the entry durably and enough followers have acknowledged to form a majority. So the replication cost is the round trip from the leader to the follower that completes the quorum: the nearest one in a 3-replica group (leader + 1), the second-nearest in a 5-replica group (leader + 2). It is not the slowest replica. Add the client's round trip to the leader (the leaseholder, for CockroachDB), the fsync on each node, and for multi-range transactions the commit protocol.
commit latency ≈ RTT(client -> gateway -> leaseholder)
+ max(fsync_leader, RTT(leader -> k-th nearest follower) + fsync_follower) where k = quorum - 1
+ cross-range commit (≈ 0 extra rounds with Parallel Commits, +1 round classic 2PC)
+ clock wait (Spanner commit wait ≈ 2ε; CockroachDB none on write)Worked numbers. The RTTs are illustrative assumptions for three regions A, B, C: A–B 10 ms, A–C 70 ms, B–C 65 ms, within a region 1 ms; fsync 1 ms.
| Placement | Quorum completes at | Replication cost | Client in A | Client in C |
|---|---|---|---|---|
| 3 replicas, 3 zones of region A, leader in A | Nearest zone, 1 ms | ≈ 2 ms | ≈ 3 ms | ≈ 72 ms (client RTT dominates) |
| 3 replicas in A, B, C, leader in A | B at 10 ms | ≈ 11 ms | ≈ 12 ms | ≈ 81 ms |
| 3 replicas in A, B, C, leader in C | B at 65 ms | ≈ 66 ms | ≈ 136 ms | ≈ 67 ms |
| 5 replicas A, A, B, B, C, leader in A | 2nd follower: A (1 ms) and B (10 ms) | ≈ 11 ms | ≈ 12 ms | ≈ 81 ms |
| Spanner-style, + commit wait ε = 4 ms | as above | + ~8 ms unless overlapped with Paxos |
Three consequences. Put leaders (leaseholders) where the writes come from: CockroachDB REGIONAL BY ROW tables home each row in the region that writes it. Surviving a region failure needs voters in at least three regions, so writes pay at least the RTT to the nearest other region. And the client-to-leader hop is often larger than replication: a client in C writing to a leader in A pays 70 ms before consensus even starts.
Knobs Important
| Knob | Product | Effect |
|---|---|---|
max_prepared_transactions | PostgreSQL | 0 (default) disables PREPARE TRANSACTION; restart required; set ≥ max_connections if used |
XA_RECOVER_ADMIN privilege | MySQL 8 | Required for XA RECOVER |
--max-offset | CockroachDB | Maximum allowed clock offset; nodes beyond it are at risk of consistency violations |
--locality | CockroachDB | Region/zone labels used for replica and lease placement |
--join, cockroach init | CockroachDB | Cluster bootstrap |
sql.txn.read_committed_isolation.enabled | CockroachDB | Allows READ COMMITTED transactions (true by default) |
default_transaction_use_follower_reads | CockroachDB | Makes read-only transactions use follower_read_timestamp() |
ALTER DATABASE ... SURVIVE REGION FAILURE / ZONE FAILURE | CockroachDB | Survival goal (zone is default) |
--heartbeat-interval, --election-timeout, --snapshot-count | etcd | Raft timing and snapshot frequency |
PreVote, CheckQuorum, ReadOnlyOption | etcd raft library | Election disruption guards, read mode (ReadOnlySafe / ReadOnlyLeaseBased) |
tidb_txn_mode | TiDB | pessimistic (default for new clusters) or optimistic |
catchUpTimeoutMillis | MongoDB replica sets | Trade faster failover against preserving w:1 writes |
Error codes you will catch Must-know
| Error | Product | Meaning | Retry? |
|---|---|---|---|
SQLSTATE 40001, "restart transaction" | CockroachDB | Serialization or uncertainty conflict | Yes, whole transaction |
SQLSTATE 40001 | PostgreSQL Serializable/RR, YugabyteDB | Serialization failure | Yes, whole transaction |
Write conflict at COMMIT | TiDB optimistic mode | Another transaction committed the key first | Yes (or switch to pessimistic) |
| "prepared transactions are disabled" | PostgreSQL | max_prepared_transactions = 0 | No: configuration |
| "transaction identifier ... is already in use" | PostgreSQL PREPARE TRANSACTION | Duplicate gid | No: bug in gid generation |
| "prepared transaction with identifier ... does not exist" | PostgreSQL COMMIT PREPARED | Already finished (by recovery) or wrong database | No: check pg_prepared_xacts |
ER_XAER_RMFAIL (1399) | MySQL | Statement not allowed in the XA transaction's current state | No: fix the XA state machine |
NotLeader / "not leader" | etcd, TiKV, YugabyteDB clients | Request reached a follower | Yes, to the new leader (drivers do it) |
etcdserver: request timed out | etcd | No quorum or slow disk | Yes with backoff; investigate quorum |
Ambiguous result (40003 statement_completion_unknown) | CockroachDB | Connection lost during COMMIT; outcome unknown | Only if the transaction is idempotent |
Solving the classic problems
One business action across two databases
A payment debits a wallet in one database and marks an invoice paid in another.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Two local commits in sequence (the bug) | Commit wallets, then commit billing | Simple | A crash between them leaves money taken and the invoice open, silently |
| PostgreSQL 2PC with a decision log | PREPARE TRANSACTION on both, durable decision, COMMIT PREPARED, recovery job | Atomic across PostgreSQL databases | Blocking on coordinator failure; locks held across network rounds; you now operate a transaction manager |
| Move both tables into one distributed SQL database | One ordinary transaction in CockroachDB/YugabyteDB/TiDB | Atomic, non-blocking (replicated coordinator state), scales out | Quorum latency per write, 40001 retries, migration effort |
| Transactional outbox + idempotent consumer | Commit the debit and an invoice.paid message together; billing applies it once | Each service keeps its own database, no distributed locks | Eventual consistency; you need dedup and monitoring of the relay |
| Saga with compensation | Local steps, each with an undo (refund) | Works across many services and external APIs | No isolation between steps; compensations must be designed |
Before (Go): two databases, two commits.
// Package main moves credit from a wallet in one PostgreSQL database to an
// invoice in another, by committing two local transactions one after the other.
package main
import (
"context"
"database/sql"
"log"
"os"
_ "github.com/jackc/pgx/v5/stdlib"
)
// Pay looks atomic but is two independent commits. If the process crashes,
// the network drops or billing rejects the write after the wallet commit,
// the customer has been charged and the invoice is still open. Nothing
// records that the second half is missing, so nothing will ever fix it.
func Pay(ctx context.Context, wallets, billing *sql.DB, customerID, invoiceID int64, cents int) error {
tx1, err := wallets.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx1.Rollback()
if _, err := tx1.ExecContext(ctx,
`UPDATE wallets SET balance_cents = balance_cents - $1 WHERE customer_id = $2`,
cents, customerID); err != nil {
return err
}
if err := tx1.Commit(); err != nil { // first database is now final
return err
}
// A crash here leaves the two databases disagreeing forever.
tx2, err := billing.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx2.Rollback()
if _, err := tx2.ExecContext(ctx,
`UPDATE invoices SET paid_cents = paid_cents + $1 WHERE id = $2`,
cents, invoiceID); err != nil {
return err // too late to undo the wallet debit
}
return tx2.Commit()
}
func main() {
wallets, err := sql.Open("pgx", os.Getenv("WALLETS_DSN"))
if err != nil {
log.Fatal(err)
}
billing, err := sql.Open("pgx", os.Getenv("BILLING_DSN"))
if err != nil {
log.Fatal(err)
}
if err := Pay(context.Background(), wallets, billing, 42, 7, 1500); err != nil {
log.Fatal(err)
}
}After (Go): PostgreSQL two-phase commit. Each participant runs its work on a pinned *sql.Conn and ends with PREPARE TRANSACTION. The coordinator writes its decision to a log table (presumed abort: only commit decisions are written on the happy path), and COMMIT PREPARED runs on every participant. Recover scans pg_prepared_xacts and finishes anything a crash left behind. The comment in the code says what this does not fix: the coordinator and its log are still a single point at which prepared transactions wait while holding locks.
// Package twophase runs one transaction across several PostgreSQL databases
// with PREPARE TRANSACTION / COMMIT PREPARED. Every participant must be
// started with max_prepared_transactions > 0; the default of 0 disables 2PC.
package twophase
import (
"context"
"database/sql"
"errors"
"fmt"
"regexp"
"time"
)
// The decision log lives in the coordinator's own database:
//
// CREATE TABLE twopc_decisions (
// gid text PRIMARY KEY,
// outcome text NOT NULL CHECK (outcome IN ('commit', 'abort')),
// decided_at timestamptz NOT NULL DEFAULT now()
// );
//
// The coordinator is still a single point of failure. If it, or this log,
// is unavailable after the participants have prepared, they keep holding
// their row locks (and pin VACUUM's horizon) until Recover runs again.
// That is the blocking problem of two-phase commit; this code does not
// remove it, it only makes the outcome recoverable.
type Coordinator struct {
Log *sql.DB
Participants map[string]*sql.DB
}
// Step is one participant's share of the work. Use at most one Step per
// participant, and make every participant a different PostgreSQL server:
// a gid can be prepared only once per server, not once per database.
type Step struct {
Participant string
SQL string
Args []any
}
const prefix = "twopc-"
// PREPARE TRANSACTION takes a string literal, not a bind parameter, so the
// identifier is validated before it is spliced into SQL.
var safeID = regexp.MustCompile(`^[a-z0-9-]{1,64}$`)
func (c *Coordinator) Run(ctx context.Context, id string, steps []Step) error {
if !safeID.MatchString(id) {
return fmt.Errorf("unsafe transaction id %q", id)
}
gid := prefix + id
// Phase 1: each participant does its work and votes by preparing.
for _, s := range steps {
db, ok := c.Participants[s.Participant]
if !ok {
return fmt.Errorf("unknown participant %q", s.Participant)
}
if err := prepare(ctx, db, gid, s); err != nil {
// Record the abort first, so a later Recover agrees with us.
if outcome, derr := c.decide(ctx, gid, "abort"); derr == nil {
_ = c.finish(ctx, gid, outcome)
}
return fmt.Errorf("prepare on %s: %w", s.Participant, err)
}
}
// Decision: the first outcome written for a gid wins. After this row
// commits, the global transaction is committed, whatever crashes next.
outcome, err := c.decide(ctx, gid, "commit")
if err != nil {
return err // ambiguous; Recover will read the log and finish
}
// Phase 2: any session may finish a prepared transaction.
if err := c.finish(ctx, gid, outcome); err != nil {
return err
}
if outcome != "commit" {
return fmt.Errorf("transaction %s was aborted by recovery", gid)
}
return nil
}
// Pay is the payment from the before snippet, now atomic across databases.
func (c *Coordinator) Pay(ctx context.Context, paymentID string, customerID, invoiceID int64, cents int) error {
return c.Run(ctx, paymentID, []Step{
{"wallets", `UPDATE wallets SET balance_cents = balance_cents - $1 WHERE customer_id = $2`,
[]any{cents, customerID}},
{"billing", `UPDATE invoices SET paid_cents = paid_cents + $1 WHERE id = $2`,
[]any{cents, invoiceID}},
})
}
func prepare(ctx context.Context, db *sql.DB, gid string, s Step) error {
// BEGIN, the work and PREPARE must run on one session, so pin a conn.
conn, err := db.Conn(ctx)
if err != nil {
return err
}
defer conn.Close()
if _, err := conn.ExecContext(ctx, "BEGIN"); err != nil {
return err
}
if _, err := conn.ExecContext(ctx, s.SQL, s.Args...); err != nil {
_, _ = conn.ExecContext(context.WithoutCancel(ctx), "ROLLBACK")
return err
}
// If PREPARE fails it acts as ROLLBACK. On success the session has no
// transaction any more and the prepared state is on disk.
_, err = conn.ExecContext(ctx, "PREPARE TRANSACTION '"+gid+"'")
return err
}
func (c *Coordinator) decide(ctx context.Context, gid, want string) (string, error) {
if _, err := c.Log.ExecContext(ctx,
`INSERT INTO twopc_decisions (gid, outcome) VALUES ($1, $2) ON CONFLICT (gid) DO NOTHING`,
gid, want); err != nil {
return "", err
}
var got string
err := c.Log.QueryRowContext(ctx,
`SELECT outcome FROM twopc_decisions WHERE gid = $1`, gid).Scan(&got)
return got, err
}
// finish applies the outcome on every participant that still holds gid.
func (c *Coordinator) finish(ctx context.Context, gid, outcome string) error {
stmt := "ROLLBACK PREPARED '" + gid + "'"
if outcome == "commit" {
stmt = "COMMIT PREPARED '" + gid + "'"
}
for name, db := range c.Participants {
var pending bool
if err := db.QueryRowContext(ctx,
`SELECT EXISTS (SELECT 1 FROM pg_prepared_xacts
WHERE gid = $1 AND database = current_database())`,
gid).Scan(&pending); err != nil {
return fmt.Errorf("%s: %w", name, err)
}
if !pending {
continue
}
// COMMIT PREPARED cannot run inside a transaction block.
if _, err := db.ExecContext(ctx, stmt); err != nil {
return fmt.Errorf("%s on %s: %w", outcome, name, err)
}
}
return nil
}
// Recover runs at start-up and on a timer. It finishes every prepared
// transaction this coordinator owns: commit if a commit decision exists,
// otherwise record "abort" once the prepare is older than grace, so that
// in-flight transactions are left alone.
func (c *Coordinator) Recover(ctx context.Context, grace time.Duration) error {
for name, db := range c.Participants {
rows, err := db.QueryContext(ctx,
`SELECT gid, prepared FROM pg_prepared_xacts
WHERE database = current_database() AND starts_with(gid, $1)`, prefix)
if err != nil {
return fmt.Errorf("%s: %w", name, err)
}
stale := map[string]bool{}
for rows.Next() {
var gid string
var at time.Time
if err := rows.Scan(&gid, &at); err != nil {
rows.Close()
return err
}
stale[gid] = time.Since(at) > grace
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for gid, old := range stale {
var outcome string
err := c.Log.QueryRowContext(ctx,
`SELECT outcome FROM twopc_decisions WHERE gid = $1`, gid).Scan(&outcome)
switch {
case errors.Is(err, sql.ErrNoRows) && !old:
continue // no decision yet and still young: in flight
case errors.Is(err, sql.ErrNoRows):
outcome, err = c.decide(ctx, gid, "abort") // a racing commit decision still wins
}
if err != nil {
return err
}
if err := c.finish(ctx, gid, outcome); err != nil {
return err
}
}
}
return nil
}After (Go): CockroachDB. Both tables live in one logical database and the application writes an ordinary transaction with pgx. Raft groups and Parallel Commits stay inside the database; the application's one remaining duty is the retry loop on 40001.
// Package main runs the same payment against CockroachDB. Wallets and
// invoices are two tables in one logical database; their rows may live in
// ranges on different nodes, each replicated by its own Raft group, but the
// application writes one ordinary SQL transaction.
package main
import (
"context"
"errors"
"log"
"os"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func Pay(ctx context.Context, conn *pgx.Conn, customerID, invoiceID int64, cents int) error {
return runTx(ctx, conn, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx,
`UPDATE wallets SET balance_cents = balance_cents - $1 WHERE customer_id = $2`,
cents, customerID); err != nil {
return err
}
_, err := tx.Exec(ctx,
`UPDATE invoices SET paid_cents = paid_cents + $1 WHERE id = $2`,
cents, invoiceID)
return err
})
}
// runTx retries the whole transaction on SQLSTATE 40001, which CockroachDB
// returns when a SERIALIZABLE transaction has to restart. The error can come
// from any statement or from COMMIT itself; pgx.BeginFunc returns both.
// The callback must be safe to run more than once: no side effects outside
// the transaction.
func runTx(ctx context.Context, conn *pgx.Conn, fn func(pgx.Tx) error) error {
const maxAttempts = 5
for attempt := 1; ; attempt++ {
err := pgx.BeginFunc(ctx, conn, fn)
var pgErr *pgconn.PgError
if err == nil || !errors.As(err, &pgErr) || pgErr.Code != "40001" || attempt == maxAttempts {
return err
}
backoff := time.Duration(attempt*attempt) * 20 * time.Millisecond
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoff):
}
}
}
func main() {
ctx := context.Background()
// e.g. postgresql://app@crdb-lb:26257/shop?sslmode=verify-full
// Any node (or a load balancer in front of them) accepts the connection.
conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer conn.Close(ctx)
if err := Pay(ctx, conn, 42, 7, 1500); err != nil {
log.Fatal(err)
}
}The Go angle. database/sql has no concept of a distributed transaction: a *sql.Tx belongs to one connection of one pool, so atomicity across two *sql.DB values cannot be expressed with it. Implementing 2PC in Go has three practical consequences. You pin a session with db.Conn and issue BEGIN yourself, because after PREPARE TRANSACTION the session has no open transaction and Tx.Commit would have nothing to commit. The gid must be a string literal, not a bind parameter, so validate it before building the SQL. And COMMIT PREPARED cannot run inside a transaction block, so it runs on the pool. On the distributed SQL side, pgx reports server errors as *pgconn.PgError and you match Code == "40001"; pgx.BeginFunc returns the commit error too, which matters because CockroachDB can reject at COMMIT. CockroachDB's docs point Go users to github.com/cockroachdb/cockroach-go/v2/crdb/crdbpgxv5 (crdbpgxv5.ExecuteTx), which wraps the same loop.
Before (Laravel): nested transaction() calls on two connections look atomic and are not; each connection has its own PDO session and the inner one commits first.
<?php
// app/Services/PaymentService.php — two connections, two separate transactions.
namespace App\Services;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
final class PaymentService
{
public function pay(int $customerId, int $invoiceId, int $cents): void
{
// The nesting reads as one unit of work, but 'wallets' and 'billing'
// are separate PDO sessions with separate transaction counters.
// The inner closure commits billing as soon as it returns. If the
// outer commit on wallets then fails, or the worker is killed in
// between, the invoice is paid and the wallet was never debited.
// No Laravel API can undo a commit that already happened elsewhere.
DB::connection('wallets')->transaction(function (Connection $wallets) use ($customerId, $invoiceId, $cents) {
$wallets->table('wallets')
->where('customer_id', $customerId)
->decrement('balance_cents', $cents);
DB::connection('billing')->transaction(function (Connection $billing) use ($invoiceId, $cents) {
$billing->table('invoices')
->where('id', $invoiceId)
->increment('paid_cents', $cents);
});
});
}
}After (Laravel): one CockroachDB transaction. CockroachDB is reached through the stock pgsql driver (port 26257, sslmode and sslrootcert passed into the DSN), and both writes go into one DB::transaction with attempts: 5.
<?php
// config/database.php — CockroachDB speaks the PostgreSQL wire protocol, so
// the stock pgsql driver connects to it. Point the host at a load balancer
// in front of the nodes; any node can serve any statement.
//
// 'cockroach' => [
// 'driver' => 'pgsql',
// 'host' => env('CRDB_HOST', 'crdb-lb.internal'),
// 'port' => env('CRDB_PORT', '26257'), // CockroachDB's default SQL port
// 'database' => env('CRDB_DATABASE', 'shop'),
// 'username' => env('CRDB_USERNAME', 'app'),
// 'password' => env('CRDB_PASSWORD', ''),
// 'charset' => 'utf8',
// 'prefix' => '',
// 'search_path' => 'public',
// 'sslmode' => 'verify-full',
// 'sslrootcert' => env('CRDB_CA_CERT'), // passed into the PDO DSN
// ],
// app/Services/PaymentService.php — one logical database, one transaction.
namespace App\Services;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
final class PaymentService
{
public function pay(int $customerId, int $invoiceId, int $cents): void
{
// Under SERIALIZABLE, CockroachDB's default, a conflict is reported
// as SQLSTATE 40001 ("restart transaction"). Laravel's
// ConcurrencyErrorDetector treats a PDOException with code 40001 as
// retryable, and QueryException extends PDOException and keeps the
// SQLSTATE, so `attempts: 5` reruns the closure, including when the
// error is raised by COMMIT. Retrying only happens on the outermost
// transaction; inside a nested one Laravel throws DeadlockException.
// The closure may run up to five times: no emails or HTTP calls here.
DB::connection('cockroach')->transaction(function (Connection $db) use ($customerId, $invoiceId, $cents) {
$db->table('wallets')
->where('customer_id', $customerId)
->decrement('balance_cents', $cents);
$db->table('invoices')
->where('id', $invoiceId)
->increment('paid_cents', $cents);
}, attempts: 5);
}
}Alternative (Laravel): an outbox. If wallets and billing must remain separate databases, commit the debit together with a message and let billing consume it idempotently. Relay strategies and consumer dedup are in Transactional Outbox and Idempotent Consumers.
<?php
// app/Services/PaymentService.php — no distributed transaction at all. The
// debit and an "invoice was paid" message commit together in the wallets
// database; a relay worker delivers outbox rows to billing afterwards, at
// least once, so billing must apply them idempotently (keyed by id).
namespace App\Services;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
final class PaymentService
{
public function pay(int $customerId, int $invoiceId, int $cents): void
{
DB::connection('wallets')->transaction(function (Connection $db) use ($customerId, $invoiceId, $cents) {
$db->table('wallets')->where('customer_id', $customerId)->decrement('balance_cents', $cents);
$db->table('outbox')->insert([
'id' => (string) Str::uuid7(),
'topic' => 'invoice.paid',
'payload' => json_encode(['invoice_id' => $invoiceId, 'cents' => $cents]),
'created_at' => now(),
]);
});
}
}The Laravel angle. DB::connection('name') gives each connection its own transaction counter, and Laravel has no API that spans connections and no two-phase commit. The documented retry is the second argument of transaction, "the number of times a transaction should be retried when a deadlock occurs". The framework source is broader than the docs: ConcurrencyErrorDetector returns true for any PDOException whose code is 40001, QueryException extends PDOException and keeps the SQLSTATE, and handleCommitTransactionException applies the same check, so a CockroachDB 40001 raised at COMMIT is retried too. Two traps remain: retries happen with no delay, and inside a nested transaction Laravel throws DeadlockException instead of retrying, so put attempts: on the outermost call. Laravel's documentation does not list CockroachDB as a supported database; it works because CockroachDB speaks the PostgreSQL wire protocol.
Orphaned prepared transactions
A coordinator crashed between PREPARE TRANSACTION and COMMIT PREPARED. Symptoms: lock waits on rows nobody is touching, VACUUM not removing dead rows, age(datfrozenxid) growing.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Automated recovery from the decision log | Job reads pg_prepared_xacts, looks up the decision, commits or rolls back | Correct and hands-off | Needs the decision log to be durable and reachable |
| Alert on age | now() - prepared > interval '1 minute' | Catches bugs in the coordinator | Only detects |
| Manual resolution | Operator checks every participant and the log, then runs COMMIT/ROLLBACK PREPARED | Works when tooling is broken | Must be consistent across all participants: never roll back on one and commit on another |
| Keep 2PC disabled | max_prepared_transactions = 0 everywhere it is not used | Prevents accidental prepares | None |
-- Find every prepared transaction, oldest first.
SELECT gid, prepared, now() - prepared AS age, owner, database
FROM pg_prepared_xacts
ORDER BY prepared;
-- Locks held by prepared transactions have no backend: pid is null.
SELECT locktype, relation::regclass, mode FROM pg_locks WHERE pid IS NULL;
-- Decide from the coordinator's log (never guess), then on EVERY participant:
COMMIT PREPARED 'twopc-pay-17'; -- if twopc_decisions says 'commit'
ROLLBACK PREPARED 'twopc-pay-17'; -- if it says 'abort' or nothing, after the grace periodGo: Coordinator.Recover(ctx, grace) in the snippet above does exactly this and runs at start-up and on a timer. Laravel: a scheduled Artisan command with the same rules.
<?php
// app/Console/Commands/RecoverPreparedTransactions.php
//
// Finishes orphaned PostgreSQL prepared transactions that a crashed
// coordinator left behind. Schedule it every minute:
//
// Schedule::command('twopc:recover')->everyMinute()->withoutOverlapping();
//
// The decision log ('twopc_decisions', see the Go coordinator) is the only
// source of truth: commit if a commit decision exists, otherwise record an
// abort once the prepare is older than the grace period, then roll back.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class RecoverPreparedTransactions extends Command
{
protected $signature = 'twopc:recover {--grace=60 : seconds before an undecided prepare is aborted}';
protected $description = 'Commit or roll back orphaned prepared transactions';
/** @var list<string> participant connection names from config/database.php */
private const PARTICIPANTS = ['wallets', 'billing'];
public function handle(): int
{
$grace = (int) $this->option('grace');
foreach (self::PARTICIPANTS as $name) {
$rows = DB::connection($name)->select(
"SELECT gid, extract(epoch FROM now() - prepared) AS age
FROM pg_prepared_xacts
WHERE database = current_database() AND starts_with(gid, 'twopc-')"
);
foreach ($rows as $row) {
// PREPARE/COMMIT PREPARED take a literal, never a binding.
if (preg_match('/^twopc-[a-z0-9-]{1,64}$/', $row->gid) !== 1) {
$this->warn("skipping unexpected gid {$row->gid}");
continue;
}
$outcome = DB::connection('coordinator')
->table('twopc_decisions')
->where('gid', $row->gid)
->value('outcome');
if ($outcome === null) {
if ($row->age < $grace) {
continue; // still in flight
}
// First decision wins; a racing commit decision is kept.
DB::connection('coordinator')->table('twopc_decisions')
->insertOrIgnore(['gid' => $row->gid, 'outcome' => 'abort']);
$outcome = DB::connection('coordinator')->table('twopc_decisions')
->where('gid', $row->gid)->value('outcome');
}
$sql = $outcome === 'commit'
? "COMMIT PREPARED '{$row->gid}'"
: "ROLLBACK PREPARED '{$row->gid}'";
// Runs outside any transaction block, as PostgreSQL requires.
DB::connection($name)->unprepared($sql);
$this->info("{$name}: {$sql}");
}
}
return self::SUCCESS;
}
}Low-latency reads in a multi-region cluster
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Follower reads, exact staleness | AS OF SYSTEM TIME follower_read_timestamp() | Local read, no cross-region RTT | Seconds stale; read-only |
| Bounded staleness | AS OF SYSTEM TIME with_max_staleness('10s') | Freshest locally available data | Single-statement reads only |
| GLOBAL tables | ALTER TABLE ... SET LOCALITY GLOBAL | Strong, local reads everywhere | Slower writes |
| REGIONAL BY ROW | crdb_region column homes each row | Local reads and writes for each region's own rows | Cross-region reads of other rows pay RTT |
-- CockroachDB: a catalogue page read from the nearest replica
SELECT id, name, price_cents
FROM products AS OF SYSTEM TIME follower_read_timestamp()
WHERE category_id = 12;
-- or for a whole session of read-only work
SET default_transaction_use_follower_reads = on;// Go (pgx): stale-but-local read; use only for data that tolerates seconds of staleness.
rows, err := pool.Query(ctx, `SELECT id, name, price_cents
FROM products AS OF SYSTEM TIME follower_read_timestamp()
WHERE category_id = $1`, categoryID)// Laravel: a raw select on the CockroachDB connection.
$products = DB::connection('cockroach')->select(
'SELECT id, name, price_cents FROM products AS OF SYSTEM TIME follower_read_timestamp() WHERE category_id = ?',
[$categoryId],
);Placing data for multi-region writes
-- CockroachDB multi-region: regions come from each node's --locality=region=...
ALTER DATABASE shop SET PRIMARY REGION "us-east1";
ALTER DATABASE shop ADD REGION "europe-west1";
ALTER DATABASE shop ADD REGION "asia-southeast1";
ALTER DATABASE shop SURVIVE REGION FAILURE; -- default is ZONE FAILURE
ALTER TABLE orders SET LOCALITY REGIONAL BY ROW; -- each row lives where it was written
ALTER TABLE currencies SET LOCALITY GLOBAL; -- read everywhere, written rarely
SHOW RANGES FROM TABLE orders; -- where are the replicas and leaseholders?| Goal | Placement | Write latency | Survives |
|---|---|---|---|
| Lowest latency, one region | 3 replicas in 3 zones of one region (SURVIVE ZONE FAILURE) | ~1–3 ms | One zone |
| Survive a region | Voters in ≥ 3 regions (SURVIVE REGION FAILURE, 5 replicas) | ≥ RTT to nearest other region | One region |
| Local writes per user region | REGIONAL BY ROW + zone survival | Local for home-region rows | One zone per region |
| Global reference data | GLOBAL table | Slow (future-timestamp writes) | Configured goal |
Leader election and fencing in your own services
A job must run on exactly one worker (billing run, cache warm-up, outbox relay). Elect a leader with a consensus-backed store and fence every write with a token.
-- The database is the fence: a write carries the token; stale tokens change nothing.
CREATE TABLE job_fence (job text PRIMARY KEY, token bigint NOT NULL);
INSERT INTO job_fence VALUES ('monthly-invoices', 0);
-- the new leader claims the next token (atomic, so two claimants get different tokens)
UPDATE job_fence SET token = token + 1 WHERE job = 'monthly-invoices' RETURNING token;
-- every side-effecting write re-checks the token under FOR SHARE in the same statement:
-- a claim in progress makes it wait, a committed claim makes the check fail (0 rows),
-- and a later claim waits until this write commits.
WITH fence AS (
SELECT 1 FROM job_fence WHERE job = 'monthly-invoices' AND token = $2 FOR SHARE
)
UPDATE invoices SET sent_at = now()
WHERE id = $1 AND EXISTS (SELECT 1 FROM fence);// Go: claim a token, then pass it to every write; zero rows affected means you were deposed.
var token int64
if err := db.QueryRowContext(ctx,
`UPDATE job_fence SET token = token + 1 WHERE job = $1 RETURNING token`, job).Scan(&token); err != nil {
return err
}
res, err := db.ExecContext(ctx, `WITH fence AS (
SELECT 1 FROM job_fence WHERE job = $2 AND token = $3 FOR SHARE)
UPDATE invoices SET sent_at = now() WHERE id = $1 AND EXISTS (SELECT 1 FROM fence)`,
invoiceID, job, token)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return errors.New("fenced: a newer leader holds the job")
}// Laravel: Cache::lock gives mutual exclusion while it holds, but no fencing token;
// combine it with the database token so a paused worker cannot write after losing the lock.
Cache::lock('monthly-invoices', 600)->get(function () use ($invoiceId) {
$token = DB::selectOne(
"UPDATE job_fence SET token = token + 1 WHERE job = 'monthly-invoices' RETURNING token"
)->token;
$updated = DB::update(
"WITH fence AS (
SELECT 1 FROM job_fence WHERE job = 'monthly-invoices' AND token = ? FOR SHARE)
UPDATE invoices SET sent_at = now() WHERE id = ? AND EXISTS (SELECT 1 FROM fence)",
[$token, $invoiceId],
);
if ($updated === 0) {
throw new \RuntimeException('fenced: a newer leader holds the job');
}
});Retries and failure handling
In a distributed SQL database a transaction retry is not an exception path; it is part of the protocol. CockroachDB: "All transaction retry errors use the SQLSTATE error code 40001, and emit error messages with the string restart transaction", and under SERIALIZABLE the application must handle them client-side.
| Error | Where it comes from | Retry? | Note |
|---|---|---|---|
40001 at any statement | CockroachDB, YugabyteDB, PostgreSQL Serializable | Yes | Whole transaction, from BEGIN |
40001 at COMMIT | CockroachDB (refresh failed), PostgreSQL SSI | Yes | pgx.BeginFunc and Laravel's commit handler both surface it |
40003 ambiguous result | CockroachDB, connection lost during commit | Only if idempotent | The transaction may or may not have committed |
| Connection refused / reset | Node died, leaseholder moving | Yes, on a new connection | Use a load balancer or multi-host DSN |
23505 unique violation | Any | No | The constraint answered |
ROLLBACK PREPARED / COMMIT PREPARED failure | PostgreSQL | Recovery job retries | Never resolve one participant differently from the others |
Rules.
- Retry the whole transaction function, never a single statement; after
40001the transaction is dead. - The function must have no side effects outside the database (emails, HTTP calls, queue publishes): put them in an outbox row or
DB::afterCommit. - Bound attempts (5–10) and back off with jitter; CockroachDB contention resolves faster when retries do not collide again.
- Make writes idempotent where a commit can be ambiguous (
40003, timeouts): an idempotency key in a unique column turns a duplicate into23505. - Reduce retries at the source: keep transactions short, avoid hot rows (sharded counters), use
SELECT ... FOR UPDATEin CockroachDB to take the lock early, and consider READ COMMITTED for code ported from PostgreSQL. - Measure: export retry counts per endpoint; CockroachDB's DB Console shows transaction restarts by reason.
Go. The runTx loop in the CockroachDB snippet retries on 40001 with quadratic backoff and honours context cancellation; for production use crdbpgxv5.ExecuteTx, which also handles CockroachDB's savepoint-based retry protocol. Laravel. DB::connection('cockroach')->transaction($fn, attempts: 5) retries 40001 immediately, only at the outermost level; for backoff, wrap it in Laravel's retry() helper with a when: callback, or use the runner from Isolation Levels.
// Laravel: backoff between attempts, retrying only on SQLSTATE 40001.
use Illuminate\Database\QueryException;
retry(5, fn () => DB::connection('cockroach')->transaction(function ($db) use ($from, $to, $cents) {
$db->table('accounts')->where('id', $from)->decrement('balance_cents', $cents);
$db->table('accounts')->where('id', $to)->increment('balance_cents', $cents);
}), fn (int $attempt) => random_int(10, 50) * $attempt ** 2, fn ($e) => $e instanceof QueryException && (string) $e->getCode() === '40001');Choosing
When single-node PostgreSQL plus replicas is enough. Most systems never need consensus in the data path. One PostgreSQL primary on a large machine handles tens of thousands of write transactions per second; streaming replicas take reads; Patroni (which itself uses etcd, Consul or ZooKeeper for leader election) automates failover; synchronous replication to one standby gives zero data loss on failover at the cost of one in-region RTT per commit. Move to distributed SQL when one of these is true: writes or data outgrow one primary even after partitioning; the business requires surviving a zone or region with no manual step and no lost commits; or data must live in specific regions while being queried as one database.
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Single-region app, < one big machine of writes | PostgreSQL primary + replicas | Patroni with fencing; sync standby if RPO must be 0 | Lowest latency, full feature set |
| Must survive a zone with zero data loss, automatic failover | PostgreSQL with synchronous standby, or CockroachDB/YugabyteDB in 3 zones | Test failover; read-your-writes routing | Both work; distributed SQL removes the failover tooling |
| Must survive a region failure | Distributed SQL with voters in ≥ 3 regions | Leaseholders near writers; follower reads | Quorum across regions is the only way to lose nothing |
| Writes outgrow one primary | Partition first; then Citus or distributed SQL | Shard key that keeps invariants local | See Partitioning & Sharding |
| Data residency (EU rows stay in EU) | CockroachDB REGIONAL BY ROW or per-region databases | Region column in the primary key | Placement per row |
| Two services, two databases, one action | Outbox + idempotent consumer, saga for multi-step | Reconciliation job | 2PC couples availability of both and holds locks across services |
| Legacy XA between a database and a broker | Keep, but monitor pg_prepared_xacts / XA RECOVER | Recovery job, alerts on age | Removing it may be a larger project |
| Leader election / locks for your own workers | etcd or ZooKeeper (or a database row) with fencing tokens | CheckQuorum + pre-vote in etcd | A Redis TTL lock alone has no fencing |
| Globally consistent reads after writes across regions | Spanner (external consistency) or CockroachDB with care | Accept write latency | Strict serializability across regions costs RTT or clock waits |
| Hot single row (global counter) | Not distributed SQL's strength | Sharded counters, batching | All writes to one range go through one leader |
| Mostly reads, tolerate seconds of staleness | Any, with follower reads / replicas | Bounded staleness | Avoid cross-region reads |
In architecture: from a single process to a distributed system
Atomic commit and consensus are what make "one database" possible when the database is many machines. Above that line, in your services, you choose between borrowing the database's guarantees (keep the data together) and designing without them (outbox, saga, idempotency).
Monolith: one process, one database
How it shows up: it does not, and that is the point. One PostgreSQL commit is atomic without 2PC; replication happens below you.
Simplest correct usage: keep data that must change together in one database; use atomic updates and constraints; add replicas for reads with read-your-writes routing.
Example (simple): a shop's checkout decrements stock and inserts the order in one transaction on one primary.
Example (complex): the same shop adds a hot standby with synchronous_commit = on and Patroni backed by a 3-member etcd. etcd's Raft decides who is primary; the database itself stays single-leader. The only consensus in the system is in the failover control plane, and it is the reason a partitioned old primary is demoted instead of accepting orders (split-brain prevention).
Modular monolith and multiple databases
How it shows up: modules own their tables. While they share one database, one transaction still covers them. The day a module moves to its own database, a cross-module transaction becomes a distributed transaction.
Example: Wallets and Billing split into two PostgreSQL databases. Options: keep a cross-database transaction with PREPARE TRANSACTION (this page's Go coordinator); or, better, keep each invariant within one module and publish invoice.paid through an outbox. The rule: never let a module read another module's database inside its transaction and assume atomicity.
Microservices: sagas and outbox instead of 2PC
What survives: each service's local transaction. What does not: atomicity across services. 2PC between services is rejected in practice because it couples availability (every participant must be up to commit), holds locks across network calls, and needs every datastore and broker to speak XA.
Order service Payment service Inventory service
1 BEGIN; INSERT order(PENDING); INSERT outbox(OrderPlaced); COMMIT
2 consume OrderPlaced (dedup by message id)
BEGIN; charge; INSERT outbox(PaymentCaptured); COMMIT
3 consume PaymentCaptured
UPDATE stock ... WHERE stock >= qty -> 0 rows
outbox(StockUnavailable)
4 consume -> refund (compensation), outbox(PaymentRefunded)
5 consume -> UPDATE order SET status = 'CANCELLED'Each arrow is at-least-once, so each consumer is idempotent; each step is a local ACID transaction; the saga gives atomicity eventually through compensation, without isolation. See Saga Pattern, Transactional Outbox and Idempotent Consumers.
Distributed data: replicas, sharding and distributed SQL
Replicas. Asynchronous PostgreSQL/MySQL replicas can lose the last commits on failover and need fencing against split brain; synchronous replicas trade one RTT per commit for zero loss. Neither is consensus: the failover decision is made by external tooling. Details in Replication & Failover.
Hand-built sharding. Shards are independent databases; a cross-shard transaction is 2PC (Citus uses PREPARE TRANSACTION internally for multi-shard writes) or a saga. Choose shard keys so invariants stay on one shard.
Distributed SQL. Each range is a consensus group; cross-range transactions use a replicated commit protocol; clocks (TrueTime, HLC, PD) order transactions. The design levers are placement (leaseholders near writers, voters across failure domains), isolation (Serializable + retries, or Read Committed), and read freshness (strong vs follower reads).
Example (multi-region shop): CockroachDB with regions us-east1, europe-west1, asia-southeast1, SURVIVE REGION FAILURE; orders is REGIONAL BY ROW so an EU customer's order commits with EU-local leaseholders and pays the RTT to the nearest other region for the quorum; currencies is GLOBAL; the product catalogue is read with follower reads; payments go through crdbpgxv5.ExecuteTx.
Scaling path: 1×, 10×, 100×
| Load | What changes | Consensus / commit consequence |
|---|---|---|
| 1× (one primary) | Single PostgreSQL, replicas for reads, Patroni + etcd | Consensus only in the failover control plane; no 2PC |
| 10× (bigger data, stricter availability) | Sync standby, partitioning; maybe split services with outbox/saga | Commit pays an in-region RTT; cross-service atomicity becomes eventual |
| 100× (many regions, write scale-out) | Distributed SQL or Citus; per-region placement | Every write pays a quorum RTT; 40001 retries and follower reads become everyday tools; clock sync (--max-offset) is an SLO |
Lab
Two experiments. Commands follow the CockroachDB "Deploy a Local Cluster in Docker (Insecure)", SHOW RANGES and cockroach sql pages and the PostgreSQL manual. The comments give the output you should expect from the documented behaviour; they were not captured from a run, so exact values, timings and error wording will differ.
Lab A: a 3-node CockroachDB cluster, kill the leader, observe
Setup.
docker network create -d bridge roachnet
docker volume create roach1; docker volume create roach2; docker volume create roach3
for i in 1 2 3; do
docker run -d --name=roach$i --hostname=roach$i --net=roachnet \
-p $((26256+i)):$((26256+i)) -p $((8079+i)):$((8079+i)) \
-v "roach$i:/cockroach/cockroach-data" \
cockroachdb/cockroach:latest start \
--advertise-addr=roach$i:26357 --listen-addr=roach$i:26357 \
--sql-addr=roach$i:$((26256+i)) --http-addr=roach$i:$((8079+i)) \
--insecure --join=roach1:26357,roach2:26357,roach3:26357
done
docker exec -it roach1 ./cockroach --host=roach1:26357 init --insecure
# Cluster successfully initialized
# pin a real version instead of :latest for repeatable results (the docs use {TAG})Experiment 1: one table, three replicas.
-- terminal A: docker exec -it roach1 ./cockroach sql --host=roach1:26257 --insecure
CREATE DATABASE lab;
CREATE TABLE lab.accounts (id INT PRIMARY KEY, balance_cents INT NOT NULL);
INSERT INTO lab.accounts SELECT i, 10000 FROM generate_series(1, 1000) AS g(i);
SHOW RANGES FROM TABLE lab.accounts WITH DETAILS;
-- one or more ranges; columns include lease_holder and replicas = {1,2,3}
SELECT range_id, lease_holder, replicas FROM [SHOW RANGES FROM TABLE lab.accounts WITH DETAILS];
-- note the lease_holder node id, e.g. 2Experiment 2: kill the leaseholder (Raft leader) and keep writing.
# terminal B: write in a loop through a node you will NOT kill (say roach1 if the leaseholder is 2)
docker exec -it roach1 ./cockroach sql --host=roach1:26257 --insecure -e \
"UPDATE lab.accounts SET balance_cents = balance_cents + 1 WHERE id = 1;" --watch 200ms
# terminal C:
docker stop roach2 # the leaseholder from experiment 1 terminal B (writes every 200 ms) terminal C
1 UPDATE 1, UPDATE 1, ...
2 docker stop roach2
3 a few updates stall (several seconds): the lease and Raft leadership move
4 UPDATE 1, UPDATE 1, ... -- 2 of 3 replicas = quorum, writes continue
5 SHOW RANGES ... lease_holder is now 1 or 3; the range is under-replicatedExperiment 3: lose quorum.
docker stop roach3 # now only roach1 is up: 1 of 3
# terminal B: the UPDATE hangs; reads of the range hang too (no leaseholder can be established)
docker start roach2 roach3 # quorum returns; the stalled statement completes; nothing was lostExperiment 4: watch a 40001.
-- terminal A -- terminal B
BEGIN; BEGIN;
SELECT balance_cents FROM lab.accounts WHERE id = 2;
UPDATE lab.accounts SET balance_cents = 0 WHERE id = 2;
COMMIT;
UPDATE lab.accounts SET balance_cents = balance_cents - 100 WHERE id = 2;
COMMIT;
-- ERROR: restart transaction: TransactionRetryWithProtoRefreshError: ... (SQLSTATE 40001)
-- (the exact reason, e.g. RETRY_SERIALIZABLE or RETRY_WRITE_TOO_OLD, depends on timing)Repeat experiment 4 after SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED; in both terminals: terminal A's UPDATE waits for B and then applies to the new value, with no client-visible 40001.
Clean up: docker rm -f roach1 roach2 roach3; docker volume rm roach1 roach2 roach3; docker network rm roachnet.
Lab B: PostgreSQL 2PC and orphan recovery with pg_prepared_xacts
Setup. Two PostgreSQL servers, because a gid must be unique across a whole server, not per database: one for wallets (which also holds the coordinator's decision log) and one for billing.
docker run -d --name pgw -e POSTGRES_PASSWORD=pg -p 5433:5432 postgres:17 -c max_prepared_transactions=10
docker run -d --name pgb -e POSTGRES_PASSWORD=pg -p 5434:5432 postgres:17 -c max_prepared_transactions=10
# terminal A: docker exec -it pgw psql -U postgres
# terminal B: docker exec -it pgb psql -U postgres-- terminal A (wallets server)
CREATE TABLE wallets (customer_id int PRIMARY KEY, balance_cents int NOT NULL);
INSERT INTO wallets VALUES (42, 10000);
CREATE TABLE twopc_decisions (gid text PRIMARY KEY, outcome text NOT NULL CHECK (outcome IN ('commit','abort')),
decided_at timestamptz NOT NULL DEFAULT now());
-- terminal B (billing server)
CREATE TABLE invoices (id int PRIMARY KEY, paid_cents int NOT NULL DEFAULT 0);
INSERT INTO invoices VALUES (7, 0);Experiment 1: prepare on both, "crash" the coordinator.
-- terminal A (wallets) -- terminal B (billing)
BEGIN; BEGIN;
UPDATE wallets SET balance_cents = balance_cents - 1500 WHERE customer_id = 42;
UPDATE invoices SET paid_cents = paid_cents + 1500 WHERE id = 7;
PREPARE TRANSACTION 'twopc-pay-17'; PREPARE TRANSACTION 'twopc-pay-17';
-- PREPARE TRANSACTION -- PREPARE TRANSACTION
-- the "coordinator" now dies: no decision row is written, nobody commitsA second PREPARE TRANSACTION 'twopc-pay-17' on the same server would fail with "transaction identifier ... is already in use".
Experiment 2: observe the orphan and its locks.
-- terminal B (billing)
SELECT gid, prepared, owner, database FROM pg_prepared_xacts;
-- gid | prepared | owner | database
-- twopc-pay-17 | 2026-11-25 10:00:03.40+00 | postgres | postgres
SELECT locktype, relation::regclass, mode FROM pg_locks WHERE pid IS NULL;
-- the prepared transaction's locks, including RowExclusiveLock on invoices
SET lock_timeout = '2s';
UPDATE invoices SET paid_cents = paid_cents + 1 WHERE id = 7;
-- ERROR: canceling statement due to lock timeout -- the prepared transaction still holds the row lock
SELECT paid_cents FROM invoices WHERE id = 7;
-- 0 -- the prepared change is invisible until COMMIT PREPAREDExperiment 3: recover by the presumed-abort rule. No decision row exists and the prepare is older than the grace period, so the recovery job records an abort and rolls back on every participant.
-- terminal A (wallets server, holds the decision log)
INSERT INTO twopc_decisions (gid, outcome) VALUES ('twopc-pay-17', 'abort') ON CONFLICT (gid) DO NOTHING;
ROLLBACK PREPARED 'twopc-pay-17';
-- terminal B (billing server)
ROLLBACK PREPARED 'twopc-pay-17';
SELECT count(*) FROM pg_prepared_xacts; -- 0
SELECT paid_cents FROM invoices WHERE id = 7; -- 0, consistent with the wallet (10000)Experiment 4: the happy path and the session rules. Repeat experiment 1 with gid 'twopc-pay-18', insert ('twopc-pay-18', 'commit') into twopc_decisions in terminal A, then run COMMIT PREPARED 'twopc-pay-18' on both servers from new sessions (any session of the same user may finish it). Try BEGIN; COMMIT PREPARED 'twopc-pay-18'; and see it rejected inside a transaction block. Start a third container without the -c flag and try PREPARE TRANSACTION: "prepared transactions are disabled".
Experiment 5: run the Go Recover. Point the coordinator's Log at the wallets server and its Participants at both servers, leave a prepare orphaned, and call Recover(ctx, 10*time.Second): after ten seconds it writes abort and rolls back both, exactly like experiment 3. The Laravel php artisan twopc:recover --grace=10 command does the same.
Clean up: docker rm -f pgw pgb.
Common misconceptions
| Belief | Reality |
|---|---|
| "Two-phase commit makes the system fault tolerant." | It makes the commit atomic and the system less available: a coordinator failure after the votes blocks every participant with its locks held. |
| "A prepared participant can just time out and abort." | Only before voting. After voting YES it must wait for the decision, or it can break atomicity. |
| "3PC fixed 2PC, so modern systems use it." | 3PC is unsafe under network partitions; production systems replicate the coordinator with Paxos/Raft instead. |
"PREPARE TRANSACTION is for application code." | The manual: "Unless you're writing a transaction manager, you probably shouldn't be using PREPARE TRANSACTION." It is off by default. |
| "Consensus means every replica has the latest data." | A majority has it; followers lag. Fresh reads need a read index, a lease, or the leader. |
| "Four or six nodes are safer than three or five." | Even sizes add a quorum member without adding fault tolerance. Use 3 or 5 voters. |
| "The leader is always fresh, so leader reads are linearizable." | A deposed leader that has not noticed serves stale data; Raft requires a heartbeat round or a lease. |
| "Leases are free." | They rely on bounded clock offset; a frozen VM clock breaks them. That is why CockroachDB enforces --max-offset. |
| "Spanner's clocks are perfect, so there is no waiting." | TrueTime has bounded uncertainty ε and Spanner waits it out: commit wait ≈ 2ε. |
| "Distributed SQL is a faster PostgreSQL." | Every write pays a quorum RTT; it scales out and survives failures, it is not faster per transaction. |
| "Connecting to the nearest node gives local latency." | The gateway forwards to each range's leaseholder; latency follows leaseholder placement. |
| "Commit latency is set by the slowest replica." | It is set by the replica that completes the quorum (the nearest one of three, the second-nearest of five) plus the client-to-leader hop. |
| "A Redis lock with a TTL prevents two leaders." | A paused process can write after its lease expired; only a fencing token checked by the storage prevents it. |
| "TiDB transactions fail at commit because they are optimistic." | New TiDB clusters default to pessimistic mode (since v3.0.8); optimistic mode is opt-in. |
"CockroachDB always forces me to handle 40001." | Under SERIALIZABLE, yes. Under READ COMMITTED it does not return serialization errors that need client-side handling. |
Cheat sheet
| Topic | What to remember |
|---|---|
| 2PC | Prepare (vote, fsync, keep locks) then decide (TM fsyncs decision = commit point); blocks if TM dies after votes |
| Presumed abort | No record means abort; saves log writes; still blocking |
| 3PC | Extra PreCommit round; non-blocking only without partitions; not used in practice |
| XA / PostgreSQL | PREPARE TRANSACTION 'gid' (literal, < 200 bytes, unique per server), COMMIT/ROLLBACK PREPARED from any session, pg_prepared_xacts, max_prepared_transactions = 0 by default |
| XA / MySQL | XA START/END/PREPARE/COMMIT/ROLLBACK, XA RECOVER (needs XA_RECOVER_ADMIN) |
| Quorum | ⌊n/2⌋+1; tolerates ⌊(n−1)/2⌋ failures; odd sizes; learners/non-voting replicas do not count |
| Paxos | Prepare/promise (ballot), accept/accepted; reuse the highest accepted value; leader only for liveness |
| Multi-Paxos / Raft | One RTT per write with a stable leader; Raft adds terms, election restriction, log matching |
| Raft commit | Entry committed when on a majority and from the current term (older ones commit indirectly) |
| Membership | Joint consensus Cold,new; add as learner first; remove dead members before adding |
| Reads | Log read < read index (heartbeat round) < lease read (clock assumption) < follower read (stale) |
| Split brain | Prevented inside consensus by terms; outside it only by fencing tokens or STONITH |
| Latency | client→leaseholder RTT + leader→quorum-completing follower RTT + fsync (+ commit wait on Spanner) |
| Spanner | TrueTime interval, s = TT.now().latest, commit wait until TT.after(s), external consistency |
| CockroachDB | Ranges × 3 replicas, leaseholder = Raft leader (Leader leases), HLC + --max-offset, Parallel Commits, SERIALIZABLE default, READ COMMITTED option, 40001 retries |
| TiDB | Regions × 3 peers, PD timestamps, Percolator primary key, pessimistic default |
| YugabyteDB | Tablets, Raft with leader leases and pre-vote, DocDB on RocksDB, YSQL + YCQL |
| Alternatives | One database if possible; otherwise outbox + idempotent consumers + sagas |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A coordinator crashes after both participants voted YES. Why can't a participant simply abort after a timeout? Important
Answer
Answer: Because the coordinator may already have written COMMIT and told the other participant, which committed. Aborting would make one side commit and the other abort. A prepared participant must wait for the decision. See Coordinator failure and blocking.
2 — What does presumed abort save, and what does it not fix? Good to know
Answer
Answer: It saves forced abort records and abort acknowledgements, and lets the coordinator forget aborted transactions: no record means abort. It does not make 2PC non-blocking. See Presumed abort.
3 — Why do production systems not use 3PC? Important
Answer
Answer: 3PC avoids blocking only if message delays are bounded and the network never partitions; with a partition, the two sides can decide differently. Replicating the coordinator with consensus (Paxos Commit, Spanner, CockroachDB) is safe under partitions. See 3PC.
4 — You find a row in pg_prepared_xacts that is three days old. What do you do? Important
Answer
Answer: Look up the gid in the coordinator's decision log. If it says commit, run COMMIT PREPARED on every participant that still has it; if it says abort or nothing, run ROLLBACK PREPARED on every participant. Never decide differently on different participants. Then find why recovery did not run, and set max_prepared_transactions = 0 where 2PC is not used. See Orphaned prepared transactions.
5 — Why is a 4-node Raft cluster no better than 3 nodes? Must-know
Answer
Answer: The quorum of 4 is 3, so it tolerates one failure, exactly like 3 nodes, while needing one more acknowledgement per write. See Quorum.
6 — In Paxos, a proposer learns in phase 1 that one acceptor has already accepted (ballot 4, value 9). It wants to propose 5. What must it propose, and why? Good to know
Answer
Answer: 9, the value of the highest-numbered accepted proposal it learned about, because 9 may already have been chosen by a majority; proposing 5 could choose a second value. See Paxos.
7 — A Raft leader serves a read from its local state without any check. How can that read be stale, and what are the two fixes? Must-know
Answer
Answer: It may have been deposed by a newer leader it has not heard of. Fixes: confirm leadership with a heartbeat round to a majority before reading (read index), or rely on a leader lease, which assumes bounded clock offset. See Linearizable reads.
8 — Three replicas in regions A, B, C with RTT A–B 10 ms and A–C 70 ms; the leaseholder is in A. Roughly what does a write from a client in A cost, and why not 70 ms? Important
Answer
Answer: About 11–12 ms: the quorum is the leader plus one follower, and the nearest follower (B, 10 ms) completes it, plus fsync and the local client hop. C's 70 ms is not on the commit path. See Write latency = RTT math.
9 — What does Spanner's commit wait guarantee, and how long is it? Good to know
Answer
Answer: That the write becomes visible only after its timestamp s is definitely in the past, so any transaction that starts afterwards gets a larger timestamp (external consistency). The expected wait is at least 2ε, a few milliseconds, overlapped with Paxos replication. See TrueTime.
10 — A worker holding a Redis lock pauses for 20 s, the lock expires, another worker takes over, and then the first wakes up and writes. What prevents corruption? Must-know
Answer
Answer: Only a fencing token: each lock holder gets a higher number and the storage rejects writes with a lower number than it has seen. A TTL lock alone cannot prevent it. See Split brain and fencing and the fencing solution.
11 — Your PostgreSQL primary with two replicas handles the load and you lose at most a few seconds of data on failover. When would you move to distributed SQL? Important
Answer
Answer: When writes or data outgrow one primary even after partitioning, when you must survive a zone or region failure with zero lost commits and no manual step, or when rows must be placed in specific regions while queried as one database. Otherwise stay. See Choosing.
12 — Two services own two databases and must both reflect a payment. Why is a saga with an outbox usually preferred to XA? Must-know
Answer
Answer: XA couples the availability of both services, holds locks across network calls, blocks on coordinator failure and needs XA support everywhere. An outbox commits the local change and the message atomically; idempotent consumers and compensations give eventual atomicity without distributed locks. See Microservices.
Glossary
| Term | Meaning |
|---|---|
| Atomic commit | All participants of one transaction commit or none do |
| Two-phase commit (2PC), 2PC phases | Prepare/vote phase, then a decision phase driven by a coordinator |
| Coordinator / transaction manager (TM) | The process that collects votes and decides |
| Participant / resource manager (RM) | A database or broker that prepares and then obeys the decision |
| Commit point | The moment the coordinator's decision is durable |
| Blocking (coordinator failure) | A prepared participant cannot decide while the coordinator is down |
| Presumed abort / presumed commit | 2PC optimisations: missing information means abort (or commit), saving log writes and messages |
| Three-phase commit (3PC) | 2PC plus a PreCommit round; non-blocking only without partitions |
| X/Open XA | Standard interface between a transaction manager and resource managers |
PREPARE TRANSACTION | PostgreSQL command that makes a transaction durable and detaches it from the session for 2PC |
COMMIT PREPARED / ROLLBACK PREPARED | Finish a prepared transaction from any session; not inside a transaction block |
pg_prepared_xacts | PostgreSQL view of prepared transactions: transaction, gid, prepared, owner, database |
max_prepared_transactions | PostgreSQL limit on prepared transactions; 0 (default) disables the feature |
XA RECOVER | MySQL statement listing XA transactions in the PREPARED state |
| Orphaned prepared transaction | A prepare whose coordinator never sent the decision; holds locks and the xmin horizon |
| Paxos Commit | Gray & Lamport's commit protocol with 2F+1 acceptors; 2PC is its F = 0 case |
| Consensus (the consensus problem) | Agreement on one value (or one log order) despite failures |
| FLP | Fischer–Lynch–Paterson: no deterministic asynchronous algorithm guarantees termination with one crash |
| Safety / liveness | Nothing bad happens (never two values) / something good eventually happens (a decision) |
| Replicated state machine | Replicas apply the same log in the same order and reach the same state |
| Quorum | A set of voters large enough that any two such sets intersect; usually a majority |
| Proposers / acceptors / learners | Paxos roles: suggests values, votes on them, learns the chosen one |
| Ballots (proposal numbers) | Paxos round number; higher ballots pre-empt lower ones |
| Multi-Paxos | Paxos for a log with a stable leader that skips phase 1 for each slot |
| Distinguished proposer | The Paxos leader, needed for liveness |
| Raft | Consensus algorithm with terms, leader election and log replication, equivalent in result to Multi-Paxos |
| Term (Raft terms) | Raft's numbered leadership period; at most one leader per term |
| Leader election | Followers time out, become candidates and collect a majority of votes |
| Election timeout | Randomised wait (example 150–300 ms) before a follower starts an election |
| AppendEntries / RequestVote | Raft's replication/heartbeat RPC and election RPC |
| Log matching property | Same index and term means identical logs up to that point |
| Commit index (commitIndex) | Highest log index known to be stored on a majority (current term) |
| Membership changes / joint consensus | Raft's two-step configuration change through Cold,new |
| Learner / non-voting replica | Receives the log but does not vote or count toward quorum |
| Snapshot / InstallSnapshot | Compacted state replacing a log prefix; sent to followers that fell behind |
| Delegated snapshot | CockroachDB snapshot sent by a nearby follower instead of the leader |
| Pre-vote | Election dry run that does not bump the term unless the candidate would win (etcd PreVote) |
| CheckQuorum | A leader steps down if it cannot hear from a quorum |
| Leader lease | Time-bounded guarantee that no other leader exists; enables local reads |
| Leader leases (CockroachDB) | Leasing regime that keeps the leaseholder equal to the Raft leader |
| Linearizable (linearizable reads) | Every operation appears to take effect at one instant between its start and end |
| Read index | Linearizable read after confirming leadership with a heartbeat round |
| Lease reads | Linearizable reads served under a valid leader lease, without a round trip |
| Follower reads | Reads from a nearby replica at a timestamp it is known to have complete |
| Closed timestamp | CockroachDB leaseholder's promise not to accept writes at or below a timestamp |
| Bounded / exact staleness | Follower reads at a freshest-possible or a fixed past timestamp |
| Split brain | Two nodes both acting as leader and accepting writes |
| Fencing token | Monotonic number sent with writes so storage can reject a deposed leader |
| STONITH | Fencing by powering off the old node |
| Zab | ZooKeeper Atomic Broadcast; leader-based, zxid ordering |
| zxid | ZooKeeper transaction id: 32-bit epoch + 32-bit counter |
| etcd | Raft-replicated key-value store with leases, watches and transactions |
| TrueTime | Spanner's clock API returning an interval [earliest, latest] with bounded error ε |
| Commit wait | Spanner waits until TT.after(s) before making a commit visible |
| External consistency | If T1 commits before T2 starts, T1's timestamp is smaller (strict serializability) |
| HLC (hybrid logical clock) | Physical time plus a logical counter; CockroachDB and YugabyteDB timestamps |
| Uncertainty interval | Window of possible clock offset in which a read cannot order a value; may force a restart |
--max-offset | CockroachDB's maximum allowed clock offset between nodes |
| Range | CockroachDB's unit of data and replication: a contiguous key span |
| Leaseholder | The replica of a range that serves reads and proposes writes |
| Gateway node | The CockroachDB node a client is connected to; routes requests to leaseholders |
| Write intent | CockroachDB provisional value plus exclusive lock pointing to a transaction record |
| Transaction record | CockroachDB per-transaction state: PENDING, STAGING, COMMITTED or ABORTED |
| Parallel Commits | CockroachDB's commit protocol that usually needs one consensus round |
| Percolator | Google's SI transactions on Bigtable with a primary lock and a timestamp oracle; TiDB's model |
| Prewrite / primary key | Percolator's lock-and-write phase / the key whose commit decides the transaction |
| PD (Placement Driver) | TiDB's metadata and timestamp service |
| Region | TiKV's unit of data and Raft replication (256 MiB default size limit) |
| Tablet | YugabyteDB's unit of data and Raft replication |
| DocDB | YugabyteDB's distributed document store on RocksDB |
| Calvin | Deterministic database: agree on transaction order first, no 2PC |
| Multi-region placement | Choosing where voters and leaseholders live (survival goals, table localities) |
REGIONAL BY ROW / GLOBAL | CockroachDB table localities: per-row home region / fast reads everywhere |
| RTT (write latency) | Round-trip time; the unit of commit latency |
40001 | SQLSTATE serialization failure / "restart transaction"; retry the whole transaction |
Ambiguous result (40003) | Commit outcome unknown after a lost connection |
| Retry loops | Client code that re-runs the transaction function on 40001 with backoff |
| Transactional outbox | A message row committed with the business change, relayed later |
| Saga (sagas) | Sequence of local transactions with compensations instead of a distributed transaction |
References
- Jim Gray & Leslie Lamport, "Consensus on Transaction Commit", MSR-TR-2003-96, revised 19 April 2004. arXiv cs/0408036
- Leslie Lamport, "Paxos Made Simple", 1 November 2001. PDF
- Diego Ongaro & John Ousterhout, "In Search of an Understandable Consensus Algorithm (Extended Version)", 2014. raft.github.io
- James C. Corbett et al., "Spanner: Google's Globally-Distributed Database", OSDI 2012. PDF
- Daniel Peng & Frank Dabek, "Large-scale Incremental Processing Using Distributed Transactions and Notifications" (Percolator), OSDI 2010. PDF
- Alexander Thomson et al., "Calvin: Fast Distributed Transactions for Partitioned Database Systems", SIGMOD 2012. PDF
- Martin Kleppmann, "How to do distributed locking", 8 February 2016. Blog
- CockroachDB docs: Architecture Overview, Replication Layer, Transaction Layer, Transaction Retry Error Reference, Read Committed, Follower Reads, Multi-Region Overview, cockroach start, Deploy a Local Cluster in Docker, Connection Parameters, Build a Go App, SHOW RANGES, cockroach sql
- TiDB docs: TiDB Architecture, TiKV Overview, TiDB Storage, Optimistic Transactions
- YugabyteDB docs: Architecture, Raft, DocDB, Isolation levels
- etcd: FAQ, API guarantees,
go.etcd.io/raft/v3 - ZooKeeper: ZooKeeper Internals
- PostgreSQL docs: PREPARE TRANSACTION, COMMIT PREPARED, pg_prepared_xacts, max_prepared_transactions
- MySQL 8.4: XA Transaction SQL Statements
- MongoDB: Replica Set Protocol Version, Transactions: Production Considerations
- SQLite: Atomic Commit In SQLite
- Laravel 13 docs: Database: Getting Started; framework source: ConcurrencyErrorDetector, ManagesTransactions
- Go:
database/sql,pgx/v5