Chapter 08 / 10 · Distributed Systems

Distributed transactions

Asha is on shard 3 and Ravi on shard 11. Moving ₹500 between them means two-phase commit or a saga, and each has a price.

This chapter lets you keep a transfer correct when the two accounts it touches live on different machines. You should come away able to trace two-phase commit and say exactly where it blocks, design a saga whose in-between states are honest, and choose between them from the invariant you need rather than from habit.

Asha’s account is on shard 3 and Ravi’s is on shard 11. Each shard has its own primary, its own database and its own log. On one machine, the transfer was a single transaction that debited one row and credited another. Now no single database sees both rows. Asha sends Ravi ₹500, and we need the debit and the credit to happen together or not at all.

Say what must remain true

Before choosing a protocol, write down the invariants. For the wallet there are four. Money is conserved: the total across all accounts, plus anything explicitly in transit, never changes because of a transfer. No balance goes below zero. Each transfer is applied exactly once. And a fourth, which is a choice rather than a law: whether anyone may observe the moment when the money has left Asha and not yet reached Ravi.

The naive approach shows why the list matters. The transfer service debits Asha on shard 3, commits, then calls shard 11 to credit Ravi. If the service crashes between those steps, ₹500 has left Asha and arrived nowhere. Conservation is broken, and nothing in the system records that a credit is owed. If the credit call times out, we are back in the first chapter: the credit may or may not have happened.

There are two broad responses. One makes both shards commit atomically, so the in-between state is never visible. The other accepts the in-between state and makes it an explicit, recorded state that the system knows how to finish. Two-phase commit is the first; sagas are the second.

Two-phase commit, step by step

Two-phase commit has a coordinator, here the transfer service, and participants, here the two shards. It runs as follows.

The coordinator writes a transaction record and sends prepare to both shards. Shard 3 checks that Asha has at least ₹500, locks her row, writes the pending debit and a prepare record durably to its log, and votes yes. By voting yes, it promises that it can commit no matter what happens next, including its own crash and restart. Shard 11 does the same for Ravi’s credit. If either votes no, or does not answer, the coordinator decides to abort.

If both vote yes, the coordinator writes its decision, commit, durably to its own log. That write is the moment the transaction commits. It then sends commit to both shards, which apply their changes and release their locks. If a shard does not acknowledge, the coordinator keeps resending until it does.

coordinatorshard 3 · Ashashard 11 · Raviprepareyes✕crashed beforelogging commitin doubtlocks held · cannotcommit or abort alone
Fig 8 · Both shards have voted yes and hold their locks. The coordinator crashes before recording a decision, and neither shard can decide alone
Predict first

The coordinator crashes after both shards vote yes and before it writes its decision. Asha immediately tries to pay a shop from her account on shard 3. What happens to that payment, and what can shard 3 do about the stuck transfer?

Show the worked answer

Shard 3 holds the lock on Asha’s row, so her new payment waits behind it, and eventually times out.

Shard 3 cannot abort on its own, because the coordinator might have recorded commit and told shard 11, which would then have credited Ravi with money Asha never paid. It cannot commit on its own either, because the coordinator might have decided to abort, for example if shard 11’s yes vote never arrived. Asking shard 11 helps only if shard 11 has heard the decision; if it is also waiting, neither knows more than the other.

So shard 3 waits, holding the lock, until the coordinator recovers and reads its log. If the coordinator’s disk is lost, a human decides. A participant that has voted yes is in doubt, and the protocol gives it no way out. One machine’s failure has frozen an account on another.

What two-phase commit costs on a busy account

The blocking case is rare. The everyday cost is lock duration. Each participant holds its lock from prepare until it hears the decision: at least two round trips plus the forced log writes at every step. Inside one data centre, that might total around 5 ms.

For Asha, 5 ms is invisible. For a busy merchant receiving payments from thousands of users, it sets a ceiling. Every payment to the merchant locks the merchant’s row for the duration of its two-phase commit, and payments to that row are processed one at a time. At 5 ms per transaction, the merchant can receive at most about 200 payments per second (1,000 ms ÷ 5 ms), however many machines we add. If each participant is itself a replicated group across two data centres, as our shards are, each prepare and each commit must be replicated before it counts, adding about 30 ms each. The lock is held for something like 65 ms, and the ceiling drops to roughly 15 payments per second.

