Replication Lag and Consistency Anomalies

Reading from asynchronous replicas can show users old data. The three anomalies that lag causes (missing your own write, going back in time, effects before causes) and the guarantees that fix each.

Overview

With asynchronous replication, a follower applies each change a little after the leader. That delay is replication lag. The PostgreSQL documentation says it is typically under one second when the standby can keep up. Under heavy writes, a slow network or a busy replica it can grow to seconds or minutes, and nothing in asynchronous replication puts an upper limit on it.

If every copy eventually catches up once writes stop, the system is eventually consistent. That promise says nothing about what a user sees in the meantime. Three anomalies show up in practice, and each has its own guarantee and fix.

  • Missing own write: the user saves a comment, reloads, and the comment is gone. The guarantee that prevents it is read your writes.
  • Going back in time: the user sees a new reply, reloads, and the reply is gone. The guarantee that prevents it is monotonic reads.
  • Effect before cause: the user sees an answer before the question it answers. The guarantee that prevents it is consistent prefix reads.

Where lag comes from

Between the leader's commit and the follower's replay there is a window, and a read from the follower inside that window returns the old value. Here is one write and one read falling into it.

  • The user writes x = 2 to the leader.
  • The leader commits and answers OK.
  • The user reads x from a follower.
  • The follower has not replayed the change yet, so it answers x = 1, the old value.
  • The leader's change x = 2 then reaches the follower, and once it is replayed the follower shows x = 2.

Four things stretch that window.

  • Write bursts: the follower replays changes more slowly than the leader produces them.
  • Network between sites: changes take longer to arrive, especially across regions.
  • Long queries on the follower: in PostgreSQL, replay can pause for a query that conflicts with it, up to max_standby_streaming_delay (30 seconds by default) before the query is canceled.
  • Weaker follower hardware: a slower disk or CPU than the leader.

Key concepts

  • Replication lag
  • Eventual consistency
  • Read your writes
  • Monotonic reads
  • Consistent prefix reads
  • Session guarantees
  • Bounded staleness
  • Sticky routing

Interview questions

  • A user posts a comment, refreshes, and the comment is missing. What is happening, and how do you fix it?
  • What is the difference between monotonic reads and consistent prefix reads?
  • Does pinning a user to one replica give read your writes?
  • How would you monitor and limit replication lag in production?
  • Is eventual consistency enough for a social feed?

Sign up free to read the full topic

More DDIA topics

Start free on Cariara · Coding problems · System design studio