Module 5 / When one database isn't enough / Replication lag

Lesson9 minModule 5 · lesson 2 of 8

Replication lag

When a copy is slightly behind.

A customer places an order, the app shows 'Order confirmed', and the next screen loads the order history from a replica. The order is missing. The customer panics and orders again. Nothing is broken: the write reached the primary, but the replica has not replayed it yet. The delay between a write on the primary and its visibility on a replica is replication lag.

Lag is usually milliseconds, but it is not a constant. A burst of writes, a long-running query on the replica, a slow network link or a replica on weaker hardware can push lag to seconds or even minutes. With asynchronous replication, the default for most setups, the primary confirms a write without waiting for any replica, so the app has no built-in guarantee about what a replica currently shows.

Async lag window

Press play and watch the reads after each write. Which replica reads come back stale, and why does the read at second 5 come back fresh? Then raise the lag to 8 and see how many more reads go stale.

Replication
  1. t=0sWrite to primary
  2. t=2sRead from replica
  3. t=2sRead from primary
  4. t=4sRead from replica
  5. t=5sRead from replica
  6. t=10sWrite to primary
  7. t=12sRead from replica
  8. t=16sRead from replica
0 of 8 events

In the simulator a replica read is stale if it happens less than lag seconds after the latest write. The read at second 5 is exactly five seconds after the write at second 0, so the replica has caught up. The read from the primary is always fresh, which hints at the main fix: route reads that must see a recent write to the primary.

Common lag anomalies and their fixes

Step 1 of 4

Read-your-writes violated

A user saves a profile change and immediately sees the old one. Fix: for a short window after a user writes (say 10 seconds), serve that user's reads from the primary, or remember the write's log position and only read from a replica that has reached it.

Question 1

A user updates their delivery address and the next page shows the old one. What is the most targeted fix?

Question 2

Why can a user see newer data on one refresh and older data on the next?

Your turn

List three screens in a food-delivery app and decide for each whether a replica read is fine or must go to the primary. Give a one-line reason for each.

Stuck? Ask: does the user expect to see the thing they just changed?

What to remember

  1. Replication lag is the delay before a write on the primary appears on a replica.

  2. Async replication gives no freshness guarantee; lag can spike under load.

  3. Fix anomalies with read-your-writes routing and sticky replicas.

  4. Monitor lag and remove replicas that fall too far behind.