Databases and storage

Replication

Keep copies of the same data on several machines, and reason about what lag, failover and conflicting writes do to the guarantees you can offer.

Lesson15 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A team runs its product on one PostgreSQL server. One night the disk controller fails. The newest backup was taken at 02:00, restoring it takes three hours, and every order placed after 02:00 is gone. A month later a marketing email triples read traffic, and the same server burns its CPU on product pages while checkouts time out. Then the company launches in Australia, where each query crosses the Pacific and back, adding roughly 150 ms before the database does any work.

These are three different problems with one answer: keep the same data on more than one machine. A second copy survives a dead disk, can serve reads, and can sit close to distant users.

The first attempts were crude. Teams took nightly dumps, then shipped the database’s log files to a standby every few minutes. Both leave a window of lost data. Modern replication streams each change as it happens. Copying the data is the easy part. The hard part is deciding what to promise while the copies disagree, which they always do for at least a moment.

Leader and followers

In the most common design, one node is the leader (or primary) and accepts every write. It records each change in a log, the write-ahead log in PostgreSQL or the binlog in MySQL, and streams that log to followers (replicas), which apply the changes in the same order. Reads can go to any node.

The choice that matters is when the leader tells the client “committed”.

Mode The leader waits for What it costs
Asynchronous Nothing A leader crash can lose writes the client was told were safe
Synchronous Every follower One slow or dead follower stalls all writes
Semi-synchronous At least one follower out of several Each write pays a round trip to the fastest follower

Asynchronous is the default in both PostgreSQL and MySQL. Teams that cannot lose writes usually run semi-synchronous. In PostgreSQL, synchronous_standby_names = 'ANY 1 (s1, s2)' commits once either standby confirms. MySQL’s semi-synchronous plugin is similar, but by default it falls back to asynchronous if no replica answers within 10 seconds, so the guarantee can quietly disappear during an incident.

Replication lag and what users see

An asynchronous follower is usually milliseconds behind the leader. Under heavy writes, a long-running transaction or a network problem it can be seconds or minutes behind. Three anomalies follow.

  • A user cannot see their own write. They save their profile, the next page load reads from a follower that has not received the change, and the old value comes back. To the user this looks like data loss.
  • Time moves backwards. Two reads hit two followers with different lag. A comment appears, then vanishes on refresh.
  • Effects arrive before causes. When related writes travel through different partitions or leaders, a reply can become visible before the message it answers.

The fixes are routing rules, not faster replication:

  • Read your own writes from the leader. Send a user’s reads to the leader for anything they can edit, or for a few seconds after their last write.
  • Track the log position. Remember the position of the user’s last write (an LSN in PostgreSQL, a GTID in MySQL) and only read from a follower that has reached it.
  • Pin a user to one follower, so successive reads never go back in time. This guarantee is called monotonic reads.

Consistency models covers these guarantees in more depth.

Failover and split brain

When a follower dies, it restarts and catches up from the log. When the leader dies, a follower must be promoted. That is failover, and it has three steps: detect the failure (usually heartbeats missed for some timeout), pick the most up-to-date follower, and repoint clients and the other followers.

Failover with asynchronous replication, and split brain4 components: App servers, Node A, Node B, Node C. Connections: App servers to Node A (writes); Node A to Node B (log stream); Node A to Node C (log stream); App servers to Node B (after failover).App serversNode Azone 1leader, log at 1001Node Bzone 2follower, log at 1001Node Czone 3follower, log at 1001writeslog streamlog streamafter failover

Step 1 of 8

Node A is the leader. Every write goes to A, which acknowledges it at once and then streams its log to followers B and C asynchronously. The followers are usually a few milliseconds behind.

Read the steps as text
  1. Node A is the leader. Every write goes to A, which acknowledges it at once and then streams its log to followers B and C asynchronously. The followers are usually a few milliseconds behind.
  2. Two more writes arrive in a burst. A acknowledges both to the app, but they have not reached B or C yet. The app believes writes 1002 and 1003 are safe.
  3. The network between A and the rest of the cluster breaks. A is still running, but B and C stop receiving its heartbeats. They cannot tell a dead leader from an unreachable one.
  4. After a timeout the failover manager promotes B, the most up-to-date follower. C starts following B and the app is pointed at B. Writes are flowing again within seconds.
  5. Writes 1002 and 1003 existed only on A, so the new leader has never seen them. The app was told they had succeeded. This is the price of asynchronous replication: a failover can lose acknowledged writes.
  6. A was never dead. An app server with an old connection can still reach it, and A still believes it is the leader, so it accepts the write. Two leaders are now taking writes and their logs diverge. This is split brain.
  7. The defence is fencing. Each promotion gets a higher epoch number. When A reconnects and offers its log with epoch 1, the others refuse it because they are on epoch 2, and A steps down.
  8. A rejoins as a follower and discards its two unreplicated writes, or sets them aside for manual repair. Safe failover needs two things: one agreed leader, and a way to stop the old one.
