Replication

How replication keeps copies of data on several machines, how single-leader, multi-leader and leaderless setups differ, and what interviewers ask.

18 minLesson 3 of 7
On this page
  1. Where replication sits
  2. Single-leader replication
  3. Synchronous, asynchronous and semi-synchronous replication
  4. Multi-leader replication
  5. Leaderless replication
  6. Replication lag, failover and conflict resolution
  7. In the interview
  8. What to practise next

Replication means keeping copies of the same data on several machines, so that every change made on one machine is also applied to the others. It is used so that data survives the loss of a machine, so that another copy can take over when a machine fails, and so that reads can be spread over several machines. The cost is that the copies can briefly disagree, so most replication decisions are about how long they may disagree and who is allowed to see it.

Without replication, a database on one machine is a single point of failure. If its disk fails, everything since the last backup is lost, and that machine also serves every read, so reads can overload it even when nothing has failed.

Where replication sits

Writes go to one primary database, and the changes are copied to replicas that serve reads.Client to App servers; App servers to Primary database (writes); App servers to Replicas (reads); Primary database to Replicas (change log).ClientApp serversPrimary databaseReplicaswritesreadschange log
Writes go to one primary database, and the changes are copied to replicas that serve reads.

Single-leader replication

In single-leader replication, also called leader-follower or primary-replica, one node is the leader and accepts every write. It appends each change to a log and sends the log to the followers, which apply the changes in the same order. Reads can go to the leader or to any follower. Because one machine orders all writes there are no write conflicts, which is why single-leader is the default choice.

A write, a stale read and a fixUse the arrows or ← → keys
  1. A write, a stale read and a fix, step 1User to App server; App server to Leader A (writes); App server to Follower B (reads); App server to Follower C (reads); Leader A to Follower B, asynchronous; Leader A to Follower C, asynchronous.UserApp serverLeader Aname = MoFollower BFollower Cwritesreadsreads
    A log
    1042
    B log
    1041
    C log
    1041

    1A user renames their profile to Mo, and the write goes to leader A.

  2. A write, a stale read and a fix, step 2User to App server; App server to Leader A (writes); App server to Follower B (reads); App server to Follower C (reads); Leader A to Follower B, asynchronous; Leader A to Follower C, asynchronous.UserApp serverLeader AFollower BFollower Cwritesreadsreads
    A log
    1042
    B log
    1041
    C log
    1041

    2A commits and replies at once, because replication is asynchronous and A does not wait for B or C.

  3. A write, a stale read and a fix, step 3User to App server; App server to Leader A (writes); App server to Follower B (reads); App server to Follower C (reads); Leader A to Follower B, asynchronous; Leader A to Follower C, asynchronous.UserApp serverLeader AFollower BFollower Cold namewritesreadsreads
    A log
    1042
    B log
    1041
    C log
    1041

    3The user reloads the page and the read goes to follower C, which has not yet applied entry 1042, so it returns the old name. This is replication lag.

  4. A write, a stale read and a fix, step 4User to App server; App server to Leader A (writes); App server to Follower B (reads); App server to Follower C (reads); Leader A to Follower B, asynchronous; Leader A to Follower C, asynchronous.UserApp serverLeader Aname = MoFollower BFollower Cwritesreadsreads
    A log
    1042
    B log
    1041
    C log
    1041

    4To fix it, the app remembers that this user wrote at position 1042 and sends their reads to the leader until a follower has caught up to that position.

1 / 4

The limit of single-leader replication is that every write goes through one machine, so followers add read capacity but no write capacity. When the leader fails, a follower has to be promoted, as described under failover below.

Synchronous, asynchronous and semi-synchronous replication

This choice decides whether the leader waits for followers before it tells the client that a write succeeded.

Synchronous replication

With synchronous replication the leader waits until a follower confirms it has stored the change, and only then replies to the client. An acknowledged write therefore exists on at least two machines, so losing the leader cannot lose it. The cost is one extra round trip per write, and if every follower is synchronous, one slow or dead follower stalls all writes.

Asynchronous replication

With asynchronous replication the leader replies as soon as it has stored the change itself and ships it to the followers afterwards. Writes are fast and a dead follower does not affect them. The followers are always slightly behind, and if the leader fails, changes that had not been shipped are lost even though the client was told they succeeded.

Semi-synchronous replication

Semi-synchronous replication makes one follower synchronous and the rest asynchronous. Every acknowledged write is on the leader and on at least one follower, and the write waits for only one follower. If the synchronous follower becomes slow or dies, an asynchronous one takes its place. Use it when acknowledged writes must not be lost, such as for payments, and use plain asynchronous replication when a few lost writes are tolerable, such as for likes.

Multi-leader replication

