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, andreplay_lagare intervals, andpg_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_sizedefaults to -1 (unlimited); PostgreSQL 18 addsidle_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;Related
- read-replica: the destination that lags.
- write-ahead-log: the stream whose backlog is the lag.
- eventual-consistency: the guarantee lag implies.
- postgres-replication: monitoring and slots.
- postgres: the Postgres reference.