Sub topic 7
Checking replication health and measuring lag
This chapter assumes you have a working primary and at least one hot standby, as built in the previous chapters. It also assumes you can use psql, and that you know what a log sequence number (LSN) is. The queries below use column names from PostgreSQL 13 and later. Most also work on PostgreSQL 10 to 12.
A standby that is connected can still be far behind. A standby that looks quiet can be healthy. You need to know which numbers to read and what each one means.
The four positions of a WAL record
A WAL record passes through several stages on its way to being visible on a standby. The primary tracks each stage for every connected standby and reports it in the view pg_stat_replication.
The four columns always satisfy sent_lsn >= write_lsn >= flush_lsn >= replay_lsn. The gap between two neighbors tells you where the delay is:
- A large gap between the primary's current position and
sent_lsnmeans the walsender is not keeping up. Look at the primary's load or the sender's connection. - A large gap between
sent_lsnandwrite_lsnorflush_lsnpoints to the network or the standby's disk. - A large gap between
flush_lsnandreplay_lsnmeans the standby has the data but is slow to apply it. Long-running queries, replay conflicts, or a paused replay are the usual causes.
Reading pg_stat_replication on the primary
Run this on the primary. Each connected standby (or pg_basebackup client using streaming) has one row.
SELECT application_name, client_addr, state, sync_state,
sent_lsn, replay_lsn, replay_lag
FROM pg_stat_replication;The most useful columns are:
| Column | Meaning |
|---|---|
| `application_name` | The name the standby set in `primary_conninfo`. It is also the name matched by `synchronous_standby_names`. |
| `state` | `startup`, `catchup`, `streaming`, `backup`, or `stopping`. |
| `sync_state` | `async`, `potential`, `sync`, or `quorum`. |
| `sent_lsn`, `write_lsn`, `flush_lsn`, `replay_lsn` | The four positions described above. |
| `write_lag`, `flush_lag`, `replay_lag` | Time intervals, measured by the primary. |
| `reply_time` | When the standby last sent a status message. |
A healthy standby normally shows state = streaming. The catchup state is normal right after the standby connects, while it works through WAL it missed. If a standby stays in catchup for a long time, it is receiving WAL slower than the primary produces it.
If a standby you expect is missing from the view, it is not connected. Check the standby's log, primary_conninfo, pg_hba.conf on the primary, and max_wal_senders.
Byte lag and time lag
There are two ways to express lag, and they answer different questions.
Byte lag is the distance in WAL bytes between two LSNs. It tells you how much data the standby would lose if the primary failed now (for flush_lsn), or how much work it still has to apply (for replay_lsn). Use pg_wal_lsn_diff(), which subtracts one LSN from another:
-- On the primary
SELECT application_name,
pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn) AS flush_lag_bytes,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS replay_lag_size
FROM pg_stat_replication;Time lag is how long a commit waits before it shows up on the standby. The columns write_lag, flush_lag, and replay_lag report this. The primary measures them by noting when it sent WAL and when the standby reported reaching each stage. They show how recent commits were delayed. They are not a live clock of how stale the standby is right now.
Byte lag and time lag can disagree. A bulk load can produce gigabytes of WAL in seconds, so byte lag jumps while time lag stays small if the standby keeps up. A slow single-row workload can show a large time lag with a tiny byte lag.
Checking from the standby
The standby has its own view of progress. Run this on the standby:
SELECT pg_is_in_recovery(),
pg_last_wal_receive_lsn(),
pg_last_wal_replay_lsn(),
pg_last_xact_replay_timestamp();pg_is_in_recovery()returnstrueon a standby andfalseon a primary. Scripts use it to check which role a server currently has.pg_last_wal_receive_lsn()is the last WAL position received and flushed to disk by the walreceiver.pg_last_wal_replay_lsn()is the last position applied to the data files.pg_last_xact_replay_timestamp()is the commit time of the last transaction replayed.
The difference between receive and replay positions is the replay backlog on the standby:
-- On the standby
SELECT pg_wal_lsn_diff(pg_last_wal_receive_lsn(),
pg_last_wal_replay_lsn()) AS replay_backlog_bytes;Do not call pg_current_wal_lsn() on a standby. It raises an error because WAL is not being written there. Use pg_last_wal_receive_lsn() or pg_last_wal_replay_lsn() instead.
The view pg_stat_wal_receiver describes the connection from the standby's side:
-- On the standby
SELECT status, sender_host, slot_name,
written_lsn, flushed_lsn,
last_msg_send_time, last_msg_receipt_time
FROM pg_stat_wal_receiver;If this view returns no rows, the walreceiver process is not running. The standby may be replaying archived WAL only, or the connection may have failed. The standby's log will say which.
A time-lag query that works on an idle primary
A common way to estimate lag on the standby is now() - pg_last_xact_replay_timestamp(). This has a flaw. If the primary has no write activity, the last replayed commit gets older and older, so the number grows even though the standby is fully caught up.
Guard against this by returning zero when everything received has been replayed:
-- On the standby
SELECT CASE
WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
ELSE EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp())
END AS replay_delay_seconds;The query still has a limit. If the walreceiver is disconnected, receive and replay stay equal, so it reports zero for a standby that is cut off. Pair it with a check on pg_stat_wal_receiver or on the primary's pg_stat_replication. Some teams add a small heartbeat table that the primary updates every second. The standby then compares the stored timestamp with now(). That gives an end-to-end measure that works whether or not real traffic exists.
Replay can be paused
A standby can receive WAL and still not apply it. If replay was paused, replay_lsn stops moving while flush_lsn keeps advancing. Check this on the standby:
-- On the standby
SELECT pg_is_wal_replay_paused();Pausing is done on purpose with pg_wal_replay_pause() and undone with pg_wal_replay_resume(). It is easy to forget. A paused standby also builds up unapplied WAL on its own disk.
Slots and retained WAL
Replication slots keep WAL on the primary until a standby has consumed it. A standby that is down or very slow therefore makes the primary's disk fill. Watch this alongside lag:
-- On the primary
SELECT slot_name, slot_type, active, restart_lsn, wal_status,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;An inactive slot with a growing retained_wal is a warning. The wal_status column shows whether the needed WAL is still safe:
| `wal_status` | Meaning |
|---|---|
| `reserved` | The slot's WAL is within normal limits. |
| `extended` | The WAL is beyond the normal limits but still kept because of the slot. |
| `unreserved` | The slot is about to lose required WAL at the next checkpoint. |
| `lost` | Required WAL is gone. The standby cannot catch up and must be rebuilt. |
What to alert on
A basic monitoring set covers these checks:
- The number of rows in
pg_stat_replicationmatches the number of standbys you expect. - Each standby has
state = streaming. - Byte lag from
pg_current_wal_lsn()toreplay_lsnstays under a threshold that fits your workload. replay_lag, when it is not NULL, stays under your recovery-time or staleness target.- No replication slot is inactive for longer than a set time, and none has
wal_statusofunreservedorlost. - The standby reports
pg_is_wal_replay_paused() = false.
Pick thresholds from your own traffic. A threshold of a few megabytes would fire constantly on a system that does large batch loads, and a threshold of a few gigabytes would miss real problems on a quiet one.
Exercise
On the primary, pgstatreplication shows a standby with state = streaming, flushlsn close to pgcurrentwallsn(), but replaylsn far behind flushlsn and growing. Name two likely causes and one query you would run on the standby to check the first.
Show answer
The standby has the WAL on disk but is not applying it. Likely causes are that replay was paused with pgwalreplaypause(), or that replay is blocked or delayed by conflicts with long-running queries on the hot standby. To check the first, run SELECT pgiswalreplaypaused(); on the standby. If it returns true, resume replay with SELECT pgwalreplayresume();. If it returns false, look at long-running queries on the standby in pgstatactivity and at the standby's log for conflict messages.
Exercise
Why can now() - pglastxactreplaytimestamp() report a large lag on a standby that is fully caught up, and how do you avoid the false alarm?
Show answer
That timestamp is the commit time of the last transaction replayed. If the primary has had no writes for a while, the timestamp stays old, so the difference keeps growing even though the standby has applied everything. Avoid it by returning zero when pglastwalreceivelsn() equals pglastwalreplaylsn(), and by also checking that the walreceiver is connected, for example through pgstatwalreceiver or the primary's pgstat_replication.