That ceiling has nothing to do with total system capacity. It is a property of one hot row. The usual mitigation is to split the merchant’s balance across several sub-accounts and spread incoming payments over them, which raises the ceiling at the cost of a more complicated balance read.

Making the coordinator impossible to lose

The blocking problem comes from the coordinator being a single machine whose decision might be unavailable. Two well-known designs remove that.

Google’s Spanner makes every participant and the coordinator a Paxos group, a replicated state machine of the kind from the consensus chapter. The coordinator’s decision is not on one disk; it is committed in a replicated log. If the coordinator’s leader crashes, its group elects another leader that has the decision. The participants still wait, but they wait for an election measured in seconds, not for a human. Atomic commit is still two-phase; it is just run between groups that do not disappear.

Google’s Percolator, built on Bigtable, removes the coordinator process altogether. Each transaction picks one of its rows as the primary. In the first phase, it writes a lock on every row it touches, and every lock points to the primary. The commit point is a single-row write that replaces the primary’s lock with a commit record, and single-row writes in Bigtable are atomic. If the client crashes, any later reader that finds a stale lock on Ravi’s row follows the pointer to the primary. If the primary has committed, the reader rolls the transaction forward; if the primary’s lock is still there and has timed out, it rolls the transaction back. The decision lives in the data, so any survivor can finish the work. CockroachDB and TiDB use descendants of this idea.

Both designs keep atomicity and remove the indefinite block. Neither removes the lock duration, and both still need a way to order transactions, which Spanner gets from its clocks and Percolator from a central timestamp service.

Sagas: a transfer as a sequence of honest states

The other approach gives up atomic visibility and makes the in-between state part of the design. A saga is a sequence of local transactions, each on one shard, with a compensating action for each step that can undo its effect if a later step fails.

For the transfer, the trick that makes it honest comes from double-entry bookkeeping. Each shard has an internal account for money in transit. Step one runs on shard 3 as one local transaction: debit Asha ₹500, credit shard 3’s in-transit account ₹500, record the transfer with status debited, and write an outbox event. Conservation holds after this step, because the ₹500 sits in a named account, not in a gap.

Step two runs on shard 11, driven by that event: credit Ravi ₹500, record that transfer t-9001 has been credited, and emit an event. The credit is keyed by the transfer id, so if the event is delivered twice, the second delivery finds the record and does nothing. Step three, back on shard 3, moves the ₹500 out of the in-transit account and marks the transfer complete.

If shard 11 refuses the credit, perhaps because Ravi’s account has been closed, the saga compensates. Shard 3 moves ₹500 from the in-transit account back to Asha and marks the transfer refunded. The compensation is also keyed by transfer id, so it too can be retried safely. Between the steps, Asha sees ₹1,500 and a transfer marked pending; Ravi sees nothing yet, or the same transfer as incoming. Every state is true, and the app can show it.

The weakness is that compensation is not rollback. A rollback makes it as if the step never happened. A compensation is a new action that happens later, after others may have seen and acted on the earlier state. Here is how that goes wrong. Suppose the team adds a fraud check as a step after the credit. Asha pays Ravi, step two credits him, and Ravi immediately spends the ₹500 at a shop. Then the fraud check flags the transfer, and the saga tries to compensate by debiting Ravi. His balance is zero. The compensation fails, and the money has left the system.

The fix is to order the steps so that anything that might fail or be refused comes before anything that cannot be undone. The fraud check runs before the credit, while the money is still in shard 3’s in-transit account and can be returned cleanly. The step after which the saga can only move forward, here the credit to Ravi, should be as late as possible, and every step after it must be one that can always eventually succeed by retrying. The cost is latency, since the check now sits before Ravi gets his money, and the discipline of reviewing step order whenever someone adds a step.

Keeping a saga moving when nobody is watching

