SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Replication Lag

Followers are always a little behind. What users see because of it, and how to cope.

โฑ 13 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Replication lag is the delay between a change being made on the leader and the same change showing up on a follower. In that gap, reading from the follower returns old data.

  • With asynchronous replication the leader does not wait, so followers are always at least a little behind.
  • Lag is usually tiny, but it can grow to seconds or minutes under load, big writes or network trouble.
  • Users notice it in three ways: my own change is missing, data jumps back in time, and replies appear before the question.

02Concept: What is it?

In a leader-follower setup, the leader writes each change to its log and ships the log to the followers. A follower then applies the changes, one after another. This takes time: the message must travel, the follower must read it, and then it must do the work.

If the leader does not wait for the followers (asynchronous replication), it confirms the write to the user straight away. So for a short moment the user has been told "saved", but a follower has not seen the change yet. A read that lands on that follower gets the old value. This is replication lag, and the stale answer it gives is an example of eventual consistency: the follower will catch up, just not instantly.

The gap
โœ๏ธWriteuser posts
โ†’โ†“t = 0
๐Ÿ‘‘Leaderhas it
โ‡ขโ‡ฃlag
๐Ÿ“‹Followerhas it later
โ†a read here is stale
๐Ÿ‘€Reader
The write reaches the leader at once and the follower a little later. A read in between is stale.
๐Ÿง Lag is normal, surprises are the problem
You cannot remove lag in an async system. What you can do is design so that users are not surprised by it: show them their own changes, and never show time going backwards.

03Real-Life Example

๐ŸตThe Comment That Vanished
You write a comment on a video and press Post. The page says "Posted!". You refresh, and your comment is gone. You post again, and now there are two. What happened? Your Post went to the main server. Your refresh was answered by a helper server that had not yet received the news. A moment later the helper caught up, and both comments appeared.
The vanished comment
Replication lag
The main server that took your comment
The leader
The helper server that answered your refresh
A follower
The delay before the helper got the news
Replication lag
Your comment missing after refresh
A read-your-writes failure
Seeing it, then not seeing it
A monotonic-reads failure
Always asking the main server after you post
Read from the leader after a write
Asking the helper only if it knows your comment
Reading by log position

04Why Do We Need It?

๐Ÿ˜•Avoid confused users
A missing comment or a vanished order makes people post twice or lose trust.
๐ŸงชAvoid hard-to-find bugs
Code that reads from a replica right after writing works in tests and fails in production.
โš–๏ธChoose speed or freshness
Knowing the lag helps you pick which reads can be stale and which must be fresh.
๐Ÿ“ˆScale reads safely
Followers are how you scale reads. Handling lag is the price of using them.
๐ŸšจSpot trouble early
A growing lag is an early warning of an overloaded follower or a broken link.
๐Ÿ—ฃ๏ธInterview favourite
Read-your-writes and monotonic reads are classic questions.
Followers make reads fast and scalable. Lag is the cost, so plan which reads can live with it.

05Where Do We Use It?

๐Ÿ˜SQL read replicas
PostgreSQL and MySQL replicas run a little behind the primary. Cloud databases show the lag as a metric.
๐ŸƒDocument stores
Reading from a secondary in MongoDB can return older data than the primary.
๐ŸŒCross-region replicas
A replica across an ocean has a bigger lag because of distance.
๐Ÿ“ŠReporting replicas
A replica for heavy reports can lag during a long query.
๐ŸงญSearch and cache copies
Search indexes and caches fed by change events lag the database too.
๐Ÿ“จEvent pipelines
A consumer that is behind on a stream has the same kind of lag, measured in messages.

06Types / Parts / How It Works

Three things users notice

ProblemWhat the user seesPlain-English guarantee that fixes it
Read-your-writes failureI posted a comment and it is not thereRead-your-writes: you always see your own changes
Monotonic-reads failureI saw the comment, reloaded, and it was goneMonotonic reads: time never goes backwards for you
Consistent-prefix failureA reply shows up before the question it answersConsistent prefix: you see writes in the order they happened
Time going backwards
Reload 1
๐Ÿ“‹Fast followerhas the comment
๐Ÿ‘€User sees it
Reload 2
๐Ÿ“‹Slow followernot yet
๐Ÿ‘€Comment gone!
Reload 1 hits a fast follower and reload 2 hits a slow one.

