Replication: leader-follower, multi-leader, leaderless
Explain replication lag and choose a replication model.
By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.
In short
Replication keeps copies of data on several nodes for availability, durability and read scaling. The models differ in who accepts writes: one leader, several leaders, or any replica.
Explained simply
Replication means keeping the same data on more than one machine. If one machine dies, another still has the data. If many people read at once, several machines can share the work. And if your users live on different continents, a copy near each group makes reads faster.
The simplest setup has one leader and some followers. Only the leader accepts changes. It writes each change to a log, a list of every change in order, and sends that log to the followers, which replay it. It is like a teacher writing on the board while students copy it into their notebooks.
Copying takes time. The gap between the leader having a change and a follower having it is called replication lag. It is usually milliseconds, but under heavy load it can grow to seconds or minutes. During that gap, a reader asking a follower can see old data.
Other setups let more than one machine accept writes. That helps when the leader is far away or down, but two people can now change the same thing at the same time in different places. Then the system must decide which change wins, and that is where most of the hard problems are.
Press Play on a diagram to walk through it one step at a time.
- 1Client write
All writes go to the leader
- 2Leader commits
Appends change to its replication log
- 3Log shipped
Followers receive changes sync or async
- 4Followers apply
Copies catch up after some lag
- 5Reads scale out
Read queries can hit followers
- One node takes writes
- Simple, no write conflicts
- Failover needed if leader dies
- PostgreSQL, MySQL
- Leader per region
- Local writes, low latency
- Write conflicts to resolve
- Multi-region apps
- Any replica takes writes
- Quorum reads and writes
- High availability
- Cassandra, Dynamo
- User to Leader: Change name to Ana1Change name to Ana
- Leader to User: Saved2Saved
- User to Follower: Load profile page3Load profile page
- Follower to User: Name is still Anna (not replayed yet)4Name is still Anna (not replayed yet)
- Leader to Follower: Log record arrives 2 s later5Log record arrives 2 s later
In depth
Synchronous, asynchronous and semi-synchronous
With synchronous replication the leader waits for a follower to confirm a write before telling the client it succeeded. No acknowledged write is lost if the leader dies, but every write is as slow as the slowest waited-for follower, and if that follower is down, writes stop.
With asynchronous replication the leader confirms immediately and ships changes in the background. Writes are fast, but anything not yet shipped is lost if the leader fails.
Most production setups choose a middle path: wait for one follower (or a quorum) and let the rest catch up asynchronously. PostgreSQL does this with synchronous_standby_names, for example ANY 1 (replica_a, replica_b), and the synchronous_commit setting. MySQL offers semi-synchronous replication, where the source waits until at least one replica has received the change.
- Sync: no lost acknowledged writes, slower, blocked by a dead follower
- Async: fast, may lose the last writes on failover
- Semi-sync: wait for one, the rest catch up
- Client to Leader: UPDATE balance1UPDATE balance
- Leader to Sync follower: Ship log record2Ship log record
- Sync follower to Leader: Received and flushed3Received and flushed
- Leader to Client: Commit OK4Commit OK
- Leader to Async follower: Ship log record later5Ship log record later
What replication lag does to users
When reads go to followers, lag shows up as strange behaviour. Read-your-writes breaks: a user edits their profile, the page reloads from a follower, and the old name appears. Monotonic reads break: two refreshes hit two followers with different lag, and a new comment appears, then vanishes. Consistent prefix breaks: on a partitioned system, you see an answer before the question it replies to.
Fixes are cheap if you plan for them. Read data the user just changed from the leader for a few seconds. Pin each user to one follower so their view never goes backwards. Or remember the log position of the user's last write and only read from a follower that has replayed at least that far. In PostgreSQL, pg_current_wal_lsn() on the primary and pg_last_wal_replay_lsn() on a replica give those positions.
- Read-your-writes: route recent writers to the leader
- Monotonic reads: stick a user to one replica
- Monitor lag and pull replicas out of rotation when it grows
Failover and split brain
When the leader dies, a follower must take over. Failover has three steps: notice the failure (usually a missed heartbeat timeout of some seconds), choose the follower with the most recent data, and send all writes to it. Tools like Patroni for PostgreSQL and Orchestrator for MySQL automate this; Patroni, for example, keeps the leader lock in a consensus store such as etcd.
Two things can go wrong. With asynchronous replication, the new leader may lack the old leader's last writes, which are then lost or conflict when the old leader returns. Worse is split brain: the old leader was only cut off, not dead, and keeps accepting writes while the new one does too. Systems prevent this with fencing: the old leader must lose its lease, be shut off, or have its writes rejected before the new one starts.
- 1Heartbeats stop
Leader misses its timeout
- 2Agree it is down
Coordinator or quorum decides
- 3Pick best follower
The one with the newest log position
- 4Fence the old leader
Revoke its lease or shut it off
- 5Promote and repoint
Clients and followers use the new leader
Multi-leader: local writes, shared conflicts
In a multi-leader setup each region (or each offline device) has its own leader that accepts writes, and the leaders replicate to each other asynchronously. Users get fast local writes, and a region can keep working if the link to others breaks. Calendar and note apps that work offline are a form of this.
The price is write conflicts: two leaders change the same record before seeing each other's change. Common resolutions are last-write-wins (keep the change with the latest timestamp, silently dropping the other), merging fields, CRDTs (data types like counters and sets designed to merge automatically), or keeping both versions and asking the user or app to choose.
A practical trick is to avoid conflicts: route all writes for one user or one document to the same home region, so conflicts only happen during failover.
Leaderless: any replica takes the write
Dynamo-style stores such as Cassandra and Riak have no leader. The client, or a coordinator node, sends each write to all N replicas of a key and treats it as successful when W of them confirm. Reads ask R replicas and take the newest version. If W + R > N, at least one replica in every read has the latest acknowledged write.
Replicas that missed a write are repaired in three ways. Read repair: during a read, stale replicas are updated with the newest value. Hinted handoff: a neighbour stores the write for a down node and passes it on when the node returns. Anti-entropy: a background job compares replicas, often with Merkle trees (hash trees that find differing ranges quickly), and copies missing data. Leaderless designs stay writable through node failures, but conflicting concurrent writes still need a rule.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Explain leader-follower replication~45m
- 2Explain replication lag effects~45m
- 3Compare multi-leader and leaderless models~45m
- 4Choose a replication model~45m
Key points
- Asynchronous replication is fast but can lose recent writes on failover.
- Replication lag means followers may serve stale reads.
- Read-your-writes can be ensured by reading from the leader after a write.
- Multi-leader and leaderless systems need conflict resolution.
Key terms
Tap a card to flip it. 0/5 known
Examples
Measuring lag on a PostgreSQL replica set
Your dashboard shows some users see stale order statuses. Step 1: on the primary, list replicas and their lag. replay_lag shows how far behind each replica is in time. Step 2: on a replica, check how old its last replayed transaction is. Step 3: if lag is regularly over a second, route order-status reads for 10 seconds after a change to the primary, and alert when any replica falls more than 30 seconds behind so the load balancer can drop it.
-- on the primary
SELECT client_addr, state, sync_state,
replay_lsn, replay_lag
FROM pg_stat_replication;
-- on a replica
SELECT now() - pg_last_xact_replay_timestamp() AS lag;Lost writes after an asynchronous failover
A primary in region A replicates asynchronously to region B with about 500 ms of lag. It accepts 2,000 writes per second. Step 1: the primary crashes. Step 2: the failover tool promotes B. Step 3: about 0.5 s x 2,000 = 1,000 acknowledged writes never reached B. Users were told those orders succeeded. Step 4: when A comes back, its extra writes conflict with new writes on B and must be reconciled by hand. The lesson: for data like payments, use at least one synchronous follower, and accept the extra write latency.
Quick reference
- Leader-follower: one writer, simple, the default in PostgreSQL and MySQL
- Async replication loses the unshipped tail of writes on failover
- Semi-sync: wait for one follower, the rest catch up in the background
- Read-your-writes: send a user's reads to the leader for a few seconds after they write
- pg_stat_replication.replay_lag shows how far each PostgreSQL replica is behind
- Split brain is prevented by fencing: leases, STONITH, or rejecting stale-term writes
- Multi-leader and leaderless setups need a conflict rule: LWW, merge, or CRDT
- Leaderless repair: read repair, hinted handoff, anti-entropy with Merkle trees
Common mistakes
- Reading from a lagging follower right after a write, confusing users.
- Split brain: two nodes both believing they are leader.
- Relying on last-write-wins and silently losing concurrent updates.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
For each feature, say whether reading from a lagging follower is acceptable: (a) a product's like count, (b) a user's own just-posted comment, (c) the balance shown before a transfer.
- Exercise 2medium
Write pseudocode for a read router that guarantees read-your-writes using the leader's log position (LSN) stored in the user's session.
- Exercise 3hard
Design replication for a notes app used offline on phones and laptops that syncs when online. Choose a model, explain how conflicts are handled for (a) note text and (b) a set of tags.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is replication the same as a backup?
- No. Replication copies every change, including mistakes like a DROP TABLE, to all replicas within seconds. Backups and point-in-time recovery let you go back to before the mistake.
- How many replicas should I run?
- A common setup is three copies of the data: one leader and two followers, ideally in different availability zones. That survives one failure while keeping a spare during repairs.
- What is a normal replication lag?
- In the same region, usually well under a second. Long transactions, heavy write bursts, slow replica disks or cross-region links can push it to seconds or more, so monitor it and alert on it.