Replication means keeping copies of the same data on several machines. Almost every production database does it. The hard part is not making the copies. It is deciding what happens when a write arrives while copies are behind, when a machine dies, or when two copies are changed at the same time. This lesson covers the three ways to replicate and the rules for quorums.
1. Why Replicate
- Availability: if one machine dies, another has the data. This is how you reach the 99.99% targets from the availability lesson.
- Read capacity: reads spread over many copies, so a read-heavy system scales without sharding.
- Latency: a copy near the user answers faster than a copy across an ocean.
- Durability: data on three machines survives the loss of two.
Replication does not add write capacity. In leader-based systems, every write still goes through one node. For write capacity you need sharding (a later lesson). Replication also does not replace backups. A bad delete is replicated to every copy within seconds.
2. Leader-Follower
One node is the leader (also called primary or master). All writes go to it. It sends each change to the followers (replicas or secondaries), which apply the changes in the same order. Reads can go to the leader or to any follower. PostgreSQL, MySQL, MongoDB and Redis all work this way.
flowchart LR
A[App] -- writes --> L[Leader]
L -- "replication log" --> F1[Follower 1]
L -- "replication log" --> F2[Follower 2]
A -- reads --> F1
A -- reads --> F2
The leader sends a log of changes, not the data itself. Most databases ship the write-ahead log (WAL) bytes or a logical row-change stream. Statement-based logs are fragile because functions such as NOW() and RANDOM() give different results on each node.
2.1 Synchronous, Asynchronous and Semi-Synchronous
The key choice is when the leader tells the client "done".
- Asynchronous: the leader commits, answers the client, and sends the change later. Writes are fast and the leader is never blocked by a slow follower. But if the leader dies before the change is sent, the client was told "done" and that write is lost. How much recent data you can lose this way is your RPO (recovery point objective, from the availability lesson). With asynchronous replication the RPO is the replication lag, often under a second. PostgreSQL and MySQL replicate asynchronously unless you change the setting.
- Synchronous: the leader waits until the follower confirms. No acknowledged write is lost. But every write now pays a network round trip (about 0.5 ms in one data center, 1 to 2 ms across zones), and if the follower is down, writes stop.
- Semi-synchronous: wait for one follower, and let the rest be asynchronous. If the synchronous follower fails, another takes its place. At every moment at least two nodes have each acknowledged write, so one failure loses nothing. This is the usual setting when you cannot lose data.
Making all followers synchronous is a trap: with three followers at 99.9% each, a write would need all of them, and any one failure would block writes. One synchronous follower is the practical limit.
2.2 Replication Lag
With asynchronous followers, a follower is always a little behind. Usually the lag is milliseconds. Under heavy write load, a slow disk or a long-running query on the follower, it can grow to seconds or minutes. Reading from a follower then shows old data. Take a profile page. The user changes their display name and the page reloads:
- Read-your-writes violation: the write went to the leader, the reload read from a lagging follower, and the user sees the old name. They think the save failed. Fix: read your own recent data from the leader. For example, for 10 seconds after a user writes, send that user's reads to the leader. Or remember the position of the user's last write and read only from a follower that has reached it.
- Monotonic-reads violation: the first read hits a fresh follower and shows the new name, the second hits a stale follower and shows the old name. Time seems to go backwards. Fix: send each user always to the same follower, for example by hashing the user ID.
- Consistent-prefix violation: a reply appears before the question it answers, because the two writes lived on different shards that replicate at different speeds. Fix: keep causally related writes in the same partition.
// Route a read: use the leader if this user wrote recently
DataSource pick(String userId) {
Instant lastWrite = recentWrites.get(userId); // set after each write
boolean recent = lastWrite != null
&& Duration.between(lastWrite, Instant.now()).getSeconds() < 10;
return recent ? leader : followerFor(userId); // followerFor = hash(userId)
}
Always monitor lag, and set an alert (for example above 5 seconds). A follower that is too far behind should be removed from the read pool.
2.3 Failover
When the leader dies, a follower must take over. The steps are:
- Detect that the leader is dead. Use a timeout, such as three missed heartbeats. Too short causes false alarms. Too long extends downtime.
- Choose the new leader. Pick the follower with the most data.
- Reconfigure so that clients and the other followers use the new leader.
- Demote the old leader if it comes back, so that it becomes a follower.
Where it goes wrong:
- Lost writes: with asynchronous replication, the new leader may miss the last writes. When the old leader returns, those writes conflict with new ones. They are usually discarded. This is dangerous if other systems already saw them. An auto-increment ID reused by the new leader is a known example.
- Split brain: the old leader was only slow, not dead. Now two nodes accept writes, and the data diverges. The defense is fencing: the old leader is blocked, by a token, a lease or by cutting its storage. The consensus lesson covers how nodes agree on one leader.
- Slow recovery: the detection, promotion and DNS update add up to minutes unless they are automated. The availability lesson has the arithmetic.
3. Multi-Leader
Several nodes accept writes, and each sends its changes to the others. It is used when one leader is not enough:
- Multiple regions: each region has a leader, so users write to a nearby node instead of crossing an ocean. A region can keep working if the link between regions fails.
- Offline clients: a phone app or a calendar keeps a local copy that accepts writes offline and syncs later. Each device is a small leader.
- Collaborative editing: several people change the same document at once.
The problem is write conflicts. Two leaders change the same row before they hear about each other: one sets the title to "A" and the other to "B". Both are valid on their own node. The system must settle on one result. Options:
- Avoid conflicts: route all writes for one record to the same leader, for example by home region. This is the simplest and the best option when it fits.
- Last write wins (LWW): keep the write with the later timestamp. It is simple and it silently drops the other write. Clocks differ between machines, so "later" can be wrong. Use it only when losing a write is acceptable.
- Merge: combine both, as in a shared document or a set where adds from both sides are kept. Data types built for this are called CRDTs (conflict-free replicated data types). The Google Docs lesson covers them.
- Ask the user: keep both versions and let a person choose, as version control does.
Multi-leader is also harder to operate: auto-increment keys, constraints and triggers behave in surprising ways across leaders. Most teams use it only when they must.
4. Leaderless
There is no leader. The client (or a coordinator node) sends each write to several replicas at once, and each read to several replicas. The Amazon Dynamo paper introduced the design, and Cassandra, Riak and ScyllaDB follow it. (The AWS DynamoDB service is a different system and uses a leader for each partition.) Availability is high because no single node must be up.
4.1 Quorums
With N replicas for each piece of data, a write must be accepted by W replicas, and a read must ask R replicas. If
W + R > N
then the set of nodes that took the write and the set of nodes you read from must share at least one node, so the read sees the latest value. The reader picks the newest version using a version number or timestamp.
| N = 3 | W + R | Behavior |
|---|---|---|
| W = 2, R = 2 | 4 > 3 | Balanced. Survives one node down for both reads and writes. The usual choice |
| W = 3, R = 1 | 4 > 3 | Fast reads. Every write needs all three nodes, so one failure stops writes |
| W = 1, R = 3 | 4 > 3 | Fast writes. Reads need all three nodes |
| W = 1, R = 1 | 2 < 3 | Fastest, but a read can miss the latest write. Stale reads are possible |
With N = 3 and W = R = 2, one slow or dead node does not block anything, and the latency is that of the second-fastest replica, which helps tail latency. In Cassandra, W and R are set per request (ONE, QUORUM, ALL). Most teams use QUORUM for important data. A majority is floor(N/2) + 1 nodes: 2 of 3, 3 of 5.
4.2 Catching Up Missed Writes
A node that was down misses writes. Three mechanisms bring it back:
- Read repair: when a read finds that one replica has an old value, the coordinator writes the new value back to it.
- Anti-entropy: a background job compares replicas (often with hash trees, called Merkle trees) and copies what is missing.
- Hinted handoff: if a replica is unreachable, another node keeps the write as a hint and delivers it when the replica returns. With a sloppy quorum, a write may count towards W even though it went to a stand-in node. Availability improves, but the "read sees the latest write" guarantee no longer holds until the hints arrive.
4.3 Quorums Are Not Magic
Even with W + R > N, stale or conflicting reads can happen:
- Two writes to the same key at the same time have no clear order. Systems use LWW or version vectors to detect the conflict, and then merge or keep both.
- A write that reaches fewer than W nodes reports failure, but the nodes that took it keep it. A later read may return it.
- With sloppy quorums, a restored node can serve old data until hints are delivered.
- Clock differences make LWW drop the wrong write.
So leaderless systems give high availability and low latency, and they usually offer eventual consistency (see the consistency models lesson), not strict ordering. If you need a single order for all writes, use a leader.
5. Choosing
| Aspect | Leader-follower | Multi-leader | Leaderless |
|---|---|---|---|
| Who takes writes | One node | Several nodes | Any replica, by quorum |
| Write conflicts | None, one order | Yes, must be resolved | Yes, must be resolved |
| If a node fails | Failover needed. Short write pause | Other leaders keep working | No failover, quorum continues |
| Consistency | Strong on the leader, lag on followers | Eventual between leaders | Tunable with W and R |
| Best for | Most business systems | Multi-region writes, offline apps | Very high availability and write rates |
| Examples | PostgreSQL, MySQL, MongoDB | MySQL Group Replication (multi-primary), CouchDB | Cassandra, ScyllaDB, Riak |
A good default answer: leader-follower with semi-synchronous replication, reads from followers where lag is acceptable, and the leader for reads that must be fresh. Move to the others only when a requirement forces it, and say which one.
A fourth style, consensus-based replication, elects a leader for each partition and commits on a majority (Raft, used by etcd and CockroachDB; Spanner uses Paxos). The consensus lesson covers it.
5.1 Worked Example: A Read-Heavy Product Catalog
A catalog database gets 100 million reads and 1 million writes a day. Peak is about 4 times the average. Assume one replica serves 2,000 indexed reads per second, planned at 70% utilization (an assumption, to be replaced by a load test).
- Rates: 100 million ÷ 86,400 = 1,160 reads per second on average, so about 4,600 at peak. Writes are 12 per second on average, so about 46 at peak.
- Read replicas: 2,000 × 70% = 1,400 reads per second each. 4,600 ÷ 1,400 = 3.3, so 4 replicas, and 1 more to survive a failure: 5.
- Writes: 46 per second is far below one primary (5,000 to 20,000), so no sharding is needed. Replication here buys read capacity and availability, not write capacity.
- Durability: with asynchronous replication and 1 second of lag, a leader crash can lose about 46 writes. One semi-synchronous follower in another zone adds 1 to 2 ms per write and loses none. For a catalog, async is acceptable. For orders, choose semi-synchronous.
6. Common Pitfalls
- Reading from followers without handling lag. Users see their own changes vanish.
- Assuming replicas are backups. A bad delete or a corrupt write is copied everywhere. Keep real backups.
- Believing replication adds write capacity. It adds read capacity and availability.
- Fully synchronous replication to every follower. One slow node blocks all writes.
- No fencing in failover. Two leaders cause split brain and corrupt data.
- Last write wins on important data. It silently deletes one of two valid writes.
- Thinking W + R > N means strong consistency. Sloppy quorums, concurrent writes and clocks can still give stale reads.
7. Interview Questions This Lesson Prepares You For
- Compare synchronous and asynchronous replication. Synchronous loses no acknowledged write but adds a round trip and blocks if the follower fails. Asynchronous is fast but can lose recent writes on failover. Semi-synchronous waits for one follower and is the common compromise.
- A user updates their profile and then sees the old data. Why, and how do you fix it? The read hit a lagging follower. Read your own recent writes from the leader, or track the write position and read from a follower that has reached it.
- What happens when the leader fails? Detect the failure, promote the most up-to-date follower, repoint clients, and demote the old leader if it returns. Risks are lost async writes and split brain, which fencing prevents.
- Explain quorums. With N = 5, what W and R would you pick? W + R > N makes read and write sets overlap. W = 3 and R = 3 is balanced and survives two nodes down. Lower R makes reads faster at the cost of write availability.
- How do you resolve write conflicts in multi-leader systems? Avoid them by routing a record to one leader. Otherwise use last write wins (simple, loses data), a merge such as a CRDT, or ask the user.
- When would you pick leaderless over leader-follower? When availability and write throughput matter more than a single order of writes, and the data can tolerate eventual consistency or conflict merging.