← Back to PostgreSQL, page 5

postgresql-0090 · Hard senior

Users report that they sometimes do not see their own changes right after saving. The app reads from replicas. Diagnose and fix it.

Streaming replicas apply WAL asynchronously, so a read routed to a replica shortly after a write on the primary can return old data. Measure lag with pg_stat_replication on the primary or the replay timestamp on replicas. Fix it by routing a user's reads to the primary for a short time after they write, by waiting for the replica to reach the write's LSN, or by using synchronous replication with remote_apply for critical paths.

Full answer

How to confirm: on the primary, pg_stat_replication shows write_lag, flush_lag and replay_lag per replica; on a replica, now() - pg_last_xact_replay_timestamp() approximates delay (it grows when the primary is idle, so read it together with traffic). Correlate spikes with heavy writes such as batch jobs, long queries on the replica that conflict with replay, or network issues.

Fix options, from simplest:

  1. Read-your-writes routing: after a user writes, send their reads to the primary for a few seconds (track a timestamp in the session or a cookie).
  2. LSN waiting: return pg_current_wal_lsn() after the write, and before reading on a replica, check pg_last_wal_replay_lsn() >= that LSN, falling back to the primary if it is behind.
  3. Synchronous replication with synchronous_commit = remote_apply for the specific transactions that need it, accepting higher write latency.
  4. Reduce lag itself: tune replicas so long queries do not delay replay (hot_standby_feedback and max_standby_streaming_delay trade-offs), spread batch writes, and size replica hardware like the primary.

Also review which reads need freshness at all: dashboards and search can tolerate seconds of lag; a profile page right after saving cannot. Not run here, because it needs a replica.

Key points

  • Replicas lag the primary asynchronously
  • Measure with pg_stat_replication
  • Route reads after writes to the primary
  • LSN checks give precise freshness
  • remote_apply for critical paths

Common mistakes

  • Sending all reads to replicas blindly
  • Treating replication lag as constant

Follow-ups

  • What do hot_standby_feedback and max_standby_streaming_delay trade off?
  • How would a proxy handle read-your-writes?

Tips

  • Mention LSN comparison