Where lag comes from

CauseWhy it slows a follower
Heavy write loadThe follower must apply as many changes as the leader, and may be slower
One huge transactionA single big change takes a long time to replay
Long queries on the followerA big report can hold up the work of applying changes
Network distance or troubleChanges arrive late, or in bursts
A weaker follower machineIt cannot apply changes as fast as the leader makes them
๐Ÿ“Lag is measured in two ways
Either as time (the follower is 3 seconds behind) or as position in the log (it is 12,000 log entries behind). Both are useful. Position is exact, time is easier to read.
VisualizerPost a comment, then reloadSet a large lag on follower 2, choose Any replica and move the reload times. Then switch to the leader, leader-for-a-while and log-position rules and see which fixes work.
How are reads routed?

Each reload goes to whichever replica the balancer picks (here: a fixed rotation, follower 1 then follower 2).

The comment is posted at second 10 (log position 42). Bar = the comment is in that replica. Markers show the two reloads.
Leader
Follower 1
1
Follower 2
2
0 s10 s20 s
Reload 1
missing
Follower 1 at 11s
Reload 2
missing
Follower 2 at 14s
Reads on leader
0 of 2
more means more load
Your own comment was missing on both reloads. This is a read-your-writes failure: you posted, then read from a replica that had not caught up.

Reload 1: no rule, so whichever replica was picked answers. Reload 2: no rule, so whichever replica was picked answers. A simplified story with fixed lags and a fixed rotation between followers (no random numbers). Real lag changes from second to second, and the log position is an illustrative number.

07How to Use It / Steps / Implementation

Living with lag

  1. 1
    Decide which reads must be fresh
    A user's own profile after an edit: fresh. A public feed or a count on a dashboard: a few seconds old is fine.
  2. 2
    Read your own writes from the leader
    After a user writes, send their reads to the leader for a short time (longer than the normal lag).
  3. 3
    Or track the log position
    Remember the position of the user's last write (in a cookie or session). Only read from a replica that has reached it, otherwise use the leader.
  4. 4
    Keep a user on one replica
    Pick a replica by hashing the user id. This gives monotonic reads, because one replica never goes back in time.
  5. 5
    Keep related writes in order
    If an answer depends on a question, store them in the same shard so they are replayed in order.
  6. 6
    Use semi-sync for critical data
    If a confirmed write must be on a second machine, wait for one follower.
  7. 7
    Watch the lag
    Track seconds behind the leader for every replica. Alert when it passes your limit, and take slow replicas out of the read pool.
๐Ÿ’กCheap trick for a small app
After a write, send the user to a page that shows the new data from the leader, or show the result straight from the write response. The user sees it at once, even before any replica has it.
โš ๏ธCross-device and cross-tab
Read-your-writes is harder when the same user has two devices. A cookie on the phone does not tell the laptop. Store the last-write position on the server, tied to the user.
Typical healthy lag targetwell under a second (illustrative)

08Key Terms to Know

TermMeaning in easy words
Replication lagHow far a follower is behind the leader, in time or log entries
Asynchronous replicationThe leader confirms a write without waiting for followers
Eventual consistencyFollowers will catch up if writes stop, but not instantly
Stale readA read that returns old data
Read-your-writesYou always see your own recent changes
Monotonic readsYou never see data go back to an older state
Consistent prefixYou see writes in the order they happened
Log position (LSN)A number that marks how far along the replication log is
Semi-synchronousThe leader waits for one follower before confirming
Read replicaA follower used to answer reads
Sticky replicaSending one user's reads to the same replica every time

09Pros, Cons and Trade-offs

โœ… Pros
  • Async replication keeps writes fast and the leader free
  • Followers can serve many reads
  • Lag handling lets you keep scale without confusing users
  • Cheap tricks (leader-after-write, sticky replica) fix most surprises
  • Position tracking is exact and gives a clear guarantee
