Replication
Overview
Keeping data on one machine means one failure can make it unavailable or lose it, and one machine limits how many reads you can serve. Replication keeps copies (replicas) of the same data on several machines. It’s used in almost every database deployment. The hard part is that copies can disagree for a while, and you must decide what users see when they do.
Why replicate
- Availability: if one node fails, another has the data.
- Read scaling: spread reads across many copies.
- Latency: put copies near users in other regions.
- Isolation: run heavy analytics or backups on a replica without slowing the main database.
Leader-follower replication
The most common setup (also called primary-replica):
- All writes go to the leader.
- The leader records each change in its log (often the write-ahead log) and streams it to followers.
- Followers apply the changes in the same order and serve reads.
PostgreSQL streaming replication, MySQL replication, MongoDB replica sets and Redis replicas all work this way.
Synchronous vs asynchronous
- Synchronous: the leader waits for a follower to confirm before telling the client the write succeeded. No acknowledged write is lost if the leader dies, but every write pays a network round trip, and if the follower is down, writes stall.
- Asynchronous: the leader confirms immediately and sends changes in the background. Writes are fast, but followers lag, and if the leader dies, its latest writes may never have left it.
- Semi-synchronous: one follower is synchronous and the rest asynchronous, a common compromise. Managed “multi-AZ” databases often work this way.
Replication lag and what users see
Asynchronous followers are usually milliseconds behind, but under heavy load or after a network blip they can fall seconds or minutes behind. Reading from them causes visible oddities:
- Read-your-writes violation: you post a comment, reload, and it’s gone (it’s on the leader, not yet on the replica you read).
- Non-monotonic reads: you refresh twice and see a newer value, then an older one, because each request hit a different replica.
Fixes:
- Read your own writes from the leader: for a short period after a user writes, or for data a user can edit (their own profile).
- Track log positions: remember the leader’s position after a write and read only from replicas that have caught up.
- Sticky replicas: send each user to the same replica so time never goes backwards for them.
- Monitor lag and take replicas that fall too far behind out of rotation.
Failover
When the leader fails, a follower must be promoted:
- detect the failure (missed heartbeats),
- pick the most up-to-date follower,
- point writes at it and make other followers follow it,
- make sure the old leader can’t come back and accept writes (fencing), or you get split brain.
With asynchronous replication, promoted followers may be missing the last writes. Managed databases automate this process; you should still know the risks.
Multi-leader replication
Several nodes accept writes, typically one per region, and replicate to each other.
- Pros: local writes in every region, survives a region outage, works for offline clients (a phone or a collaborative editor is effectively its own leader).
- Cons: two leaders can change the same record at the same time, so you need conflict resolution: last-write-wins (simple, but loses data), merging values, application-specific rules or CRDTs (data types designed to merge automatically).
Use it only when you really need multi-region writes; conflicts are hard to reason about.
Leaderless replication
Any replica accepts reads and writes. A client (or coordinator) writes to several replicas and reads from several, using quorums to make sure reads see recent writes (week 5). Background processes repair replicas that missed writes. Used by Cassandra, ScyllaDB and DynamoDB-style systems, it tolerates node failures without failover, at the cost of eventual consistency and more complex reasoning.
Replication is not a backup
A replica copies everything, including mistakes. If someone runs DELETE FROM orders without a WHERE, every replica deletes the orders within milliseconds. Protecting against that needs backups and point-in-time recovery (the backups lesson).
In an interview
For a read-heavy system: “The database has a leader for writes and two async read replicas for reads; one synchronous standby in another zone for failover. Users read their own recent writes from the leader to avoid lag surprises.” That covers availability, scaling and consistency in two sentences.
Recap
Replication keeps copies of data for availability, read scaling and locality. Leader-follower is the default: synchronous followers prevent loss, asynchronous followers are fast but lag. Handle lag with read-your-writes routing, plan failover carefully to avoid split brain and data loss, and reach for multi-leader or leaderless designs only when their extra complexity buys something you need.
Fix the disappearing comment
A forum uses one PostgreSQL leader and three asynchronous read replicas. All reads go to replicas. Users complain: 'I posted a comment, the page reloaded, and my comment wasn't there — then it appeared a few seconds later.' (a) Explain the cause. (b) Give two ways to fix it without sending every read to the leader. (c) What else could go wrong if the leader crashes?
(a)
(b)
(c)(a) Replication lag. The comment is written to the leader, but the follow-up read hits
a replica that hasn't applied that write yet (asynchronous replication may lag by
milliseconds to seconds, more under load).
(b) Read-your-writes fixes:
- After a user writes, route that user's reads to the leader for a short time
(e.g. 10 seconds), tracked in their session.
- Record the leader's log position (LSN) after the write; only read from a replica
that has replayed at least that position, otherwise use the leader.
- Or update the page from the write response itself (optimistic UI), so the
reload isn't needed.
(c) With async replication, writes the leader acknowledged but hadn't yet sent to
any replica are lost when a replica is promoted. There is also a risk of split brain
if the old leader comes back and still accepts writes, unless it is fenced.Summary
- Replication keeps copies of data on several nodes for availability, read scaling and lower latency.
- In leader-follower replication one node accepts writes and streams changes to followers that serve reads.
- Synchronous replication avoids data loss but slows writes; asynchronous is fast but followers lag and recent writes can be lost on failover.
- Replication lag breaks read-your-writes and monotonic reads unless you route reads carefully.
- Multi-leader and leaderless replication allow writes in several places but must resolve conflicts.