Overview

Check replication lag before routing any read that follows a user’s own write to a replica; stale reads surface as bugs users can see. Set the alert threshold from the application’s staleness tolerance: near zero for inventory and finance, minutes for analytics.

Rules

  • Measure on the primary from pg_stat_replication: write_lag, flush_lag, and replay_lag are intervals, and pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) gives bytes behind. The time columns go NULL once a standby is caught up and idle.
  • Causes: the replica’s I/O or CPU cannot keep up with the write rate, network bandwidth, and replay conflicts with long queries on the standby.
  • A stalled standby with a replication slot makes the primary keep WAL until the disk fills. max_slot_wal_keep_size defaults to -1 (unlimited); PostgreSQL 18 adds idle_replication_slot_timeout (default 0, disabled). Alert on slot-retained WAL as well as lag.
SELECT application_name, replay_lag,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_behind
FROM pg_stat_replication;