Course contentsShow
← Databases & SQL
Lesson 828 of 1,9537. Transaction ManagementFree lesson

Replica Lag and Read Consistency

Manage the trade-offs of reading stale data from secondary replicas vs blocking for strict consistency.

In this lesson, you will learn how to navigate the trade-off between the speed of reading from secondary replicas and the guarantee that your data is perfectly up-to-date.

The Reality of Asynchronous Replication

When we use asynchronous replication, the primary database confirms a transaction as successful before that change has been fully applied to the secondary replicas. This creates a small window of time known as replica lag. If a user performs a write on the primary and immediately tries to read that data from a secondary, they might see "stale" data because the replication log hasn't arrived yet.

The Trade-off: Performance vs. Freshness

You have two main paths to manage this:

  1. Eventual Consistency (Accepting the Lag): You direct read traffic to secondary replicas to keep the primary database performant. The trade-off is that users might occasionally see data that is a few milliseconds (or seconds) old. This is perfectly acceptable for many applications, such as a social media feed or a product catalog.
  2. Strict Consistency (Blocking for Freshness): If your application requires that a user always sees their own latest writes (like a banking balance), you cannot risk reading stale data. You have two options here:
    • Read from Primary: Force all critical reads to go directly to the primary node. This ensures consistency but increases the load on the primary, potentially creating a bottleneck.
    • Synchronous Replication: Require the primary to wait for the replica to acknowledge the write before committing. As we learned in previous lessons, this drastically increases write latency and makes your system vulnerable to network partitions.

Conceptualizing the Flow

Imagine a user updates their profile picture:

-- 1. Write to Primary (Success!)
UPDATE users SET profile_pic = 'new.jpg' WHERE user_id = 101;

-- 2. Immediate read from a Secondary Replica
-- If lag > 0, this might return the old image!
SELECT profile_pic FROM users WHERE user_id = 101;

To solve this, developers often implement "read-your-writes" logic, where the application remembers that a write just occurred and forces the very next read to the primary, while allowing subsequent reads to return to the replicas.

Key Takeaway: You must choose between the high performance of reading from lag-prone secondary replicas and the strict consistency of blocking reads or forcing traffic to the primary node.