Chapter 04 / 10 · Distributed Systems

Replication and consistency

Three copies of the wallet in two data centres. Asha sends money, refreshes, and sees her old balance.

This chapter lets you choose, for each piece of data, how stale a read may be and what that costs, and predict what users will notice when the copies disagree. It also walks through the failover that most teams get wrong the first time.

The wallet now runs on three machines in two data centres. The leader and one follower are in DC-1; a second follower is in DC-2. We will assume a round trip between the data centres of about 30 ms, which is in the range for two cities several hundred kilometres apart, and about half a millisecond inside each. Asha sends ₹500 to Ravi. The app says “Sent”. She pulls down to refresh, and her balance still shows ₹2,000.

What the copies are for

Replication buys three different things, and it helps to know which one a given copy is for. The follower in DC-1 is there so that losing the leader’s machine does not lose data or stop payments for long. The follower in DC-2 is there so that losing all of DC-1 does not either. And either follower can serve reads, which spreads load and, for users near DC-2, cuts latency.

The mechanism is the leader’s log. Every committed transaction is already written to the leader’s write-ahead log for crash recovery. Streaming replication ships that log to the followers, which apply it in the same order. Because there is one leader and one log, the order question from the previous chapter is settled: every copy applies the same changes in the same sequence. The open question is timing. A follower is always somewhat behind, and the distance it is behind is called replication lag.

When does the leader say “done”?

The first decision is when the leader acknowledges a transfer to the caller. It can answer as soon as its own disk has the commit, or it can wait until some followers have it too.

Acknowledge afterAdded commit latencySurvives losingWhat the design must also handle
Leader only (async)NoneNothing that was not yet shippedAcknowledged transfers lost on failover
Leader + DC-1 followerAbout 1 msThe leader’s machineA whole-DC outage still loses recent transfers
Leader + DC-2 followerAbout 30 msAll of DC-1Every commit pays the cross-DC round trip; DC-2 trouble slows all writes
All followersAbout 30 ms, plus the slowest nodeEverythingAny one slow or dead follower stops all writes

It helps to put a number on the asynchronous row. Suppose the wallet commits 200 transfers per second and the DC-2 follower usually runs 50 ms behind. At any moment, about 200 × 0.05 = 10 acknowledged transfers exist only in DC-1. During a burst, or while DC-2 is replaying a large batch, lag can reach seconds, and the window grows to hundreds of transfers. For comments on a blog, losing ten writes in a rare disaster may be acceptable. For a wallet, an acknowledged transfer that disappears means Asha was told she paid and Ravi never got the money, or worse, Ravi was notified and the money then vanished.

So the wallet waits for at least one follower. Which one depends on the failure it must survive. Waiting for DC-2 costs about 30 ms on every commit, but databases group concurrent commits into one flush and one round trip, so throughput suffers far less than latency. That is the choice we will assume: the leader acknowledges once the DC-2 follower has the transaction on disk.

Why Asha sees her old balance

Waiting for a follower to store the log is not the same as waiting for it to apply the log. Many systems acknowledge once the follower has written the entry to disk and apply it to their tables shortly after. Reads served by that follower can still miss a transfer that has been acknowledged.

appleader · DC-1follower · DC-1follower · DC-2send ₹500₹2,000 → ₹1,500okapplied ~80 ms laterGET balance₹2,000 · the old value
Fig 4 · The leader acknowledges the transfer. The refresh is served by the DC-2 follower, which has not applied it yet, so Asha sees ₹2,000
Predict first

Asha’s refreshes are load-balanced across the two followers. The DC-1 follower applies the transfer within 2 ms; the DC-2 follower within about 80 ms. She refreshes twice in quick succession. What sequences of balances can she see?

Show the worked answer

If both refreshes land on the DC-1 follower after it applied the transfer, she sees ₹1,500 twice. If the first lands on DC-2 before it caught up, she sees ₹2,000 then ₹1,500, which looks like the app was slow.

The unsettling case is the reverse: the first refresh lands on DC-1 and shows ₹1,500, the second lands on DC-2 and shows ₹2,000. Her balance appears to go back up. To Asha this looks like the payment was reversed. She may well send it again.

Nothing is wrong with the data in any of these cases. Each replica is a correct copy of the leader at some recent moment. What is missing is a guarantee about which moment a given read reflects.

