How-To Guide

How to Monitor Replication Lag

Measure how far a replica trails its primary, understand what causes lag, and bound the staleness your readers can tolerate.

On this page

  1. Introduction
  2. What Replication Lag Is
  3. Measuring Lag
  4. Lag from Apply Conflicts
  5. Lag from Network and WAL Volume
  6. Acting on Lag
  7. Failover and Lag
  8. Conclusion

Introduction

Replicas exist to scale reads and to survive the loss of a primary, but they are always a little behind. The distance behind is the replication lag, and it determines how stale a read from a replica may be. A lag of a few milliseconds is invisible; a lag of thirty seconds means a user who writes and immediately reads elsewhere sees their own change missing. Monitoring lag is really about defining and enforcing an acceptable staleness, and catching the events that push lag beyond it. This article covers how to measure lag, what causes it to spike, and how to act when it does.

What Replication Lag Is

In asynchronous streaming replication the primary writes to its write-ahead log and streams it to replicas, which apply it. The replica is behind by however much log it has received but not yet applied, plus whatever is still in flight. The lag is measured in bytes of log, in seconds of wall-clock difference, or in transactions. Time-based lag is what consumers care about: how old is the data a replica will return.

Synchronous replication removes the lag by making the primary wait for a replica to confirm, at the cost of write latency and availability if the replica fails. Most systems use asynchronous replication for writes and tolerate bounded staleness on reads, so the practical question is not whether there is lag but whether it is within the tolerance you promised.

Measuring Lag

A robust measure is a timestamp written by the primary and read back: the replica reports the age of the most recently applied transaction relative to the primary’s clock, which captures both receiving and applying delay. Byte-based measures from the statistics views are cheaper and catch the case where a replica receives nothing at all. Combine both: bytes for a fast signal that replication is flowing, time for the user-facing staleness.

-- On the primary: create a heartbeat table updated every second.
-- CREATE TABLE repl_heartbeat (id int primary key, ts timestamptz);
-- UPDATE repl_heartbeat SET ts = now() WHERE id = 1;   -- run every second

-- On the replica: age of the last applied heartbeat (user-facing staleness)
SELECT now() - ts AS replication_lag
FROM repl_heartbeat WHERE id = 1;

-- Byte/transaction lag from the statistics views (works even if the replica
-- is not applying anything, which time-based lag can miss)
SELECT client_addr,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes,
       state,
       sync_state
FROM pg_stat_replication;

Lag from Apply Conflicts

A replica can receive log faster than it applies it, so the applied lag exceeds the received lag. This happens when a long query on the replica blocks the apply process, because applying a change to a row that a read transaction is still holding a snapshot for must wait. The classic case is a full-table scan or a long analytics query on a read replica: it holds a snapshot, the apply process stalls behind it, and lag grows until the query finishes.

The fix is to bound long reads on replicas with statement timeouts and to avoid unbounded analytics on the same replica that serves user traffic. A dedicated analytics replica, or a delay in applying, isolates the impact. Watch for idle-in-transaction sessions on replicas, which hold a snapshot just as effectively as a running query and are easy to leave open.

Lag from Network and WAL Volume

Network throughput bounds how fast the log arrives. A bulk operation that generates a large volume of write-ahead log can outrun the link between primary and replica, so the replica falls behind during the bulk load and catches up after. Large transactions are worse than many small ones because the replica must apply the whole transaction before it becomes visible, and the primary does not release the log until commit.

The mitigation is to break bulk operations into batches so the log streams in smaller increments, and to schedule large backfills for quieter periods. Monitor the network link saturation alongside lag, because a link at its limit produces lag that no amount of replica tuning will fix.

Acting on Lag

Define a threshold for acceptable lag and alert when it is breached for more than a moment. Then decide the response: if reads can tolerate the lag, do nothing but keep watching; if they cannot, route reads to the primary until the lag recovers. The routing decision should be automatic and based on the measured lag, not on a human noticing.

For read-your-writes, a client that has just written can read from the primary, or wait until the replica has applied at least the log position of its own write. That is stronger than a blanket route-everything-to-primary and keeps most reads on the replica. It requires the write to return a position the client can pass as a minimum on subsequent reads.

# Export replication_lag_seconds from the heartbeat query above, then:
# Alert when lag stays above the tolerance for more than a minute.
ALERT ReplicationLagHigh
  IF max by (replica) (replication_lag_seconds) > 5
  FOR 1m
  LABELS { severity = "warning" }
  ANNOTATIONS { summary = "Replica {{ $labels.replica }} is 5s+ behind" }

# Read-your-writes: wait until this replica has applied the write's LSN.
-- run on the replica with the LSN returned by the write
SELECT pg_last_wal_replay_lsn() >= '0/1A2B3C4'::pg_lsn AS caught_up;
-- poll until true, then serve the read from this replica

Failover and Lag

When a primary fails, the replica with the smallest lag is the best candidate and loses the least data. Monitor lag continuously so the choice is instant and informed, and so you know the expected data loss before you promote. A replica that has been lagging for hours should not be the automatic failover target without a deliberate decision.

After failover, replication restarts from the new primary, and the previous primary, when it returns, must be reconfigured as a replica. Watch the lag during this period, because the recovered node is far behind and the link may be saturated as it catches up. This is a common moment for lag to spike, so plan for it rather than being surprised.

Conclusion

Replication lag is the staleness a replica read may return, and mastering it means measuring both the flow of log and the applied timestamp, understanding the two failure modes of blocked apply and saturated network, and acting automatically. Bound long reads on replicas, batch bulk operations, alert on a sustained threshold, and route reads back to the primary or wait for a position when staleness would break read-your-writes. Then a replica that trails its primary is a known quantity rather than a source of surprise.

Sources: PostgreSQL: replication monitoring, PostgreSQL: high availability and replication, PostgreSQL: warm standby.

FAQ

Why is the replica lagging even though replication looks healthy?
The replica may be receiving log faster than it can apply it, usually because a long-running query on the replica holds a snapshot that blocks the apply process. Bound long reads on replicas with a statement timeout, or isolate analytics onto a separate replica.
How do I guarantee a user sees their own write?
Read from the primary for a short period after a write, or have the write return the log position and have subsequent reads wait until the replica has applied at least that position. This keeps most reads on the replica while preserving read-your-writes.

Related Examples