Failover with asynchronous replication, and split brain

Each step can go wrong:

  • The timeout is a guess. Too short, and a brief stall under load triggers a failover that makes the overload worse. Too long, and the outage lasts longer.
  • Acknowledged writes can vanish. With asynchronous replication the new leader may lack the old leader’s final writes.
  • Split brain. The old leader was unreachable, not dead. Two nodes now accept writes and their data diverges.

Preventing split brain takes two things. First, only one node may be chosen, which means the decision is made by majority vote in a consensus system. Patroni, a widely used PostgreSQL failover manager, keeps its leader lock in a store such as etcd for this reason. Second, the old leader must be fenced: powered off, or made harmless by an epoch number that rises with each promotion and is checked before any write is accepted.

The risk is real. In October 2018 a 43-second network break at GitHub triggered an automated MySQL failover from the East Coast to the West Coast of the United States. Each side ended up holding writes the other lacked, and the service ran degraded for just over 24 hours while they were reconciled.

Multi-leader replication

In a multi-leader setup several nodes accept writes, typically one leader per region, and each replicates its changes to the others asynchronously. Local users get fast writes, and a region keeps working when it is cut off. An app that works offline is the same idea, with every device acting as a leader.

The price is write conflicts. Two leaders can change the same record before either hears from the other. Your options:

  • Avoid conflicts. Route all writes for a given record, such as one user’s data, to a single home region. This is the most reliable choice.
  • Last write wins. Attach a timestamp and keep the highest. It is simple, and it silently discards the other write. Clocks drift, so the “last” write is not always the latest. Cassandra resolves conflicts this way, column by column.
  • Version vectors. Each replica keeps a counter per replica. Comparing two vectors shows whether one version replaced the other or the two were concurrent. Concurrent versions are kept as siblings for the application to merge, as in Riak.
  • CRDTs. Counters, sets and text sequences designed so that merges give the same result in any order, and replicas converge without coordination. Collaborative editing libraries such as Automerge and Yjs are built on them.

Leaderless replication and quorums

Dynamo-style stores such as Cassandra and Riak have no leader. A write goes to all N replicas of a key and succeeds once W of them acknowledge. A read waits for R replies and takes the newest version. If W + R > N, the replicas that answered the read must include at least one that took the write. A common setting is N = 3, W = 2, R = 2, which tolerates one dead node for both reads and writes with no failover step at all.

A quorum write and read with N = 3, W = 2, R = 25 components: Client, Coordinator, Replica A, Replica B, Replica C. Connections: Client to Coordinator; Coordinator to Replica A; Coordinator to Replica B; Coordinator to Replica C.ClientCoordinatorany node in the clusterReplica Av6Replica Bv6Replica Cv6

Step 1 of 9

The key cart:42 is stored on three replicas, so N is 3. All three hold version 6. The cluster is set to W = 2 and R = 2: a write needs two acknowledgements and a read waits for two replies.

Read the steps as text
  1. The key cart:42 is stored on three replicas, so N is 3. All three hold version 6. The cluster is set to W = 2 and R = 2: a write needs two acknowledgements and a read waits for two replies.
  2. The client writes version 7. The coordinator, which can be any node, sends the write to all three replicas at once. It does not choose two of them. It sends to all and waits for the first two.
  3. Replicas A and B store version 7 and acknowledge. Replica C is restarting and never receives the write. Two acknowledgements satisfy W, so the client is told the write succeeded.
  4. The coordinator keeps a hint for C and will replay the write when C returns. This is hinted handoff. Suppose C comes back before the hint is delivered, so it is serving again with stale data.
  5. Now a read arrives. The coordinator needs two replies, and this time it hears from B and C. Because W plus R is greater than N, any two replicas must include at least one that took the write.
  6. B answers with version 7 and C answers with version 6. The coordinator compares the versions and returns the newer one. The client sees the latest write even though one replica was stale.
  7. The coordinator also writes version 7 back to C. This is read repair: a stale replica is fixed as a side effect of being read.
  8. Keys that are rarely read are never repaired that way. A background anti-entropy process compares replicas using Merkle trees and copies whatever differs.
  9. The trade is in the numbers. W = 2 and R = 2 survive one dead replica for both reads and writes. Lower W or R and requests get faster and more available, but a read may miss the latest write.
