PostgreSQL replication lag occurs when a replica falls behind changes on its primary, leaving reads temporarily stale. Diagnose it by comparing WAL transmission, receipt, and replay progress, then matching the stalled stage to resource pressure or replication errors.
For SaaS users, this can mean a saved account setting disappears after refresh or a new invoice briefly returns “not found.” Start with the affected read path, because database replay progress alone doesn’t establish what the user can see.
Key takeaways
- Compare primary-side WAL positions with standby receipt and replay progress before changing settings.
- Read time-based lag alongside byte backlog, workload, and application freshness.
- Protect consistency-sensitive workflows with primary reads or bounded read-after-write routing.
Separate replay delay from read staleness
Physical replication sends write-ahead log (WAL) records to a standby, which writes, flushes, and replays them. Replay makes the changes available to new read snapshots.
PostgreSQL identifies WAL positions using log sequence numbers, or LSNs. As PostgreSQL’s WAL internals documentation explains, subtracting positions measures bytes, not seconds.
End-to-end staleness also includes application behavior. A request might use another replica, return cached data, or run inside a transaction with an older snapshot. Even after replay catches up, those paths can return an earlier value.
A replica can finish replaying a write while an existing Repeatable Read transaction continues seeing its earlier snapshot.
Record the affected endpoint, replica identity, write commit time, and read time. Also establish that the write committed successfully. An uncommitted change missing from another connection isn’t replication lag.
1. Locate the gap on the primary
Run diagnostics through an authorized monitoring role, such as one granted pg_monitor. Take repeated samples in separate transactions so a retained statistics snapshot doesn’t obscure progress.
Inspect each connected standby
Run this on the primary:
SELECT application_name, state, sync_state,
sent_lsn, write_lsn, flush_lsn, replay_lsn,
pg_wal_lsn_diff(
pg_current_wal_lsn(), replay_lsn
) AS backlog_bytes,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
The replication statistics reference describes these columns. Each row represents a WAL sender for a directly connected standby. A disconnected replica or a standby farther down a cascading topology won’t appear here.
state = 'streaming' identifies streaming activity; it doesn’t establish that replay has caught up. Likewise, sync_state describes synchronization participation, not application freshness.
Compare the stages across samples
A growing distance between the primary’s current position and sent_lsn points toward sender-side pressure. A widening sent_lsn to write_lsn gap directs attention toward transport or standby write capacity.
If flush_lsn advances while replay_lsn stalls, investigate replay. Use pg_wal_lsn_diff() to quantify these gaps.
The interval columns describe recent acknowledgment timing. They aren’t catch-up estimates. After idle periods, they can retain a previous measurement briefly and then become NULL.
2. Inspect receipt and replay on the standby
Sample the affected standby close to your primary-side measurements. WAL continues advancing, so widely separated samples can suggest misleading gaps.
Establish whether WAL is arriving
Run:
SELECT status, sender_host, slot_name,
last_msg_send_time, last_msg_receipt_time
FROM pg_stat_wal_receiver;
This view has at most one row. Its status and message timestamps help distinguish an active receiver from connection trouble.
However, recent messages don’t prove that application transactions have replayed. An empty result also needs context: a standby can retrieve WAL through archive recovery rather than an active streaming connection.
Correlate receiver changes with database logs, network throughput, retransmissions, and authentication or connection errors.
Compare received and replayed positions
Next, run:
SELECT pg_is_in_recovery() AS in_recovery,
pg_last_wal_receive_lsn() AS received_lsn,
pg_last_wal_replay_lsn() AS replayed_lsn,
pg_is_wal_replay_paused() AS replay_paused,
pg_last_xact_replay_timestamp()
AS last_replayed_commit;
The receive function reports WAL received and synced through streaming replication. A growing receive-to-replay gap means durable incoming WAL is outpacing replay. NULL positions require context; don’t convert them into zero-lag readings.
If replay is paused, establish why before resuming it. An operator may have paused recovery intentionally.
Finally, last_replayed_commit can look old on an idle database. Time since the last replayed transaction doesn’t measure an unapplied queue when no new transactions exist.
3. Match the stalled stage to workload pressure
Use the measurements to narrow the investigation. A byte gap identifies where progress slows, but it doesn’t identify the responsible resource by itself.
Investigate load, I/O, and WAL bursts
When sending falls behind, inspect primary CPU, storage latency, and concurrent maintenance. When receipt falls behind, inspect network health and standby write capacity.
For replay backlog, correlate replica disk latency, CPU, and reporting queries. PostgreSQL’s database monitoring guidance recommends combining database views with system tools such as iostat and vmstat.
Backfills, bulk imports, and index builds can generate WAL faster than a replica normally consumes it. Measure changes in pg_stat_wal.wal_bytes over a known interval, accounting for counter resets.
Pause dispensable maintenance or reduce backfill batch size and concurrency first. Add replica capacity when sustained measurements show a resource limit.
Examine transactions and recovery conflicts
Run this on the affected database:
SELECT pid, application_name, state,
now() - xact_start AS transaction_age,
wait_event_type, wait_event,
pg_blocking_pids(pid) AS blockers
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start;
Long standby queries can conflict with WAL replay. Inspect recovery-conflict logs and changes in pg_stat_database_conflicts.
On the primary, old snapshots can prevent tuple cleanup. Investigate idle-in-transaction sessions, especially code holding transactions open across HTTP calls.
Follow blocking PIDs before intervening. An empty blocker array doesn’t exclude snapshot retention. Cancel dispensable work selectively; increasing max_standby_streaming_delay can trade fewer query cancellations for greater replay delay.
4. Inspect replication-slot retention safely
Slots preserve replication state and can retain WAL when consumers fall behind. Run this on the server hosting the slot:
SELECT slot_name, slot_type, active,
xmin, catalog_xmin, restart_lsn,
pg_wal_lsn_diff(
pg_current_wal_lsn(), restart_lsn
) AS retained_wal_distance_bytes
FROM pg_replication_slots;
restart_lsn concerns required WAL retention. The calculated distance indicates retention pressure, rather than exact filesystem usage.
Meanwhile, xmin can prevent cleanup of user-table row versions, and catalog_xmin can retain catalog row versions. These markers describe different retention obligations.
An inactive slot isn’t automatically abandoned. Its consumer may be disconnected temporarily. Restore that consumer or deliberately retire its replication dependency before removing the slot. Dropping required state can force resynchronization.
PostgreSQL’s replication configuration reference documents max_slot_wal_keep_size. Its default, -1, allows unlimited slot-based WAL retention. A finite limit bounds retention but can permit required WAL removal, leaving a consumer unable to continue.
Monitor storage headroom alongside slot state. Never delete files manually from pg_wal to reclaim space. If storage is approaching exhaustion, reduce nonessential WAL-generating work while restoring consumer progress.
5. Diagnose logical replication separately
The physical standby queries above don’t describe a logical subscriber’s apply progress. On a logical subscriber, start with:
SELECT subname, pid, relid, received_lsn,
latest_end_lsn, last_msg_receipt_time
FROM pg_stat_subscription;
PostgreSQL’s logical replication monitoring documentation explains that this view reports subscription workers. Initial table synchronization can add workers; a disabled or crashed subscription may have no rows.
Treat received positions and message times as communication evidence, not proof that every expected row is visible.
Inspect subscriber logs for apply errors, schema mismatches, and constraint conflicts. Also inspect subscriber lock waits and resource saturation. Repair the underlying incompatibility before restarting a failing workload repeatedly.
On the publisher, inspect the subscription’s logical slot for retained WAL. Don’t assume pg_stat_replication lag intervals are populated for every logical replication setup, or interpret logical LSN differences as the physical replay state of an entire database.
Monitor PostgreSQL replication lag as several signals
Build alerts around each workload’s freshness requirement. A reporting dashboard and an account-permission read need different consistency policies.
Track primary-to-replay byte distance, receiver connectivity, replay progress, WAL generation rate, and storage headroom. Add replica CPU, I/O latency, recovery conflicts, and slot retention. Page on sustained failures or growing backlogs rather than one noisy sample.
A periodic committed heartbeat can provide an application-visible freshness signal. Read its value through the same replica-routing path used by production traffic. Timestamp-based measurements also need synchronized clocks.
Keep that probe uncached when measuring database freshness. Separately measure the complete application path if cache staleness matters.
During an incident, record whether backlog grows, remains steady, or shrinks after each intervention. Avoid changing several settings together, because that makes the outcome harder to interpret.
Route consistency-sensitive reads deliberately
Read-after-write routing is appropriate when a successful write must appear on the next screen. Account changes, newly created records, and permission updates commonly need this behavior.
The simplest policy sends those reads to the primary. Keep lag-tolerant reporting on replicas, while budgeting for the extra primary traffic.
A fixed primary-stickiness window reduces stale reads, but it can’t guarantee freshness during unusually long replication delays. A stronger physical-replication approach captures a post-commit WAL position and uses a replica only after replay reaches it. Bound the wait and fall back to the primary, accounting for failovers and timeline changes.
Primary routing doesn’t repair an old transaction snapshot or stale cache. Start the read in an appropriate transaction and apply the relevant cache invalidation policy.
Finally, don’t authorize sensitive actions using a replica that may still show revoked access. Use the authoritative primary-backed path for that decision.
Restore freshness without hiding the cause
Useful diagnosis connects three things: the user’s stale read, the WAL stage falling behind, and the workload preventing progress. One lag number can’t establish all three.
Capture evidence before intervening, reduce avoidable pressure, and watch whether replay catches up. Keep consistency-sensitive reads on a path that satisfies their requirements while the replica recovers.