dataiotech Labs
Scripts Library/postgresql/#6
Script #6
postgresql
Replicationread-onlyMin Version: 10

Measure PostgreSQL Streaming Replication Lag

Shows WAL lag in bytes and time on the primary, and replay delay on the standby. Used to monitor replication health and RPO risk.

#replication#lag#streaming#wal
postgresql · sql
-- 1. Primary Üzerinde (Run on Primary)
SELECT application_name, client_addr, state, sync_state,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS replay_lag_bytes,
       write_lag, flush_lag, replay_lag
FROM pg_stat_replication;

-- 2. Standby Üzerinde (Run on Standby)
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;
Operational Notes & Remediation Guidance

Verify in a staging environment prior to running in production. This is a read-only diagnostic query; it does not acquire exclusive locks.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 10).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.

Engineering Triad: Related Runbooks & Incident Response

Which production incidents and emergency drills execute this script as a diagnosis step?

Runbook Library (63)
Related Alerts & Metrics
M3PostgreSQL Replication Lag (Seconds)PostgreSQL
M4PostgreSQL WAL Retained by Replication SlotsPostgreSQL