The PostgreSQL administration field guideField notes · Runbooks · Free certification
advanced22 minute lesson

Replication, WAL, and lag

Separate WAL generation, transport, flush, and replay so a lag number becomes a diagnosable pipeline.

Progress stays on this device

Mental model

Physical streaming replication is a pipeline. The primary generates WAL, a sender transmits it, the standby receives and writes it, and the recovery process replays it. Lag can therefore mean missing transport, slow storage, blocked or slow replay, deliberate delay, or simply no recent commit timestamp. Compare WAL positions and rates before assigning a cause.

What healthy usually looks like

  • Connected standbys remain in the expected state and their WAL gaps converge after bursts.
  • Receive and replay positions advance at rates that can catch up with WAL generation.
  • Replication slots retain bounded WAL and inactive slots have explicit ownership.

Ask the database a bounded question

Diagnostic query

Inspect the primary-side replication pipeline

Compare sender state, lag intervals, and WAL-position gaps for every connected standby.

SELECT
  application_name,
  client_addr,
  state,
  sync_state,
  write_lag,
  flush_lag,
  replay_lag,
  pg_size_pretty(
    pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)
  ) AS replay_byte_gap
FROM pg_stat_replication
ORDER BY application_name;
low observation cost

Read the output

  1. Measure WAL generation, receive, and replay rates across an interval; a large gap that is shrinking is different from a smaller gap that grows continuously.
  2. Inspect `pg_stat_wal_receiver` on the standby and `pg_stat_replication` on the primary to see both sides of transport.
  3. Check hot-standby conflicts, long standby queries, storage latency, recovery settings, and deliberate replay delay before restarting anything.

Common traps

  • Restarting the standby before separating a disconnected receiver from slow or blocked replay.
  • Treating the lag interval as a precise completion estimate.
  • Ignoring inactive replication slots while retained WAL consumes primary disk.

Check your reasoning

The standby receive position advances, but its replay position does not. Where is the investigation now focused?

Related runbooks

Sources