← Back to SQL, page 24

sql-0468 · Medium mid

A read replica has fallen hours behind the primary. What could cause it, and what would you do?

Common causes are a burst of writes on the primary (bulk loads, mass updates), a replica too weak to replay changes at the primary's rate, long queries on the replica that delay replay (hot_standby_feedback or max_standby_streaming_delay settings), or network limits. Measure lag, find what the replica is waiting on, and reduce the write burst or strengthen the replica.

Full answer

Diagnose:

  • Lag: on the primary, pg_stat_replication shows sent, written, flushed and replayed positions; on the replica, now() - pg_last_xact_replay_timestamp() approximates time lag.
  • Replay conflicts: queries on the replica can block replay when max_standby_streaming_delay allows waiting; check for long reporting queries.
  • Resources: replay is single-threaded for much of the work in PostgreSQL, so a replica with slow disks falls behind under heavy writes.
  • Write bursts: a large batch job or index build on the primary generates WAL faster than replay.

Actions:

  • Throttle or batch bulk jobs on the primary.
  • Move long analytics off the replica or allow them to be cancelled.
  • Give the replica comparable disk performance.
  • Route lag-sensitive reads to the primary while the replica catches up.

Alert on replication lag so it is noticed in minutes, not hours. Described here, not run.

Key points

  • Write bursts outpace replay
  • Replica queries can delay replay
  • Replay needs fast disks
  • Measure lag at both ends
  • Route sensitive reads to the primary meanwhile

Common mistakes

  • Ignoring lag until users report stale data
  • Running heavy reports on a replica configured to wait for them

Follow-ups

  • What does hot_standby_feedback trade off?
  • How would you detect lag from the application?

Tips

  • List causes on both sides