PostgreSQL replication lag monitoring: what it tells you about your RPO
Replication lag monitoring answers one question: how much committed data does a standby not yet have? A standby that falls behind silently changes how much data a failover or a restore can lose, and nothing in a healthy-looking cluster shows that change unless you measure it. PostgreSQL supports hot standby servers that answer read-only queries, and it supports two replication modes. With synchronous replication, a commit waits until one or more standbys confirm it, so lag directly affects write latency. With asynchronous replication, the primary does not wait, so any standby may trail by an amount that varies with load, network capacity and disk speed. Which mode you run determines what your recovery point objective (RPO) actually is, and the lag figures are the only evidence of it between tests.
PostgreSQL does not detect a failed primary or promote a standby on its own. The PostgreSQL failover documentation describes promotion as a step you trigger, and external tools must make the decision to fail over. Those tools need current lag data to judge whether promoting a given standby is safe, so lag monitoring feeds the failover design rather than sitting beside it. Set up monitoring once standbys exist, and make sure it is working before you trust any failover tooling. Also monitor lag when logical subscribers or replication slots are in use, because an inactive or slow slot holds back WAL on the primary and can fill its disk, which is a separate risk from standby lag.
Confirm with your team which lag measurements your PostgreSQL version exposes in pg_stat_replication and how each one is calculated before you set thresholds. Then decide what RPO each standby must meet, and derive the alert threshold from it. Test that alert by pausing replay or throttling the network on a non-production standby and checking that the alert fires within the time your RPO allows. Ask any partner to show this test as part of the written scope, because a threshold chosen without a measured RPO is a guess.
Which lag measure answers which monitoring question
This table compares the lag measures available for PostgreSQL replication and shows which question each one answers. Read it to choose the right signal for a dashboard, an alert or a recovery point discussion, and remember that the primary and each standby report different views.
| Measure | What it measures and where to read it | Question it answers | Typical alert use |
|---|---|---|---|
| Write lag | Time for a standby to receive and write WAL, reported as write_lag in pg_stat_replication on the primary | How quickly has the standby received the latest commits from the network? | Early warning for network or standby I/O trouble on synchronous standbys |
| Flush lag | Time until the standby has flushed WAL to durable storage, reported as flush_lag in pg_stat_replication on the primary | How much committed work would be lost if the standby lost power right now? | Tie to recovery point exposure for synchronous commit designs |
| Replay lag | Time until the standby has applied WAL, reported as replay_lag in pg_stat_replication on the primary | How far behind are read queries on the standby, and how stale is a failover target? | Alert when hot standby reads or failover readiness exceed the agreed limit |
| Byte lag from LSNs | Difference between pg_current_wal_lsn() on the primary and the replica position in sent_lsn, write_lsn, flush_lsn or replay_lsn, measured in bytes | How much WAL is queued, independent of time and commit rate? | Detect growing backlog during bulk loads or when a standby stops accepting WAL |
| Logical replication lag | Position of the subscriber relative to the publisher, reported through the subscriber and publisher statistics views for your version | Is the subscriber keeping up with changes for the tables it receives? | Alert on sustained growth in apply delay for migration or reporting feeds |
| Replication slot lag | Retained WAL held for each slot, measured by comparing the slot restart position with the current WAL position in pg_replication_slots | How much WAL is the primary keeping on disk because a consumer has not confirmed it? | Alert on retained WAL growth that threatens disk space, including inactive slots |
| Standby's own view | Receive and replay positions and replay delay reported on the standby itself, which can differ from the primary's view during restarts or network gaps | What has this standby actually received and applied? | Use alongside primary metrics to confirm which side is lagging |
| Column semantics by version | Exact column names, units and reset behavior in pg_stat_replication and related views | Are the numbers in my dashboard what I think they are? | Confirm against the PostgreSQL documentation for your major version before setting thresholds |
Replication lag is measured at four points between the primary's WAL and the standby's replay
A commit starts as WAL records written on the primary. The walsender process streams those records to the standby, where they are written to disk, flushed, and then replayed into the data files. Each hand-off is a separate position, so write_lag, flush_lag and replay_lag in pg_stat_replication measure different delays. A logical subscriber reads the same WAL through a logical decoding slot, and an inactive replication slot keeps WAL on the primary until it is consumed. The monitoring collector reads primary-side views and standby-side functions, so check both ends.
Primary-side and standby-side measurements along the commit path.
Physical standbys, logical subscribers and replication slots need different checks
Streaming physical standbys replay the primary's WAL byte for byte, so lag is measured against the primary's current write position. On the primary, the pg_stat_replication view has one row per connected standby, with write_lag, flush_lag and replay_lag showing how long WAL takes to reach each stage. The sent_lsn, write_lsn, flush_lsn and replay_lsn columns let you compute byte lag with pg_wal_lsn_diff(), which shows the gap in bytes even when the time-based values are empty because the standby is idle. Confirm which columns your PostgreSQL version reports before you build dashboards on them.
- Time lag versus byte lag: Time-based lag can read zero on an idle system while byte lag still shows unreplayed WAL. Alert on both.
- Replay gap on a hot standby: A growing
replay_lagwith a steadyflush_lagusually points to the standby's apply process, such as long-running read queries that block replay conflicts or limited I/O on the standby. - Receive gap: A growing
write_lagorflush_lagpoints to the network or the standby's disk. - Synchronous standbys: If
synchronous_standby_namesis set, commit latency on the primary rises with these lags, so the same numbers also explain write slowdowns. - Standby-side view: Run
pg_last_wal_receive_lsn()andpg_last_wal_replay_lsn()on the standby to confirm what it has received and applied.
Check that the standby's own view agrees with the primary's before you trust either number during an incident.
Logical replication sends decoded row changes to subscribers, so the primary's pg_stat_replication view still shows the walsender connection, but the meaningful question is how far each replication slot has fallen behind. The subscriber side lists its subscriptions in pg_stat_subscription, which shows the last received and reported LSNs, and the slot lag on the publisher is the gap between the current WAL position and the slot's confirmed flush position. Whether your release exposes every field you need depends on the version, so confirm against the documentation for your release.
- Confirmed flush gap: On the publisher, compare the current WAL LSN with the logical slot's
confirmed_flush_lsninpg_replication_slots. A growing gap means the subscriber has stopped confirming changes. - Apply errors: A subscription stuck on one bad row or a missing table will stop advancing while the connection stays open, so check for errors in the subscriber logs before assuming network trouble.
- Initial table sync: Large initial copies keep the slot busy and can look like lag for hours. Plan a baseline before a major upgrade or large migration.
- Subscriber capacity: A slow subscriber on constrained storage or with missing indexes on target tables grows lag in the same way a slow network does.
Before you rely on subscriber lag numbers, confirm which publications, tables and sequences are included, because sequences do not replicate through the same path.
A replication slot makes the primary keep WAL until the consumer confirms it has read that WAL. This protects the standby or subscriber from falling out of sync, but the same retention can fill the primary's disk when the consumer stops. The pg_replication_slots view shows each slot's active flag, its restart_lsn (the oldest WAL the slot still needs) and, for logical slots, confirmed_flush_lsn. Measuring the distance from restart_lsn to the current WAL position gives the retained WAL per slot, which is the figure to watch on the primary's disk.
- Inactive slots: A slot with
activeset to false still pins WAL. An abandoned standby or a subscriber removed without dropping its slot is the most common cause of runaway WAL growth. - Retained WAL size: Track the byte distance from
restart_lsnper slot and alert on it against free space in the WAL directory, not only on replay lag. - Failover slots: If you use failover of logical slots to a standby, confirm the configuration and the PostgreSQL release that supports it before you assume the slot survives a promotion.
- Cleanup procedure: Dropping a slot releases WAL but also discards the consumer's position, so the consumer will need a resync. Document who approves that step.
- Limits: Check whether your configuration caps retained WAL for slots. Confirm the setting and its behavior in the documentation for your release before you depend on it.
Review slot retention on the primary at least as often as lag on the standbys, because an inactive slot can exhaust disk without any visible replication delay.
Setting up PostgreSQL replication lag monitoring in order
This sequence moves from knowing every replica that needs watching to a tested lag signal, so the team can see how far each standby trails the primary and whether that gap stays inside the recovery point target. The output is a monitored inventory, a least-privilege collection path, byte-lag measurements and slot retention checks that have been proven against controlled load.
Inventory every standby, subscriber and slot
The platform or database team lists each physical standby, each logical replication subscriber and each replication slot on the primary, along with the role each one plays in recovery. Record which standbys are synchronous and which are asynchronous, because the lag that matters for commit waits differs from the lag that matters for data loss. Check the list against the primary's pg_stat_replication and pg_replication_slots views, and confirm that no standby or slot exists outside the inventory. The step is done when the inventory matches what the primary reports and the owner of each entry is named.
Create a dedicated monitoring role
The database administrator creates a login role used only for lag collection and grants it the narrowest privileges that the lag queries need, following the least-privilege model in the PostgreSQL authentication and role documentation. Restrict network access in pg_hba.conf to the monitoring host and use the authentication method your security standard requires. Confirm in your own environment that the role can read the replication views and that a test connection with it cannot modify data or read application tables. The step is done when the role connects from the collector host and the access review records its purpose.
Collect LSN and replication view data on a fixed interval
The collector queries the primary on a fixed schedule for the current WAL position and for the rows in pg_stat_replication, and it queries each standby for its replay position. Store each sample with a timestamp and the standby name so trends can be read later. Choose the interval with the team that owns the recovery point objective, and confirm that the collector's own load on the primary is small enough for your workload. The step is done when samples arrive without gaps for a full business cycle and the stored timestamps match the collector clock.
Compute byte lag from LSN positions
The collector subtracts each standby's replay position from the primary's current WAL position using pg_wal_lsn_diff, which returns the lag in bytes. Also record write and flush lag from the lag columns in pg_stat_replication, since the replay figure alone can hide a standby that has received but not yet applied WAL. Keep the byte figure as the primary signal, because it is independent of the time since the last transaction. The step is done when each standby shows a byte lag value that rises during a busy period and falls when the workload quiets, and when the unit of each column is documented for the on-call team.
Add slot retention checks
For each physical and logical replication slot, the collector records how much WAL the slot is holding back and whether the slot is active. A slot that has no consumer keeps WAL on the primary, which can fill the disk and stop writes, so the check should flag inactive slots as well as slots whose retained WAL grows steadily. Compare slot retention with the free space on the WAL volume and set the threshold with the storage owner. Confirm that a deliberately inactive test slot appears in the check and is removed after the test. The step is done when the slot check reports both the retained size and the active state for every slot in the inventory.
Map byte lag to alert thresholds tied to RPO
The team translates the recovery point objective into a byte threshold by working out how much WAL the business could lose at the moment of failure and how fast the primary generates WAL at peak. Set warning and critical thresholds below that limit, and document which standbys are the failover candidates so their thresholds are stricter. Ask the platform owner to confirm the recovery point objective in writing, because the thresholds depend on it. The step is done when each alert has a named threshold, a severity and an owner who will act on it.
Verify with controlled write load
In a non-production environment that mirrors the topology, the team generates a controlled write load, such as a bounded batch insert, and watches the collector sample byte lag, write lag, flush lag and slot retention. The lag should rise while the load runs and return to near baseline after it stops, which confirms the measurement reacts to real WAL volume. Repeat the test with one standby paused or slowed to confirm that its lag alone climbs and that the alert fires at the agreed threshold. The step is done when the rise, the recovery and the alert behavior are recorded and the thresholds have been adjusted if they fired too early or too late.
Tying alert thresholds to your RPO rather than to default values
Start from the recovery point objective your business has agreed, not from a threshold someone copied from a dashboard template. The RPO states how much committed data the organization can afford to lose in a failover, expressed as a time window. Lag alerts only mean something when they are tied to that window: if a standby can fall further behind than the RPO allows before anyone is told, the alert set is wrong regardless of how green the dashboards look. Confirm the RPO with the data owners and the business continuity owner before choosing any number, and record which systems it applies to, since a reporting database and a payments ledger rarely share one.
Next, decide which lag measure represents potential data loss for each standby mode. For asynchronous standbys, the exposure is the work the primary has committed that the standby has not yet received or replayed, so the relevant measures are the byte lag between the primary's current write position and the standby's replay position, derived from LSNs in pg_stat_replication, and the write, flush and replay lag intervals. Confirm which of these your failover runbook assumes the standby will hold. For synchronous standbys, a commit waits for the standby to confirm, so data loss exposure is mainly during a failure that happens while the standby is unavailable or fell out of the synchronous set. Monitor the synchronous state and the number of connected synchronous standbys as closely as the lag itself. Logical replication slots need their own measure, because retained WAL growth affects disk risk, not only RPO.
For warning and critical thresholds, measure a baseline under normal load first, then set the warning level well inside the RPO and the critical level at a point where a failover would still be within the agreed window. Attach a sustained-duration condition to each rule so that a single sample above the limit does not page anyone, and keep the duration short enough that a real problem is still caught in time. Batch jobs, bulk loads and nightly maintenance produce predictable bursts of WAL, so schedule expected windows as known conditions or exclude them explicitly rather than widening thresholds for everyone. Review the thresholds after any change to workload shape, network path, standby hardware or replication settings, because a threshold derived from last year's network will quietly stop meaning what the RPO requires.
Securing the monitoring role and the lag data
The lag data that makes replication monitoring useful also maps your architecture, so the collector needs the same care as the database. The cards below cover the monitoring role, how the collector authenticates, the network path, who can read topology, how long metrics are kept, and how incident changes to slots and standbys are recorded.
Least-privilege monitoring role
Create a dedicated login role for the collector and grant it only what it needs to read replication views such as pg_stat_replication and pg_replication_slots. The role should not be a superuser, and it should not hold write privileges on application schemas. Confirm the exact grants your PostgreSQL version and exporter require, then test the role by running the same queries the collector runs before you connect it to production. Re-check the grants after each major upgrade.
Collector authentication method
Choose the authentication method for the collector from the methods PostgreSQL documents, and set it in pg_hba.conf for the collector's address only. Password-based logins should use SCRAM, since MD5 password authentication is deprecated in PostgreSQL 18. Where the collector runs under a service identity, consider certificate or directory-based methods so no static password sits in a monitoring config file. Record which method each collector uses in your access review.
Network path and TLS
Decide which hosts can reach the database port from the collector, and restrict those paths with firewall rules and pg_hba.conf entries. Traffic that crosses a segment boundary should use TLS with hostssl entries, and the collector should verify the server certificate rather than accept any certificate. Confirm whether your exporter or agent supports certificate verification in your version before you assume it does.
Who can see topology
Replication views expose standby addresses, application names, slot names and sync states. Those details reveal how the cluster is built and where its failover paths lead. Limit read access to the dashboards, the time-series store and the raw query results to the operators who run the cluster, and keep slot names free of customer or system identifiers where your naming standard allows it.
Retention of lag metrics
Lag history is useful for post-incident review and for showing that the standby met its recovery point target over time, but it is also operational data that should be governed. Set a retention period for raw samples and a longer period for downsampled series, and agree it with your compliance and incident response owners. Ask your monitoring vendor or platform team to confirm how retention, deletion and access logging work in your stack.
Change control during incidents
During an outage, engineers often drop an inactive slot, repoint a standby or change synchronous settings to recover service. Each of those changes alters what the lag graphs show. Require a ticket or incident record for every slot and standby change, note the time in the monitoring annotations, and review the change after recovery so the lag history can be interpreted correctly.
Failover docsWhat buyers ask before they commission lag monitoring
What does replication lag monitoring cost and what drives the effort up?
The cost is the labor to design, build and hand over the monitoring, so it scales with the work rather than with a fixed package. The main drivers are the number of clusters, the topology (one primary with a few standbys, cascading standbys, or several logical publications), whether you already run Prometheus, Grafana, Zabbix or a log platform that can take the metrics, how alerts are routed to on-call staff, and how many runbooks must be written and tested. Ask for a written scope that lists each cluster, each monitored view, the alert routes and the runbooks. Separate one-time build work from any retainer for tuning and review, since thresholds usually need adjustment after the first few weeks of real traffic. DeployOpen does not publish prices; a quote follows from the written scope.
How long does a lag monitoring engagement take?
Duration depends on the work sequence, not on a fixed number of days. The sequence is usually: inventory the clusters and current monitoring, confirm the monitoring role and network access, build the collectors and dashboards on a staging cluster, define thresholds from your recovery point objective, test alerts by inducing controlled lag, write runbooks, then move to production and tune. Each step waits on client input such as access approvals and change windows, so those waits often set the calendar. Ask the partner to show the milestones and the client dependencies in the written scope before work begins.
What must our team provide before the work starts?
Plan to provide the following before the first milestone:
- Read access to the primary and standby configuration, and a database role that can read the replication views, agreed with your DBA team.
- A staging cluster that mirrors the production topology closely enough to test lag under load.
- Recovery point objective targets for each critical database, written in seconds or bytes of acceptable loss, owned by the business or risk owner.
- Named on-call contacts, escalation paths and the ticketing or paging tool that alerts must reach.
- Change windows for enabling settings and restarting collectors.
Missing RPO targets are the most common blocker, because alert thresholds cannot be set without them.
Can our internal team build replication lag monitoring alone?
Yes, a team with PostgreSQL and monitoring experience can build basic lag monitoring using the built-in views and an existing exporter or agent. The harder parts are usually outside the query itself: converting an RPO into alert thresholds, avoiding noisy alerts during bulk loads, routing alerts to the right people, and proving that alerts fire during a real lag event. Confirm that your team has someone who can read the replication views, someone who owns alert policy, and time to run a controlled test. If any of those are missing, a partner can cover the gap through a fixed-scope build and handover.
What changes when logical replication or replication slots are involved?
Logical replication and slots add a second kind of lag. Physical standby lag is measured against the primary's WAL position. For logical replication, you also watch the subscriber's apply progress and the retained WAL held by each replication slot. An inactive or lagging slot can keep WAL on the primary until disk fills, so slot retained size belongs in the alert set alongside replay lag. Ask whether any consumers are outside your control, because those can stall without warning. Confirm slot ownership and the cleanup procedure in the scope, and check the PostgreSQL replication documentation for the view names and settings that apply to your major version.
Which lag figures should we alert on, and how do we set thresholds?
Alert on the lag your recovery point objective can tolerate, not on a generic default. Write-, flush- and replay-lag values in the pg_stat_replication view show where time is spent, and byte lag computed from the LSN positions shows how much WAL is outstanding. Set a warning level below the RPO and a critical level at or near it, then test both by inducing lag on staging. Thresholds should also account for expected batch jobs so they do not page at 2 a.m. for planned work. Ask the partner to document each threshold, its source target and the test that proved it fires.
What should we check in the written scope before signing?
Check that the scope names each cluster and standby, the exact metrics and views collected, the monitoring role and its privileges, the alert routes and severities, the runbooks for each alert, the staging test plan, and the handover format. Ask whether the work includes dashboards, tuning after go-live and a retest after any topology change. Confirm who owns credentials and where the configuration is stored. A scope that lists these items lets you compare quotes on equal terms.
Limits to confirm in your environment before you rely on lag figures
Replication lag figures are only as good as the view they come from. The cards below cover the places where a healthy-looking number can hide a standby that is behind, or where a dashboard cannot see the problem at all. Confirm each point in your own cluster before you set alert thresholds or write an RPO into a runbook.
Lag values are samples, not live state
The write, flush and replay columns in pg_stat_replication reflect the moment the sender last reported, and a monitoring job reads them only at its polling interval. Between two polls a standby can fall far behind and recover before the next sample. Confirm your scrape interval, and test lag under a bulk load shorter than that interval so you know what the graph can miss.
Columns depend on server version
Column names and availability in pg_stat_replication and related views change between major releases, and some lag fields are only populated under particular settings. Before writing a query, check the release your cluster runs against the current documentation for that version. Treat a NULL in a lag column as a question to answer, not as zero lag.
Standbys the primary view misses
The primary only lists standbys that are connected to it. A standby that has lost its connection, points at a different upstream, or is a cascading replica may not appear in the primary's pg_stat_replication output at all. Compare the list of expected standbys from your inventory against the rows the primary returns, and query each standby's own pg_stat_wal_receiver view.
Managed services may restrict the views
Managed PostgreSQL offerings often hide superuser-only functions, restrict the monitoring role, or expose replication status through their own metrics with different names and intervals. Ask the provider which views and functions your monitoring role can read, how lag is reported, and whether the figures are the same ones PostgreSQL uses internally. Self-hosted clusters are not affected by these limits, so confirm this only where a provider runs the database.
Thresholds need a measured baseline
A lag alert set from a guessed number produces either constant noise or silence during a real backlog. Measure normal lag over several weeks of peak and batch activity, including nightly jobs and backups, then set warning and critical levels against the RPO your business has agreed. Revisit the thresholds after every major change to write volume or network path.
Failover is not provided by PostgreSQL
PostgreSQL does not detect a failed primary or promote a standby on its own, so lag figures alone do not protect you during an outage. Confirm which external tool will detect the failure, how it chooses a standby with acceptable lag, and what happens when the lag is too high to promote safely. Test that decision path in your own cluster, not only in the vendor documentation.
Failover docsHow DeployOpen scopes and delivers replication lag monitoring
DeployOpen plans, implements and documents replication lag monitoring for PostgreSQL inside your own infrastructure, tied to the recovery point target your team has agreed. Engagements are fixed-scope, so the metrics, thresholds, alert routing and handover materials are written down before any build starts.
How we scope
- Inventory every standby, cascading replica and logical subscriber, with the replication topology your team actually runs
- Record the recovery point objective and which replicas back it, so thresholds have a documented source
- Agree the metric sources, monitoring role, dashboards and alert routing in the written scope before work starts
- Confirm which monitoring platform you already run, such as Prometheus, Zabbix or the OpenTelemetry Collector
How we build
- Create a least-privilege monitoring role and verify it can read pg_stat_replication and replication slot views
- Configure collection of write, flush and replay lag plus byte lag from LSN positions on each standby
- Add logical replication and slot lag checks, including retained WAL on the primary, with test cases for each
- Test alerts by simulating a stalled standby and a paused subscriber in a non-production environment first
How we hand over
- Deliver the runbook with each threshold, its tie to the recovery point objective and the response expected
- Document the monitoring role, its privileges, credential storage and the process for rotating it
- Provide dashboards, alert rule definitions and a short walkthrough so your team can change thresholds safely
- Record open items and the settings to review after the next PostgreSQL minor or major upgrade
How we support
- Ongoing support, upgrades and continuous testing are available as retainers after handover
- Retainers can cover threshold reviews when topology, write volume or recovery targets change
- Retest alerting after PostgreSQL upgrades, because view columns and slot behavior can change between major versions
- Confirm retainer terms, response expectations and included hours with DeployOpen in the written quote