Each region has its own leader that accepts local writes, and the leaders send their changes to each other.EU users to EU leader (local writes); US users to US leader (local writes); EU leader and US leader (async replication), asynchronous.EU usersUS usersEU leaderUS leaderlocal writeslocal writesasync replication

request and replyasynchronous message

Each region has its own leader that accepts local writes, and the leaders send their changes to each other.

In multi-leader replication several nodes accept writes and forward their changes to the other leaders. The usual setup is one leader per region. A user writes to the nearest leader, so writes are fast, and a region can go offline while the others keep accepting writes.

The cost is write conflicts. Two users can change the same row in different regions at the same time, and each leader accepts its own write before it learns about the other, so the database needs a rule for the final value, as described below. Choose multi-leader only when writes must be local to several regions or must work offline.

Leaderless replication

In a leaderless system, such as a Dynamo-style key-value store, a coordinator sends each write to several replicas at once and any replica can accept it. There is no leader, so there is no failover: if a replica is down, the others carry on.

Quorums and why R + W > N

Each key is stored on N replicas. A write succeeds when W replicas confirm it, and a read asks R replicas and takes the newest version. If R + W > N, any set of R replicas shares at least one replica with any set of W replicas, so every read reaches a replica that has the latest successful write.

A quorum write and read with N = 3, W = 2, R = 2Use the arrows or ← → keys
  1. A quorum write and read with N = 3, W = 2, R = 2, step 1Client to Coordinator; Coordinator to Replica 1; Coordinator to Replica 2; Coordinator to Replica 3.ClientCoordinatorReplica 1v2Replica 2v2Replica 3v1
    N
    3
    W
    2
    R
    2
    acks
    2

    1A write of x = v2 reaches replicas 1 and 2, and replica 3 is unreachable. Two confirmations equal W, so the write succeeds.

  2. A quorum write and read with N = 3, W = 2, R = 2, step 2Client to Coordinator; Coordinator to Replica 1; Coordinator to Replica 2; Coordinator to Replica 3.ClientCoordinatorReplica 1v2Replica 2v2Replica 3v1
    N
    3
    W
    2
    R
    2
    answers
    v2, v1

    2A read asks replicas 2 and 3, and they disagree: replica 2 returns v2 and replica 3 returns v1.

  3. A quorum write and read with N = 3, W = 2, R = 2, step 3Client to Coordinator; Coordinator to Replica 1; Coordinator to Replica 2; Coordinator to Replica 3.ClientCoordinatorReplica 1v2Replica 2v2Replica 3v1
    N
    3
    W
    2
    R
    2
    returned
    v2

    3Any 2 replicas out of 3 overlap with any other 2, because 2 + 2 = 4 is greater than 3, so one answer is always the latest. The coordinator returns the higher version, v2.

  4. A quorum write and read with N = 3, W = 2, R = 2, step 4Client to Coordinator; Coordinator to Replica 1; Coordinator to Replica 2; Coordinator to Replica 3.ClientCoordinatorReplica 1v2Replica 2Replica 3v1 (stale)
    N
    3
    W
    1
    R
    1
    returned
    v1

    4With W = 1 and R = 1 the sum is 2, which is not greater than 3. A write that reached only replica 1 followed by a read of replica 3 returns the stale v1.

1 / 4

W = N with R = 1 makes reads fast but lets one dead replica block every write, and W = 1 with R = N does the opposite. A majority for both tolerates a minority of replicas being down.

How stale replicas catch up

A replica that missed a write while it was down does not fix itself, so leaderless stores use two repair mechanisms. In read repair, a read that sees different versions from its R replicas writes the newest version back to the replicas that returned an old one. In anti-entropy, a background process compares replicas, often using hash trees so that it only transfers the ranges that differ, and copies missing data.

What a quorum does not guarantee

R + W > N guarantees overlap, but it does not make the system behave like one up-to-date copy. Concurrent writes to the same key can both succeed, so the store still needs a conflict rule. A write that reached fewer than W replicas is reported as failed but can still be seen by later reads. With a sloppy quorum, which accepts writes on stand-in nodes when the owners are unreachable, a read may miss the write until the stand-in hands the data back.

Replication lag, failover and conflict resolution

Replication lag and what users see

With asynchronous replication a follower can be behind the leader, by milliseconds normally and by minutes if it is overloaded. Three guarantees cover the cases users notice.

Read-your-writes means a user always sees their own changes. The fix is to read from the leader for data the user has modified, for a short time after each write or until a follower reaches the log position of that write.

Monotonic reads means a user never sees data go backwards. Without it, one read can reach an up-to-date follower and the next a lagging one, so a comment appears and then disappears. The fix is to send each user's reads to the same replica, chosen by hashing the user id.