A quorum write and read with N = 3, W = 2, R = 2

Replicas that missed a write catch up in three ways:

  • Read repair. A read that sees a stale replica writes the newer value back to it.
  • Hinted handoff. While a replica is down, another node keeps its writes as hints and replays them when it returns. Cassandra keeps hints for three hours by default.
  • Anti-entropy. A background process compares replicas using Merkle trees and copies the differences, which covers data that is rarely read.

When to choose each

Topology Choose it when Avoid it when
Single leader You want transactions, constraints and simple reasoning. This is the default. Writes exceed one machine. Then add sharding.
Multi-leader Users in several regions need fast local writes, or clients work offline The same records are edited in several places and you cannot define a merge
Leaderless Writes must survive node failures with no failover, and access is by key You need transactions, unique constraints or read-modify-write without conflicts

Every topology here copies the whole data set to each node. Replication adds read capacity and fault tolerance. It does not add write capacity.

In the interview

Replication appears in almost every design, so state the topology and the mode in one sentence: “a single PostgreSQL leader, one semi-synchronous standby in a second zone, and two asynchronous read replicas”. Then name the consequences before you are asked. Replica reads can be stale, so reads that follow a user’s own write go to the leader. Failover is automatic, decided through a consensus store, with fencing, and typically takes tens of seconds. If the interviewer pushes for multi-region writes, start with conflict avoidance by homing each user in one region. If you pick a Dynamo-style store, give N, W and R and say what the choice trades.

Key takeaways

  • Replication buys durability, availability, read capacity and lower latency for distant users. It does not add write capacity.
  • Asynchronous replication is fast but can lose acknowledged writes on failover. Synchronous replication is safe but stalls on a slow follower. Semi-synchronous is the usual compromise.
  • Lag makes users miss their own writes or see time go backwards. Fix it with routing rules, not by hoping lag stays small.
  • Failover needs one agreed leader and fencing of the old one. Without both you risk split brain.
  • Multi-leader and leaderless designs stay writable through failures and pay for it with write conflicts that someone must resolve.
  • With N replicas, W + R > N makes every read overlap the latest successful write, but a quorum alone is not linearizability.

Check yourself

1. A leader acknowledges a write to the client and crashes before any follower has received it. A follower is promoted. With asynchronous replication, what happens to that write?
2. A user edits their profile. The page reloads with the old value, and a second reload shows the new one. Which fix targets the cause at the lowest cost?
3. A leaderless store keeps N = 3 replicas of each key. Which setting can return stale data even when every node is healthy and writes are not concurrent?
4. During a network partition the old leader keeps running while a new one is promoted. What actually stops the old leader from damaging the data?
5. Leaders in two regions each accept an update to the same row within the same second. The system resolves conflicts with last write wins. What is the outcome?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

Asynchronous, synchronous and semi-synchronous replication: what does the leader wait for?

Asynchronous: nothing, so a crash can lose acknowledged writes. Synchronous: every follower, so one slow follower stalls writes. Semi-synchronous: at least one follower out of several.

What is read-your-writes consistency, and how do you provide it with asynchronous replicas?

A user always sees their own latest write. Read that user's data from the leader for a short window after they write, or track the log position of their write and only use a follower that has reached it.

What is split brain and how is it prevented?

Two nodes both act as leader and accept conflicting writes. Prevent it by electing the leader with a majority vote and fencing the old leader, by shutting it down or rejecting its stale epoch number.

State the quorum condition for leaderless replication.

With N replicas, W write acknowledgements and R read replies, W + R > N guarantees that every read set overlaps the latest successful write set. N = 3, W = 2, R = 2 is the common choice.

Read repair, hinted handoff, anti-entropy: what does each do?

Read repair fixes a stale replica when a read notices it. Hinted handoff stores writes for a down replica and replays them when it returns. Anti-entropy compares replicas in the background with Merkle trees.

Three ways to resolve a multi-leader write conflict, and the safest alternative.

Last write wins (simple, loses data), version vectors with siblings (application merges), CRDTs (merge automatically). Safest is to avoid conflicts by sending all writes for a record to one leader.

Review the deck