The naive mental model is a loop. “Write to all the shards in a transaction? Open a connection to each shard, send the write, and if they all return OK, I’m done. If one fails, I undo the others.” That survives exactly until the interviewer asks what happens between two lines of that loop. You wrote to shard A and shard B, and the process crashed before you wrote to shard C - half the transaction is committed and half is not, and nobody is left to finish or undo it. Shard B returned OK to the write but crashed before its own commit landed on disk - did it actually commit? You decided to “undo the others,” but shard A already acknowledged its write to another reader who acted on it - how do you undo that? The loop has no answer to any of these, because a commit across independent databases is not a sequence of writes. It is an agreement problem: every participant has to reach the same verdict - commit or abort - even though they are separate machines that fail independently and cannot see each other.
Two-phase commit is the canonical protocol for that agreement, and it is famous for one sharp weakness: it blocks. If the coordinator - the single node that drives the agreement - dies at the wrong moment, every participant that already voted “yes” is stuck holding locks, unable to commit and unable to abort, until the coordinator comes back. The entire design below is about one property: the coordinator must write its decisions to a durable log before it acts on them, so that a coordinator that crashes mid-protocol can be restarted - on the same node or a new one - read its log, and drive every in-doubt transaction to the same terminal outcome it would have reached if it had never crashed. The log is what turns a single point of failure into a recoverable one. Get the log wrong and 2PC is a toy. Get it right and it is the backbone of cross-shard atomicity.
Let me build it properly.
Functional Requirements (FR)
In scope:
- Atomic commit across multiple independent shards. A client submits a transaction that writes to rows living on 2 or more shards (separate databases, separate machines). The outcome is all-or-nothing: either every shard commits its part, or every shard aborts it. Never a permanent partial state.
- The two-phase commit protocol. Phase 1 (prepare / voting): the coordinator asks every participant “can you commit this?” and each votes YES (durably promising it can) or NO. Phase 2 (commit / abort): if all voted YES the coordinator decides COMMIT, otherwise ABORT, and tells every participant, which then finalizes.
- A durable write-ahead coordinator log. The coordinator records every protocol-significant event - the transaction’s participant set, its own COMMIT/ABORT decision - to a replicated write-ahead log (WAL) before it sends the corresponding message. This is the recovery anchor.
- Crash recovery of in-doubt transactions. After a coordinator crash, a recovered coordinator reads its WAL and, for every transaction that was mid-protocol, drives it to completion: if a COMMIT/ABORT decision was logged, re-send it; if no decision was logged, re-query participants to decide. No transaction is left in-doubt forever.
- Participant durability and in-doubt handling. A participant that has voted YES has written a prepare record to its own local WAL and is holding locks; it stays prepared across its own crashes and waits for the coordinator’s verdict. It can also proactively ask the coordinator “what was the outcome of transaction T?” (recovery query).
- Timeouts and unilateral abort. Before a participant has voted, if the coordinator goes silent, the participant may unilaterally abort (it has promised nothing). Before all votes are in, the coordinator may abort on a timeout. After a YES vote, a participant may NOT unilaterally decide - it must block for the verdict.
- Idempotent commit/abort delivery. Phase-2 messages are retried after crashes and timeouts, so applying COMMIT or ABORT to a participant more than once must be harmless.
Explicitly out of scope (own the scope):
- The storage engine inside each shard. We coordinate the agreement; how a shard holds a prepared transaction’s locks, writes its own redo/undo records, and makes the local commit durable is the shard’s business. We assume each participant is a transactional resource manager that supports prepare / commit / abort.
- Non-blocking atomic commit (3PC, Paxos Commit). Classic 2PC blocks if the coordinator fails while participants are in-doubt. We will make that window short and recoverable by replicating the coordinator’s log and failing over fast, but we are building 2PC, not three-phase commit or a full consensus-based commit. We name the trade-off explicitly and say when you would reach for the alternative.
- Global serializable isolation across shards. 2PC gives atomicity of the commit. The isolation level the reader sees (can another transaction read a row that is prepared-but-not-committed?) is set by each shard’s concurrency control plus how long locks are held. We discuss the locking window; we do not build a global lock manager or a distributed snapshot protocol.
- Transaction routing / query planning. Deciding which shards a transaction touches, parsing SQL, and planning the writes belongs to a query layer above us. We receive a transaction with a known participant set.
- Long-running / interactive transactions. 2PC holds locks for the whole protocol. We target short transactions (tens of milliseconds of coordination). A multi-minute human-in-the-loop transaction belongs in a saga, not 2PC.
The one decision that drives everything: the coordinator is a durable state machine whose only source of truth is its write-ahead log, not its memory. The coordinator’s in-memory view of “transaction T is at phase 1” is a cache; the log is the truth. Every irreversible move - recording the participant set, recording the COMMIT decision - is written and flushed to the replicated log before the move is externalized to participants. Recovery is then trivial to state and hard to get wrong: replay the log, and for each unfinished transaction, do exactly what the log says you had already decided, or finish deciding if you had not. Everything below is a consequence of that.
Non-Functional Requirements (NFR)
- Scale: on the order of 50,000 distributed (cross-shard) transactions/sec at peak across a fleet of coordinators, each transaction touching 2-5 shards on average out of a cluster of hundreds of shards. The large majority of writes are single-shard and never touch 2PC at all; distributed transactions are the minority but the hard case.
- Latency: a distributed commit is inherently two round trips (prepare, then commit) plus durable log flushes. Target the coordinator’s own added latency at p50 ~ 5 ms, p99 ~ 20 ms on top of the participant work, dominated by two fsync-class durable writes (one at the participant on prepare, one at the coordinator on decide). We do not pretend 2PC is free; we make it as cheap as durability allows.
- Availability: 99.95%+ on accepting and driving transactions to completion. The death of any single coordinator node must not strand in-doubt transactions for more than a few seconds - a standby takes over the crashed coordinator’s log and drives its transactions.
- Durability / correctness - the headline: atomicity holds across every crash. A transaction that has committed on one shard commits on all; a transaction that aborted anywhere aborts everywhere. Once the coordinator logs COMMIT, that transaction will commit on every participant eventually, through any number of crashes and retries. This is the single property the whole design protects.
- Consistency semantics: atomic commit, not global isolation. All participants reach the same verdict. The window during which a prepared row is locked and invisible/blocking to other readers is bounded by how fast we reach and deliver the decision; shrinking that window is a first-class goal.
- Blocking bound: the classic 2PC failure mode (participants stuck in-doubt because the coordinator is gone) must be bounded. Target: a coordinator failover completes and in-doubt transactions get their verdict within single-digit seconds, not minutes and never “until a human restarts the coordinator.”
Back-of-the-Envelope Estimation (BoE)
Let me ground it in numbers.
Transaction volume:
Distributed txns/sec (peak): 50,000
Avg participants per txn: 3 shards
Total participant operations: 50,000 * 3 = 150,000 prepare ops/sec
+ 150,000 commit ops/sec (phase 2)
= 300,000 participant RPCs/sec at peak,
before retries.
Single-shard txns (not 2PC): ~10x the distributed rate, handled locally,
never enter the coordinator. We size for the
distributed minority.
Coordinator durable writes - the number that matters:
Per distributed txn, the coordinator logs:
1. a BEGIN/participant-set record (who is in this txn) -> 1 write
2. the COMMIT or ABORT decision -> 1 write
(an END record after all acks can be a lazy/batched write, not on the
critical path.)
Critical-path coordinator log writes: ~2 per txn.
At 50,000 txns/sec -> ~100,000 durable log appends/sec on the coordinator tier.
That 100,000 fsync-class writes/sec is the heart of the sizing. A single disk doing durable fsyncs tops out in the low thousands/sec. So the coordinator log must be (a) spread across many coordinators (each owns a slice of transactions) and (b) use group commit - batch many transactions’ log records into one fsync. With group commit batching ~100 records per flush, 100,000 appends/sec becomes ~1,000 fsyncs/sec, comfortably inside a replicated log tier.
Participant durable writes:
Each participant, per txn it is in:
1. prepare record (durable, "I promise I can commit T") -> 1 fsync
2. commit/abort record -> 1 fsync
150,000 prepare ops/sec -> 150,000 participant prepare fsyncs/sec across the
whole shard fleet. Per shard (say 200 shards) that is ~750 prepare fsyncs/sec,
again made cheap by each shard's own group commit.
Storage for the coordinator log:
Per txn log footprint: txn id, participant list (3 shard ids), decision,
timestamps, status ~= 300 bytes.
50,000 txns/sec * 300 B = 15 MB/sec of coordinator log at peak.
~1.3 TB/day raw, * 3 replicas = ~3.9 TB/day.
But the log is a *recovery* log, not a permanent archive. Once a txn reaches a
terminal state and all participants have acked (END record), its entries are
eligible for truncation. Steady-state retained log = only in-flight +
recently-completed txns = a few GB. We truncate aggressively.
In-flight / in-doubt window:
If a txn spends ~10 ms in-flight (prepare + decide + deliver), then
in-flight txns at any instant = 50,000/sec * 0.01s = ~500 concurrent.
Each holds locks on ~3 shards. Lock footprint is small and short-lived -
as long as the decision window stays in the tens of ms. A coordinator
crash is what stretches that window; bounding failover is therefore the
whole game.
The takeaways that shape the design: the coordinator’s durable decision write is the critical-path cost (so: group commit, and shard the coordinator fleet); the blocking window is the correctness-adjacent cost (so: replicate each coordinator’s log and fail over fast); and log truncation keeps the recovery log small so recovery is fast.
High-Level Design (HLD)
+-------------------+
client txn: | Transaction |
"write r1@shardA, | Router / Session | picks a coordinator for this
r2@shardB, | Layer | txn (by txn-id hash); forwards
r3@shardC atomically"+---------+----------+ the participant set.
|
v
+------------------------------+
| COORDINATOR (owns txn T) |
| in-mem state machine for T |
+---------------+--------------+
| writes decisions first to:
v
+-------------------------------+
| COORDINATOR WRITE-AHEAD LOG | replicated (Raft/quorum),
| per-coordinator log slice | group-committed, truncatable.
| BEGIN(T, {A,B,C}) | DECISION |
+-------------------------------+
|
phase 1: PREPARE | phase 2: COMMIT/ABORT (idempotent, retried)
(fan out) v (fan out)
+-------------+ +-------------+ +-------------+
| Shard A | | Shard B | | Shard C | each: a resource manager
| (RM + its | | (RM + its | | (RM + its | with its OWN local WAL;
| local WAL) | | local WAL) | | local WAL) | holds locks while prepared;
+-------------+ +-------------+ +-------------+ can query coordinator on
recovery ("outcome of T?")
The request flow for a happy-path distributed commit:
- The client sends a transaction to the router, naming the writes and therefore the shards involved (the participant set, say {A, B, C}). The router assigns a coordinator for this transaction - deterministically, by hashing the transaction id - so that anyone can later find which coordinator owns T.
- The coordinator generates a globally unique, monotonic transaction id
Tand writes a BEGIN record to its write-ahead log:BEGIN(T, participants={A,B,C}). This record is flushed durably (via group commit) and replicated to the coordinator log’s followers before the coordinator contacts any participant. Now, even if the coordinator dies this instant, a recovering coordinator knows T existed and who its participants were. - Phase 1 - Prepare. The coordinator sends
PREPARE(T, write)to A, B, and C in parallel. Each participant executes the write against its storage engine but does not commit; it acquires the necessary locks, writes a prepare record to its own local WAL (redo + undo, durably flushed), and replies YES (vote-commit). A participant that cannot - a constraint violation, a lock timeout, a full disk - writes nothing durable (or an abort record) and replies NO. If a participant has voted YES it is now prepared: it has surrendered the right to abort on its own and must hold its locks until it hears the verdict. - The coordinator collects votes. This is the commit point. If all votes are YES, the coordinator writes a COMMIT(T) decision record to its WAL and flushes+replicates it durably. If any vote is NO, or a vote times out, it writes ABORT(T) instead. The transaction’s outcome is defined by this single durable write and nothing else. Before this record is durable, the outcome is undecided; the instant it is durable, the outcome is fixed forever.
- Phase 2 - Commit/Abort. The coordinator sends
COMMIT(T)(orABORT(T)) to every participant. Each participant applies the verdict: on COMMIT it makes its prepared write durable-committed and releases locks; on ABORT it rolls back the prepared write and releases locks. Each participant writes its own commit/abort record locally and replies ACK. - Once all participants have acked, the coordinator writes a lazy END(T) record (not on the critical path) marking T fully resolved; its log entries are now eligible for truncation. The coordinator returns success to the client.
The reason this is correct across crashes is the ordering in steps 2 and 4: the coordinator always makes the durable log write before externalizing the corresponding action. A crash can only ever leave the system in a state the log can explain.
Component Deep Dive
1. The write-ahead coordinator log and in-doubt recovery (the hard part)
The naive approach: coordinator keeps protocol state in memory. The coordinator holds a map txnId -> {phase, votes} in RAM. It fans out PREPARE, collects votes in the map, decides, fans out COMMIT. Simple, fast, no disk on the critical path.
Where it breaks: the coordinator crashes between collecting all the YES votes and sending COMMIT. The participants are all prepared - locked, waiting, having promised to commit. The coordinator restarts with an empty map. It has no idea T ever existed, let alone that it had decided (or was about to decide) to commit. The participants wait forever. Their locks are never released. Any other transaction that needs those rows blocks behind them. This is not a rare edge case - at 50,000 txns/sec there are hundreds of transactions in exactly this window at any instant, and a single coordinator crash orphans all of them. In-memory state is a time bomb.
Why a plain local log is not enough either. Suppose we fix it by writing the decision to a local disk file before sending COMMIT. Better - a recovering coordinator on the same machine can read the file. But if the machine is gone (disk failure, hardware death), the log is gone with it, and we are back to orphaned in-doubt participants with no authority left to resolve them. The log cannot live on one disk any more than the state could live in one RAM.
The design: a replicated, group-committed write-ahead log, and a strict write-before-act discipline.
The coordinator log is a replicated log - a Raft group (or quorum-replicated log) of, say, 3 or 5 nodes. An append is acknowledged only once a quorum has it durably. The coordinator fleet is sharded: each coordinator owns a slice of the transaction-id space and its own log group, so no single log group carries all 100,000 appends/sec. Within a coordinator, group commit batches many transactions’ records into one quorum round + fsync, turning per-transaction durability cost into per-batch cost.
The write-before-act rule is absolute and has exactly two critical-path points:
BEGIN(T, participants) logged+replicated BEFORE any PREPARE is sent
DECISION(T, COMMIT|ABORT) logged+replicated BEFORE any phase-2 msg is sent
Now enumerate what a recovering coordinator finds for each transaction in its (replicated, survived) log, and what it does:
| Log state for T on recovery | What it means | Recovery action |
|---|---|---|
| No BEGIN record at all | Coordinator crashed before durably starting T; no participant can have been told to prepare by a durable BEGIN. | Nothing to do. T never really started. |
| BEGIN present, no DECISION | In-doubt. Coordinator may have sent some PREPAREs; participants may be prepared and waiting. No verdict was reached. | Re-query each participant for its vote/state on T. If all are prepared (voted YES) -> safe to decide COMMIT now, log DECISION(COMMIT), drive phase 2. If any is not prepared / voted NO / unknown -> log DECISION(ABORT), drive phase 2. |
| DECISION(COMMIT) present, no END | Coordinator decided commit but may not have told (or heard back from) all participants. | Re-send COMMIT(T) to all participants (idempotent). Collect acks. Write END. |
| DECISION(ABORT) present, no END | Decided abort; delivery possibly incomplete. | Re-send ABORT(T) to all. Collect acks. Write END. |
| END present | Fully resolved. | Nothing; eligible for truncation. |
The crucial, subtle case is BEGIN present, no DECISION. The coordinator does not know whether it had collected all votes. It cannot assume commit (maybe a participant voted NO and the record of that vote died with the coordinator’s memory) and it cannot blindly assume abort if participants have actually voted YES and are prepared, because it is allowed to still commit them. So it re-runs the voting by querying participants directly. Each participant’s local WAL is authoritative about its own vote: a participant that wrote a prepare record will answer “I am prepared for T (I voted YES)”; one that never prepared answers “I don’t know T / I aborted it.” If every participant says prepared, the coordinator is free to log COMMIT and finish - this is correct because committing is a valid outcome when all voted YES, and no participant has been told otherwise yet. If any participant is not prepared, no COMMIT can ever be safe (that participant might have aborted or lost its prepared state), so the coordinator logs ABORT and tells everyone to roll back. Participants are idempotent, so re-telling a participant that already committed/aborted is harmless.
Participant-side recovery and the recovery query. The symmetry matters. A prepared participant that crashes and restarts re-reads its own local WAL, sees it is prepared for T, re-acquires the locks, and - crucially - does not decide on its own. It asks the coordinator (whose identity is derivable from T’s id) “what was the outcome of T?” This is the participant pulling the verdict instead of waiting to be pushed, which shortens the in-doubt window when it is the participant, not the coordinator, that bounced. The coordinator answers from its log: COMMIT, ABORT, or “still deciding, hold.”
Bounding the blocking window without a new single point of failure. Classic 2PC’s reputation for blocking comes from “the coordinator is a single point of failure; if it dies, prepared participants block until a human restarts it.” We attack that on two axes, and the distinction is the whole point of this design:
- The log is replicated (quorum), so a coordinator machine dying does not destroy the authority needed to resolve in-doubt transactions. The verdict (or the ability to reach one) survives on the log’s other replicas.
- A standby coordinator in the same log group detects the leader’s failure (missed heartbeats / Raft leader election), takes leadership of that log slice, replays the log, and runs the recovery table above. Failover is a leader election plus a bounded log replay of only the unfinished transactions (which is why aggressive END/truncation matters - recovery reads a few GB, not a few TB). Target: single-digit seconds, not operator-restart minutes.
This is the key nuance to state in an interview: we have not eliminated 2PC’s blocking - a participant that voted YES still cannot unilaterally decide and will block if it cannot reach the coordinator-log authority. What we have done is make the authority itself fault-tolerant and fast to reconstitute, so the blocking window is bounded by failover time rather than by human intervention. The coordinator role is a single logical authority but not a single physical point of failure. If you need true non-blocking atomic commit (a participant can resolve without the coordinator), you move to three-phase commit or Paxos Commit - and you pay an extra round trip and more messages for it. That is a trade-off worth naming, not papering over.
2. Participant prepare semantics, locking, and the blocking window
The naive approach: “prepare” just means run the write, hold the row lock, say YES. Reasonable first cut. But two things make the prepared state special and hard.
It must be crash-durable before the YES. A participant that replies YES is making a binding promise: “no matter what happens to me, I can still commit this if told to.” If it replied YES but had not durably written the prepare record, then a crash would lose the write - and now the coordinator might log COMMIT (all voted YES) while this participant has nothing to commit. Atomicity broken. So the prepare record (redo to re-apply the write + undo to roll it back + the lock set) must be flushed to the participant’s local WAL before the YES is sent. The YES vote is itself a durable commitment, which is why prepare costs an fsync.
The locks are held for the whole protocol, and that is the real cost. From the moment a participant prepares until it receives the verdict, the rows it wrote are locked. Other transactions touching those rows block. The naive design holds these locks for: prepare fsync + network to coordinator + coordinator decision fsync + network back + commit apply. In the happy path that is tens of milliseconds, fine. Where it breaks: a coordinator crash stretches this to the failover time, and every reader of those hot rows backs up behind the prepared locks. This is why bounding failover (component 1) is not just an availability nicety - it directly bounds how long unrelated transactions stall.
Design refinements:
- Presumed abort. To keep the log small and recovery cheap, adopt the presumed-abort optimization: the coordinator does not need an END record for aborted transactions, and if a participant asks about a transaction the coordinator has no record of, the answer is ABORT. This means a coordinator can forget aborted transactions immediately after deciding, and “I don’t know T” safely means “abort.” It makes the common abort path (including abort-on-timeout before any decision is logged) cheap: no durable commit record, no END, just forget. Only committed transactions need their decision durably retained until all acks arrive.
- Read-only participant optimization. A participant that did no writes in T (it was queried but only read) can vote READ-ONLY in phase 1 instead of YES. The coordinator then skips phase 2 for that participant entirely - it holds no commit-relevant locks and needs no verdict. This cuts phase-2 traffic for mixed read/write transactions.
- Lock scope. Prepared locks should be as narrow as possible (row/key level, not table/page) so the blocking radius during the window is minimal. This is the shard’s concurrency control, but the coordinator design assumes and depends on it.
3. Coordinator assignment, fencing, and avoiding split-brain
The naive approach: any coordinator can drive any transaction; on failure just start another. The danger is two coordinators believing they own the same in-doubt transaction T - the old leader that was only network-partitioned (not actually dead) and the new standby that took over. If both drive phase 2 and they reach different conclusions, atomicity is destroyed.
Where it breaks: a GC pause or a network partition makes the standby think the leader is dead. The standby elects itself, reads the log, and starts resolving in-doubt transactions - say it queries participants, finds a NO, and sends ABORT. Meanwhile the old leader wakes from its pause still thinking it is the leader, still holding “all voted YES” in memory, and sends COMMIT for the same T. One participant commits, another aborts. Catastrophe.
The design: fencing tokens and single-writer log ownership.
- Each coordinator log slice is a Raft group; only the current Raft leader may append to it. A partitioned old leader cannot append its decision because it cannot get a quorum - it has already been superseded. So the decision record is the fence: whoever wins the quorum to append DECISION(T) is the one true decider, and there can be only one. The old leader’s attempt to log COMMIT fails; it therefore cannot legitimately send COMMIT either (it must log-before-act).
- Phase-2 messages carry a fencing token (the Raft leader term / epoch). Participants remember the highest token they have seen for T and reject messages with a stale token. So even a buggy old leader that skips the log-before-act rule and blasts COMMIT with an old term gets its message rejected by participants, who have already heard from the new leader’s higher term.
- Coordinator-to-transaction assignment is deterministic (hash of T to a log slice), so recovery and participant recovery-queries always know which log group is authoritative for T. There is no ambiguity about who owns a transaction.
The combination - single-writer replicated log for decisions + fencing tokens on phase-2 delivery - is what makes “fail over to a standby coordinator” safe. Without fencing, fast failover would be a correctness bug, not a feature.
API Design & Data Schema
Client-facing API (to the transaction router/coordinator):
POST /txn
body: {
operations: [
{ shard: "A", op: "write", key: "...", value: "..." },
{ shard: "B", op: "write", key: "...", value: "..." },
{ shard: "C", op: "write", key: "...", value: "..." }
]
}
-> 200 { txnId: "T-01H...", status: "COMMITTED" }
-> 409 { txnId: "T-01H...", status: "ABORTED", reason: "participant_vote_no" }
-> 503 { status: "UNAVAILABLE" } (no coordinator quorum; client retries)
GET /txn/{txnId}
-> 200 { txnId, status: PENDING|COMMITTED|ABORTED, participants:[...],
decidedAt, endedAt }
Coordinator-to-participant protocol (internal RPC, idempotent):
PREPARE(txnId, token, writes[])
-> VOTE { txnId, vote: YES | NO | READ_ONLY }
(YES is sent only AFTER the participant durably logged its prepare record)
COMMIT(txnId, token) -> ACK { txnId, applied: true } (idempotent)
ABORT(txnId, token) -> ACK { txnId, applied: true } (idempotent)
// participant -> coordinator, on participant recovery:
GET_OUTCOME(txnId) -> { outcome: COMMIT | ABORT | IN_PROGRESS }
(presumed-abort: unknown txnId -> ABORT)
Coordinator write-ahead log records (the source of truth):
BEGIN { txnId, participants: [shardId...], createdAt, term }
DECISION { txnId, decision: COMMIT | ABORT, decidedAt, term }
END { txnId, endedAt } // lazy; omitted for aborts (presumed abort)
Coordinator transaction-state table (materialized from the log for fast lookups; the log is authoritative):
Table: txn_state Store: replicated log + indexed KV view
txn_id STRING PK (monotonic, carries coordinator slice id)
status ENUM PENDING | COMMITTED | ABORTED
participants LIST<shard_id>
decision_term INT (fencing token at decision time)
created_at TIMESTAMP
decided_at TIMESTAMP NULL
ended_at TIMESTAMP NULL
Index: (status) for recovery scan of PENDING txns
Index: (ended_at) for truncation of resolved txns
Participant local WAL / prepared-transaction table:
Table: prepared_txn (per shard, in the shard's own storage engine)
txn_id STRING PK
state ENUM PREPARED | COMMITTED | ABORTED
redo BLOB (how to apply the write on COMMIT)
undo BLOB (how to roll back on ABORT)
lock_set LIST<key> (locks held while PREPARED)
coord_term INT (highest fencing token seen for this txn)
prepared_at TIMESTAMP
Index: (state=PREPARED) to re-acquire locks and re-query coordinator on restart
SQL vs NoSQL / store choice. The coordinator’s durable state is a replicated write-ahead log (a Raft log is the right primitive) - append-only, quorum-durable, read mostly in order during recovery, truncatable. That is neither “SQL” nor “NoSQL” in the usual sense; it is a consensus log, chosen because its exact guarantees (durable-before-ack, single-writer, survives minority failure) are precisely what the protocol’s correctness rests on. The txn_state view on top is a simple indexed key-value projection for point lookups and recovery scans; it needs no relational joins, so a KV store (or an embedded LSM/B-tree keyed by txn_id) is the fit, not a relational database. Each participant, by contrast, is typically a real transactional database (SQL or otherwise) whose storage engine already has a local WAL and lock manager - we are layering the distributed prepared-transaction state onto whatever each shard already is. The design choice that matters is not SQL vs NoSQL; it is consensus log for coordinator decisions, local transactional WAL at each participant, because atomicity lives or dies on those two durability guarantees.
Bottlenecks & Scaling
Where it breaks first: the coordinator’s durable decision write. Two fsync-class, quorum-replicated writes per transaction, at tens of thousands of transactions/sec, will saturate any single log group. Fixes:
- Group commit. Batch many transactions’ BEGIN and DECISION records into one quorum round + fsync. This is the single highest-leverage optimization; it converts ~100,000 appends/sec into ~1,000 flushes/sec. It adds a tiny latency (wait up to a few ms to fill a batch) in exchange for an order-of-magnitude throughput gain - a trade worth making above a few thousand txns/sec.
- Shard the coordinator fleet by transaction id. Partition the txn-id space across many independent coordinator log groups. Each group handles its slice; the fleet scales horizontally. The shard key is the transaction id, chosen because it distributes evenly (ids are monotonic/hashed), it is known to everyone (router, participants, recovery) so the owning coordinator for any T is always derivable, and a transaction’s entire lifecycle stays within one log group (no cross-group coordination for the coordinator’s own state).
The blocking / in-doubt window is the correctness-adjacent bottleneck. Prepared participants hold locks; a slow or crashed coordinator stretches that window and backs up every reader of those rows. Fixes: replicate the coordinator log (so a crash does not destroy the authority), fast standby failover (leader election + bounded replay of only unfinished txns), aggressive END/truncation (so replay is small), and participant-initiated GET_OUTCOME recovery queries (so a prepared participant actively pulls its verdict the moment an authority is reachable, rather than waiting to be pushed).
Hot keys / hot shards. If many distributed transactions contend on the same few rows, prepared locks serialize them and throughput on those keys collapses regardless of coordinator capacity. This is a data-modeling problem the coordinator cannot fix: keep distributed transactions short (minimize the lock window), keep lock scope narrow (row not table), and push designers toward keeping co-accessed data on the same shard so the write is single-shard and skips 2PC entirely. The cheapest distributed transaction is the one you turned into a local one by co-locating its data.
Single points of failure, eliminated:
- Coordinator node: replaced by a replicated log group + standby leader with fencing tokens. No single node’s death strands transactions; a partitioned old leader cannot commit (it cannot win a quorum to log its decision, and participants reject its stale fencing token).
- Participant node: each participant’s prepared state is in its own durable local WAL; on restart it re-acquires locks and queries the coordinator. The shard itself should be replicated (its own concern), but the prepared state is never only in memory.
- The log group itself: quorum replication (3 or 5 nodes) tolerates a minority failing with no loss of durability or availability of decisions.
Async and lazy work off the critical path. The END record and log truncation are background work, not on the commit path. Phase-2 ACK collection can lag the client response in a “commit returns once the decision is durable” model (the client is told COMMITTED the instant DECISION is durable; participant finalization and ACKs proceed asynchronously and are retried to completion). This shaves a round trip off perceived latency while preserving correctness, because the durable decision - not the acks - is what makes the outcome final.
Replication of the coordinator log is what underpins all of the above: quorum append means a decision acknowledged to the client cannot be lost, and leader election means the authority to resolve in-doubt transactions is always reconstitutable within the failover bound.
Wrap-Up
The trade-offs, stated plainly:
- Atomicity over availability of the blocking window. 2PC guarantees all-or-nothing across shards, but a participant that voted YES must block until it can reach the (now fault-tolerant) coordinator authority. We bounded that window with a replicated log and fast fenced failover; we did not eliminate it. If you need truly non-blocking commit, pay for 3PC / Paxos Commit.
- Durability cost on the critical path. Two fsync-class, quorum-replicated writes per transaction (participant prepare, coordinator decision) are the irreducible price of atomic commit. Group commit amortizes it; it does not remove it.
- Correctness rests on log-before-act plus fencing. Every irreversible move is durable in the replicated log before it is externalized, and phase-2 delivery is fenced by leader term, so fast failover is safe rather than a split-brain hazard.
- 2PC is for short cross-shard writes, not long business workflows. It holds locks for the protocol’s duration; a multi-second or human-in-the-loop transaction belongs in a saga with compensations, not here.
One-line summary of the final design: a horizontally sharded coordinator fleet, each slice backed by a replicated, group-committed write-ahead log that records the participant set and the single durable COMMIT/ABORT decision before acting on them, so that a crashed coordinator fails over to a fenced standby which replays the log and drives every in-doubt transaction - either re-delivering a logged decision or re-querying participant votes to reach one - to the same atomic outcome, bounding the blocking window by failover time instead of operator intervention.
Comments