A saga is a sequence of steps spread over time, so something has to remember where each transfer is and push it forward after failures. In the wallet, that memory is the transfer record on shard 3, with its status: debited, credited, complete, refunding, refunded. Each step updates the status in the same local transaction as its effect, and each status change writes an outbox event that triggers the next step.

Events can be delayed, lost by a buggy consumer, or stuck behind a poison event in a partition. So the wallet also runs a sweeper: a periodic job that looks for transfers whose status has not changed for longer than expected, say two minutes in debited, and re-emits the event for the next step. Because every step is keyed by transfer id, a re-emitted event for a step that already happened does nothing. The sweeper is what turns “at least once, eventually” into a bound that can be monitored: the number of transfers older than two minutes and not yet finished should be close to zero, and an alert should fire when it is not.

The sweeper also needs a rule for transfers that cannot finish. If shard 11 has been unreachable for an hour, retrying the credit every two minutes achieves nothing, and Asha has been looking at a pending transfer all that time. It is tempting, after some limit, to refund Asha and move on. That is unsafe. A credit event may still be sitting in a queue, and if shard 11 comes back and processes it, Ravi is credited and Asha refunded: ₹500 created from nothing. This race between two branches of the same saga is exactly the kind of interleaving the last chapter’s model checking is good at finding.

The safe version cancels on the far side first. The saga asks shard 11 to record that transfer t-9001 is cancelled, as a row keyed by the transfer id. Any credit for t-9001 that arrives later finds that row and is refused. Only once shard 11 has acknowledged the cancellation does shard 3 refund Asha. The uncomfortable consequence is that while shard 11 is unreachable, the transfer can be neither completed nor refunded; it stays pending, and the best the app can do is tell both users that it is delayed. The saga has not escaped the first chapter’s ambiguity. It has only made the ambiguity visible and given it a name.

Finally, sagas weaken isolation in a way that is easy to miss. While a transfer sits in debited, a reader who sums Asha’s and Ravi’s balances sees ₹500 less than before. Anything that reads across shards, such as a family-account view or the reconciliation job, must know to include in-transit accounts, or it will report money missing that is merely moving.

Choosing between them

ApproachIn-between state visible?On coordinator failureWhat the design must also handle
Classic 2PCNoParticipants block, holding locksCoordinator recovery; hot-row throughput ceilings
2PC over consensus groupsNoWait for an electionReplication latency inside lock hold time
Percolator-styleNoAny reader resolves from the primaryA timestamp source; stale locks found lazily
Saga with in-transit accountsYes, as explicit pending statesSaga resumes from its last recorded stepCompensations, step order, idempotent steps

The choice comes down to one question: can the in-between state be made honest? “₹500 in transit, transfer pending” is a state a user understands and a ledger can account for, so a saga fits a wallet well, and many payment systems are built this way. A seat on a flight sold to two passengers, or a stock trade where one side settled and the other did not, may have no acceptable in-between state, and then atomic commit is worth its locks.

If you choose a distributed SQL database such as Spanner or CockroachDB, it runs atomic commit for you, and the question becomes whether its latency and hot-row behaviour fit your workload. If you build on separate databases per shard, sagas are usually the practical choice, because classic two-phase commit across independently operated databases inherits the blocking problem in its worst form.

When to avoid the question

The cheapest distributed transaction is the one the data layout makes unnecessary. A merchant’s orders, refunds and balance can usually live on the same shard, keyed by merchant, so that the operations touching them are local transactions. Transfers between arbitrary users cannot be co-located that way, which is why the wallet needs one of the designs above at all.

Revisit the decision when the proportion of cross-shard operations changes. If a resharding puts most related accounts together, a saga’s pending states may become rare enough that users never notice them. If a regulator requires that no observer ever see money in transit, the saga’s honest in-between state is no longer allowed, and atomic commit becomes a requirement rather than a preference.

We now have the full set of pieces: idempotent RPCs, ordering without clocks, replication, event delivery, consensus, leases with fencing and cross-shard transactions. The next chapter, Systems that shipped, reads Dynamo, Spanner, Kafka and etcd as sets of choices among these pieces, and asks what our wallet would get from building on each.