Designing Data-Intensive Applications
Ch. 5

Problems with Replication Lag

Asynchronous followers may lag behind the leader, creating stale reads and subtle consistency bugs.

When followers lag seconds behind the leader, users experience anomalies: posting a comment and not seeing it, or seeing newer data followed by older data. These are not failures — they are consequences of eventual consistency.

Diagram
Fixes

Read from leader after writes, use sticky sessions, or wait for follower catch-up before serving reads.

In practice

After posting a tweet, Twitter routes your next read to the leader or a caught-up replica. E-commerce apps using PostgreSQL read replicas often force read-your-own-writes by querying the primary after checkout. HAProxy or AWS ALB sticky sessions keep a user on one replica for monotonic reads.

Instagram at scale

After you post a story, the next feed load must include it — even if replicas lag milliseconds behind. Meta routes post-write reads to the primary or enforces a short read-from-leader window per session.

typescript — Read-your-own-writes routing
// Facebook / Instagram: route reads to primary after posting
async function createPost(userId: string, text: string) {
  const post = await db.primary.posts.create({ data: { userId, text } });
  // Sticky session: next reads hit primary or caught-up replica
  session.set("readFromPrimaryUntil", Date.now() + 5_000);
  return post;
}

async function getFeed(userId: string) {
  const client = session.get("readFromPrimaryUntil") > Date.now()
    ? db.primary
    : db.replica;
  return client.feed.findMany({ where: { userId } });
}
Diagram
Key Takeaways
  • Read-your-own-writes: users must see their own recent changes.
  • Monotonic reads: users never see time go backward across requests.
  • Consistent prefix reads: causal order of writes is preserved.
  • Replication lag is normal — applications must explicitly handle it.
  • Sticky sessions route a user to one replica to improve consistency.
  • Session cookies, Redis-backed sessions, and read-after-write routing fix common lag bugs.
replication lagread-your-own-writesmonotonic readsRediseventual consistency