The guarantees users actually notice

Database theory has a long list of consistency models. Three of them map directly onto things a wallet user sees, and they are worth learning by the complaint they prevent.

Read-your-writes says that after Asha makes a change, her own reads reflect it. Its violation is the case we started with: “I sent money and my balance did not change.” Monotonic reads says that once a user has seen a value, later reads do not show an older one. Its violation is the balance that goes back up. Consistent prefix says that if a series of writes happened in an order, nobody sees a later one without the earlier ones. In the wallet, its violation is a history page showing Ravi spending ₹500 before the credit that gave him the ₹500.

There is a fourth that crosses users. Ravi receives a push notification: “You received ₹500 from Asha.” He opens the app, his read goes to a lagging follower, and the money is not there. The notification was caused by the credit, and his read should reflect everything that caused what he has seen. That is causal consistency.

One mechanism serves all of these. When the leader commits a transfer, it returns its log position along with the result, a number like LSN 88,412. The app stores the highest position it has seen and sends it with each read. A follower that receives a read asking for “at least 88,412” either waits until it has applied that far, typically a few milliseconds, or forwards the read to the leader. The push notification carries the position of the credit, so Ravi’s read waits for it too. The cost is plumbing a token through the app and API, and an occasional wait. A cruder alternative is to send a user’s reads to the leader for a few seconds after each write, which costs leader capacity and, for DC-2 users, 30 ms per read.

Measuring lag before it surprises you

Every choice in this chapter depends on how far behind the followers are, so the wallet needs to measure it, and the obvious measurements mislead.

Databases usually report lag as a distance in the log: the follower has applied up to byte position X and the leader has written up to Y. That number is precise and hard to interpret. Two megabytes of lag is nothing during a bulk import and a long time during a quiet night. Converting it to seconds by assuming a write rate gives the wrong answer exactly when the write rate changes, which is when lag matters.

A more direct method is a heartbeat row. Once a second, the leader writes its current time into a small table. Each follower, when it applies that write, compares the stored time with its own clock. The difference is the lag in seconds, as seen by a reader of that follower. It includes clock skew between the two machines, so a few milliseconds of error should be expected, but it measures the thing users care about: how old is the data a read here would see.

There is one trap. If the leader stops writing, perhaps because it has crashed or been partitioned, the follower’s last applied heartbeat simply gets older. A follower that computes lag as “now minus the last heartbeat I applied” reports growing lag, which is correct. A follower that only reports lag when a new heartbeat arrives reports nothing, and a dashboard showing the last value shows healthy lag throughout an outage. Lag should be computed continuously from the age of the newest applied heartbeat.

With a trustworthy lag figure, routing can use it. The API can send a balance read to the DC-2 follower only while that follower reports lag below, say, 200 ms, and fall back to the leader otherwise. During the salary-credit batch at the end of each month, when DC-2 falls a few seconds behind, reads quietly move to the leader instead of showing stale balances to everyone in the region. The cost is extra load on the leader at exactly the moment it is busiest, which is worth checking against its capacity before relying on it.

Which reads need the leader

The strongest model is linearizability: the system behaves as if there were one copy, and each operation takes effect at a single instant between its start and end. Every read sees every write that finished before it began. It is what a single machine gives you, and it costs a trip to the leader, or a check with a majority, on every read.

Not every read in the wallet needs it, and the skill is to decide per read path.

ReadGuaranteeWhy
Balance check inside a transferLinearizable, on the leaderA stale balance would let Asha spend money she no longer has
Balance on the home screenRead-your-writes and monotonicA few milliseconds stale is invisible; going backwards is not
Transaction historyConsistent prefix, causal across accountsCredits must appear before the spending they funded
Monthly statementSnapshot as of a log positionMust be exact for a point in time, not current
Analytics dashboardEventualMinutes of lag change nothing

This is also the right place to read the CAP theorem precisely. It says that when the network partitions, a system must choose for each operation between answering with possibly stale or conflicting data and not answering. That is all it says. Suppose the link between the data centres fails. DC-2’s app servers can reach only their follower. They can show balances marked “as of 10:42”, which is available and stale. They should not accept transfers: the leader is unreachable, and accepting debits locally would let Asha spend the same ₹2,000 once in each data centre. For the wallet, reads stay available and writes in DC-2 stop. When the network is healthy, the trade is between latency and freshness, which is the subject of every row in the table above.