โš ๏ธ Cons
  • Reads can be stale
  • Surprises are hard to reproduce in tests
  • Sending reads to the leader reduces the benefit of replicas
  • Position tracking adds code and state
  • Cross-device read-your-writes needs server-side state

Trade-offs

ChoiceWe gainWe lose
Read from any replicaMaximum read scaleStale reads and time going backwards
Always read from the leaderAlways freshNo read scale, and the leader gets busy
Leader for a short time after a writeRead-your-writes, simple to buildA guess about how long the lag lasts
Read by log positionExact guarantee, still uses replicasMore code and a position to carry around
Sticky replica per userMonotonic readsA slow replica hurts its users, and failover must move them
Synchronous or semi-syncNo stale reads for those writesSlower writes and lower availability

10Common Problems and Mistakes

Common mistakes

  1. Reading from a replica right after a write. The classic bug: it works on a laptop with one database and fails with replicas.
  2. Guessing the lag. "It is always under 100 ms" is true until a big query runs. Measure it.
  3. No lag alerts. A replica can be minutes behind and nobody knows until a user complains.
  4. Using replicas for checks that need fresh data. A stock check or a uniqueness check on a replica can be wrong.
  5. Random replica per request. A user bounces between replicas and sees data go back and forth.
  6. Treating a replica as a backup. A bad delete is copied to the replicas too.

Things to watch

โณLag spikes
A big batch job or a long report can push lag from milliseconds to minutes.
๐Ÿ”ŒBroken link
If the link drops, lag grows without limit until it returns.
๐Ÿ”€Failover and lost writes
If the leader fails with async replication, the newest writes that were not copied may be lost.
๐ŸงฎCounts and totals
A number read from a lagging replica can disagree with the page that just wrote it.

11Real-World Examples

โ˜๏ธCloud read replicas
Managed databases publish a replica lag metric so you can alert on it.
๐Ÿ“ฑSocial feeds
A post may take a moment to appear for your followers, but you should see your own post at once.
๐Ÿ›’Shopping carts
After adding an item you must see it. Stock counts can be a little stale.
๐ŸฆBanking
Balance checks that decide a payment use the leader or a synchronous copy, not a lagging replica.
๐Ÿ“ŠDashboards
A few seconds of lag is fine, so they run on replicas to protect the main database.
๐ŸŒGlobal apps
A replica near the user gives fast reads, and the cost is more lag from the leader.
๐Ÿ“Note
Typical lag values vary widely by product, hardware and load. Measure your own system rather than relying on a rule of thumb.
Mini case: post then reload
๐Ÿ“Post
โ†’โ†“write
๐Ÿ‘‘Leader
โ‡ขโ‡ฃlog, async
๐Ÿ“‹F1
๐Ÿ“‹F2
Fresh (leader) Maybe behind (followers)
Reads right after a write go to the leader. Later reads use a follower.

12Related Topics to Read Next

Replicationโ†’

The basics of leaders, followers, sync and async.

Replication Modelsโ†’

Single-leader, multi-leader and leaderless, and how lag shows up in each.

Consistency Modelsโ†’

The names for the guarantees: read-your-writes, monotonic reads and more.

Write-Ahead Log (WAL)โ†’

The log that followers replay, and where the log position comes from.

Sticky Sessionsโ†’

The same idea as a sticky replica: keep a user on one machine.

Heartbeatsโ†’

How a broken link or a slow follower is noticed.

Change Data Capture (CDC)โ†’

Other copies (search, cache) fed from the log have lag too.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: the delay before a follower has the leader's change.
  • โœ”Cause of the problem: async replication plus reads from followers = stale reads.
  • โœ”Three surprises: own change missing, time going backwards, reply before question.
  • โœ”Fixes: leader after write, log position, sticky replica, same-shard writes.
  • โœ”Strong option: semi-sync or sync for critical data, at the cost of speed.
  • โœ”Causes: heavy load, huge transactions, long follower queries, network.
  • โœ”Monitor: seconds behind the leader for every replica, with alerts.
  • โœ”One line: โ€œReplicas are a little behind, so make sure users never see that.โ€
โ† Previous
Replication Models
Next โ†’
Quorum (R + W > N)