Replication
Copying data across machines for availability and read scaling — leader–follower, multi-leader and leaderless replication; synchronous vs asynchronous; replication lag and its anomalies; failover.
Replication keeps copies of the same data on several machines. It's used to:
- Survive failures (high availability): if one node dies, another has the data.
- Scale reads: spread queries across replicas.
- Reduce latency: put copies near users in other regions.
The hard part isn't copying data — it's handling changes to it, and what readers see while copies disagree.
Leader–follower (primary–replica)
The most common setup (PostgreSQL, MySQL, MongoDB replica sets, Redis):
- Clients send all writes to the leader.
- The leader streams its change log (the WAL, or a logical change stream) to followers, which apply the changes in the same order.
- Reads can go to the leader (always up to date) or followers (possibly stale).
Synchronous vs asynchronous
| Synchronous | Asynchronous | |
|---|---|---|
| Commit returns after | Followers confirm they have the change | The leader has it locally |
| Durability on leader failure | No data loss | Recent commits can be lost |
| Latency | Higher (waits for the slowest required replica) | Low |
| Availability | Writes stall if the sync replica is down | Unaffected by follower failures |
A common compromise is semi-synchronous: wait for one follower (or a quorum), and stream to the rest asynchronously.
Replication lag and its anomalies
With asynchronous followers, replicas may be seconds (or under load, minutes) behind. That causes visible bugs:
| Anomaly | Example | Fix |
|---|---|---|
| Read-your-own-writes violation | User updates their profile, refreshes, sees the old one (read from a lagging replica) | Read your own recently-written data from the leader, or wait until the replica has caught up to your write's log position |
| Monotonic reads violation | Refreshing shows a new comment, then it disappears (second read hit a staler replica) | Pin each user to one replica |
| Consistent prefix violation | You see an answer before the question it replies to (different partitions lag differently) | Write causally related data to the same partition; causal consistency |
Failover
When the leader dies, a follower must be promoted:
- Detect failure — usually a heartbeat timeout. Too short gives false alarms; too long means longer outages.
- Choose a new leader — ideally the most up-to-date follower, by consensus among nodes or an external coordinator (Patroni with etcd, MySQL Orchestrator, a cloud control plane).
- Reconfigure — clients and other followers switch to the new leader (DNS, a proxy, or a virtual IP).
With async replication, writes the old leader acknowledged but hadn't shipped are lost on failover (GitHub's 2012 MySQL incident led to duplicate primary keys reused from such lost writes).
Multi-leader replication
Several nodes accept writes (typically one per region) and replicate to each other.
- ✓ Local write latency in every region; tolerates a region going offline.
- ✗ Write conflicts: two regions modify the same record concurrently.
Conflict resolution strategies: last-write-wins (by timestamp — simple but silently drops data), application-specific merge logic, or data types that merge automatically — CRDTs (CRDTs). Offline-first apps and collaborative editors are multi-leader systems where each device is a leader.
Leaderless replication (Dynamo-style)
Any replica accepts reads and writes (Cassandra, ScyllaDB, Riak, DynamoDB's internals). The client (or a coordinator) sends each write to N replicas and waits for W acknowledgements; reads query R replicas and take the newest version.
With N = 3, W = 2, R = 2, any read contacts at least one node with the latest write. Tuning W and R trades latency for consistency (W = 1 for fast writes, R = 1 for fast reads).
Stale replicas are repaired by read repair (fix replicas during reads) and anti-entropy (background comparison with Merkle trees). Sloppy quorums and hinted handoff keep writes available when the usual replicas are unreachable, at the cost of weaker guarantees.
Comparing the approaches
| Leader–follower | Multi-leader | Leaderless | |
|---|---|---|---|
| Writes accepted by | One node | One per region/device | Any replica |
| Conflicts | None (single order) | Must be resolved | Resolved by versioning / LWW |
| Consistency | Strong on the leader; lag on followers | Eventual | Tunable (quorums) |
| Failover | Needed (promotion) | Built in | Not needed |
| Examples | Postgres, MySQL, MongoDB | Multi-region MySQL/Postgres setups, CouchDB, offline apps | Cassandra, Riak, DynamoDB |
- Replication gives availability, read scaling and lower latency.
- Leader–follower: one writer, ordered log streamed to followers; sync is safe, async is fast.
- Replication lag breaks read-your-writes, monotonic reads and consistent prefix — design around it.
- Failover needs failure detection, leader election and fencing against split brain.
- Multi-leader needs conflict resolution; leaderless uses quorums with W + R > N.
QA user updates their profile but sees the old value after refreshing. Why, and how do you fix it?medium
The write went to the leader but the read hit an asynchronous replica that hadn't caught up (replication lag). Fix with read-your-writes consistency: route the user's reads to the leader for a short period after they write, or track the write's log position and only read from replicas that have applied it.