Copies without a leader

There is another family of designs worth understanding even though the wallet will not use it for balances. In a leaderless store, in the style of Amazon’s Dynamo, a client writes to several replicas directly and reads from several, with no single node deciding order.

write · W = 3read · R = 3n1n2n3n4n5R + W > N → the sets must share a node — here n3 — so some read replica has the new value
Fig 5 · With five replicas, a write acknowledged by three and a read that asks three must share at least one node

With N replicas, a write is acknowledged once W of them have it, and a read asks R of them and takes the newest version it gets. If R + W > N, every read set overlaps every write set in at least one node, so some replica in the read has the latest acknowledged write. With N = 3, W = 2 and R = 2 is the balanced choice; W = 3 and R = 1 makes reads cheap and lets one slow node block writes.

The overlap guarantee is weaker than it looks. A write that reached one replica and then failed is reported as failed, but it is still on that replica and may spread later. Two writes to the same key arriving at different replicas at once produce siblings, the concurrent versions from the last chapter. And nothing in the scheme can stop two concurrent debits that each see a balance of ₹2,000 from both succeeding. Preventing an overdraft means checking and updating the balance in one place, in one order. That is coordination, and leaderless replication is designed to avoid it.

The general principle is worth stating carefully. Data types designed to merge concurrent updates automatically, known as CRDTs, work well for counters, sets and presence. A counter CRDT can add up concurrent top-ups correctly. It cannot enforce “balance never below zero”, because that invariant depends on the order of concurrent debits. Any invariant of that shape needs coordination somewhere.

The failover that goes wrong

Now the walk-through the chapter promised. Before we chose to wait for DC-2, the wallet was configured asynchronously. Here is what happened during a power failure.

At 21:10, DC-1 loses power. The leader and the DC-1 follower go down together. The DC-2 follower was 400 ms behind at the time, because a large batch of salary credits had just been committed. At 200 transfers per second, that is about 80 acknowledged transfers that exist nowhere outside DC-1.

The on-call engineer sees DC-1 unreachable and promotes the DC-2 follower to leader. Payments resume after eleven minutes. The 80 transfers are gone. Some of their users were told “Sent”. Some recipients had already received push notifications, because the notification service consumed events from the old leader before it died.

It gets worse. Transfer ids came from a database sequence. The new leader’s sequence was behind, so it hands out ids t-9001 through t-9080 again, to different transfers. Receipts, support tickets and the bank reconciliation file now have two meanings for each of those ids. GitHub described a similar failure in 2012, where a promoted MySQL follower reused auto-increment ids that another system still referenced.

At 21:40, power returns in DC-1. The old leader boots, finds its configuration says it is the leader, and starts accepting writes from the API servers in DC-1 that still point at it. There are now two leaders. Both accept transfers. This is split brain, and reconciling its results is manual work measured in days.

Each problem has a fix with a price. Waiting for the DC-2 follower before acknowledging means no acknowledged transfer is lost, for about 30 ms on every commit. Identifiers that do not depend on the leader, such as the idempotency key or a random UUID, cannot be reissued. Stopping the old leader needs a rule it cannot ignore when it wakes: either it is forcibly shut down before the new leader starts, or every leader carries an epoch number and storage rejects writes from older epochs. And deciding who is leader should not depend on one engineer reading a dashboard at night. Making that decision automatically, without ever producing two leaders, is the consensus problem.

When replicas for reads are not worth it

Every anomaly in this chapter came from serving reads on followers. If the leader can handle all reads, keeping followers purely as standbys removes the whole class: users only ever read from the one copy that is always current. Many payment systems do exactly this for balances and use followers only for reporting.

Serving reads from followers becomes worth its complexity when the leader is genuinely overloaded, or when users far from the leader need lower latency than a cross-region round trip allows. Revisit the decision when either of those becomes true, and take the session tokens with it.

Before we automate failover, there is a quieter problem. The leader does not only replicate to followers; the notification service, the fraud model and the analytics store all need to hear about every balance change, in an order that makes sense. The next chapter, Broadcast, gossip and ordering guarantees, looks at what each of those listeners needs and what it costs to provide.