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.

Advanced 5 min readLesson 13 of 14 Interview Q&A

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):

writesreadsWAL streamWAL streamApplicationLeader (primary)all writesFollower 1readsFollower 2reads
  • 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

SynchronousAsynchronous
Commit returns afterFollowers confirm they have the changeThe leader has it locally
Durability on leader failureNo data lossRecent commits can be lost
LatencyHigher (waits for the slowest required replica)Low
AvailabilityWrites stall if the sync replica is downUnaffected 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:

AnomalyExampleFix
Read-your-own-writes violationUser 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 violationRefreshing shows a new comment, then it disappears (second read hit a staler replica)Pin each user to one replica
Consistent prefix violationYou 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:

  1. Detect failure — usually a heartbeat timeout. Too short gives false alarms; too long means longer outages.
  2. 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).
  3. 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.

W+R>N  ⇒  every read quorum overlaps every write quorumW + R > N \;\Rightarrow\; \text{every read quorum overlaps every write quorum}

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–followerMulti-leaderLeaderless
Writes accepted byOne nodeOne per region/deviceAny replica
ConflictsNone (single order)Must be resolvedResolved by versioning / LWW
ConsistencyStrong on the leader; lag on followersEventualTunable (quorums)
FailoverNeeded (promotion)Built inNot needed
ExamplesPostgres, MySQL, MongoDBMulti-region MySQL/Postgres setups, CouchDB, offline appsCassandra, Riak, DynamoDB
Key takeaways
  • 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.
Interview questions
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.