Consistent prefix reads means readers see related writes in the order they happened, so an answer never appears before its question. This matters mostly in sharded databases, where shards replicate at different speeds.

Failover, promotion and split brain

When the leader fails, the system must detect the failure, choose a new leader and point clients at it. Detection is usually a timeout without heartbeats: a short timeout replaces leaders that were only slow, and a long one leaves the system without writes for longer. The new leader should be the follower with the most complete log. With asynchronous replication, writes that the old leader had acknowledged but not shipped to that follower are lost. Some teams therefore require a person to confirm a failover for databases where a lost write is serious.

Split brain happens when two nodes both believe they are the leader and both accept writes. The standard defence is to elect the leader through a consensus service that issues an increasing term number, and to make storage reject writes carrying an older term, which is called fencing. The old leader rejoins as a follower and discards log entries the new leader never received. See consensus and leader election.

Conflict resolution in multi-leader and leaderless systems

When two writes to the same data happen concurrently, the system needs a rule for the final value. There are four common approaches.

  • Avoid conflicts. Route all writes for a given record to the same leader, for example by assigning each user a home region. This is the simplest approach and works whenever the data has a natural owner.
  • Last write wins. Each write gets a timestamp and the highest one is kept. It is simple, but it silently discards the other write, and clocks differ between machines, so the winner may not be the later write.
  • Keep both versions. The store detects concurrent writes, for example with version vectors, and returns both to the application, which merges them. A shopping cart can merge by taking the union of items.
  • Merge automatically. Data types called CRDTs, such as counters and sets, combine concurrent updates without conflicts.

Read replicas help reads, not writes

Adding followers is the standard way to scale reads. It does nothing for write capacity, because every write still goes to the leader and must be applied on every follower. Lagging followers also serve stale data, so the fixes above are needed. When writes or data size exceed one machine, use sharding, so that different leaders own different parts of the data.

In the interview

Bring up replication when data must not be lost, the service must stay available, or reads exceed what one database serves. Name the arrangement, say whether it is synchronous, and say how a user who has just written reads their own data. The default is single-leader with one synchronous follower and the rest asynchronous.

Questions to expect:

  • "Should replication be synchronous or asynchronous?" It depends on whether an acknowledged write may be lost. Fully synchronous replication stalls writes when any follower is down, and fully asynchronous replication can lose acknowledged writes when the leader fails. Semi-synchronous, with one synchronous follower and the rest asynchronous, is the usual compromise.
  • "What happens to writes when the leader dies?" A follower is promoted after a few seconds of detection and an election. With asynchronous replication, writes that had not reached that follower are lost, so use a synchronous follower when that is not acceptable.
  • "A user saves a change and then sees the old data. Why?" The read went to a follower that had not applied the write yet. Fix it with read-your-writes by sending that user's reads to the leader shortly after they write.
  • "How do you avoid two leaders after a failover?" Elect the leader through a consensus service that issues term numbers, and have storage reject writes from an older term. The old leader rejoins as a follower and drops writes the new leader does not have.
  • "Why does R + W > N give you the latest value?" Any read set and any write set share at least one replica, so a read always reaches a replica with the latest successful write.
  • "How does a leaderless store repair a replica that missed a write?" Read repair writes the newest version back to stale replicas whenever a read notices a difference. A background anti-entropy process compares replicas and copies missing data, so keys that are never read are repaired too.
  • "How do you handle conflicting writes in two regions?" First avoid them by giving each record one home region. Otherwise use a merge that fits the data, such as a union for sets, and avoid last write wins where updates must not be lost.
Replicating a profile serviceStrong answer
Interviewer

Your database is a single point of failure. How would you fix that?

You

I would use single-leader replication with two followers. One follower is synchronous, so every acknowledged write exists on two machines, and the other is asynchronous. The followers also take over most of the read traffic.

Interviewer

A user edits their profile and then sees the old version. What is going on?

You

Their read went to a follower that had not yet applied the write. I would send that user's reads to the leader for a few seconds after they write. Other users seeing the new profile a few hundred milliseconds late is fine.

Interviewer

What if the leader fails?

You

The synchronous follower has every acknowledged write, so I would promote it through a consensus-based election that issues a new term number. The old leader is then fenced off, and it rejoins as a follower if it comes back.

Quick check

A leaderless store keeps N = 5 copies and writes with W = 3. What is the smallest R that guarantees reads overlap the latest successful write?

A user posts a comment and the reloaded page does not show it. Which fix targets this problem directly?

What to practise next

For data too large for one leader, read Sharding and Partitioning. The guarantees here are defined precisely in CAP and Consistency, and a quorum store is built end to end in Design a Key-Value Store.