How to Monitor Replication Lag in PostgreSQL Easily
To monitor replication lag in PostgreSQL, use the
pg_stat_replication view on the primary server to check write_lag, flush_lag, and replay_lag. These fields show how far behind the replica is in writing, flushing, and replaying WAL data, helping you track replication delay.Syntax
The main way to monitor replication lag is by querying the pg_stat_replication view on the primary server. Key columns include:
write_lag: Time delay between WAL write on primary and replica.flush_lag: Delay until WAL is flushed on replica.replay_lag: Delay until WAL is replayed on replica.
These columns show intervals representing lag times.
sql
SELECT pid, application_name, client_addr, state, write_lag, flush_lag, replay_lag FROM pg_stat_replication;
Example
This example query shows how to get replication lag details from the primary server. It lists connected replicas and their lag times.
sql
SELECT application_name, client_addr, state, write_lag, flush_lag, replay_lag FROM pg_stat_replication;
Output
application_name | client_addr | state | write_lag | flush_lag | replay_lag
-----------------+--------------+----------+-----------+-----------+------------
replica1 | 192.168.1.5 | streaming| 00:00:00 | 00:00:00 | 00:00:01
replica2 | 192.168.1.6 | streaming| 00:00:02 | 00:00:02 | 00:00:03
(2 rows)
Common Pitfalls
Common mistakes when monitoring replication lag include:
- Checking lag on the replica instead of the primary;
pg_stat_replicationis only on the primary. - Not having replication slots or streaming replication properly configured, so no data appears.
- Ignoring that lag columns can be
NULLif the replica is not streaming.
Always ensure your replica is connected and streaming to get accurate lag info.
sql
/* Wrong: Checking lag on replica server */ SELECT pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn(); /* Right: Check lag on primary server */ SELECT application_name, write_lag, flush_lag, replay_lag FROM pg_stat_replication;
Quick Reference
| Column | Description |
|---|---|
| application_name | Name of the replica connection |
| client_addr | IP address of the replica |
| state | Current replication state (e.g., streaming) |
| write_lag | Delay writing WAL on replica |
| flush_lag | Delay flushing WAL on replica |
| replay_lag | Delay replaying WAL on replica |
Key Takeaways
Use the pg_stat_replication view on the primary server to monitor replication lag.
Check write_lag, flush_lag, and replay_lag columns for detailed lag times.
Replication lag info is only available on the primary, not on replicas.
Lag columns can be NULL if the replica is not streaming or disconnected.
Ensure streaming replication is properly configured for accurate monitoring.