Your monitoring says a PostgreSQL standby is minutes behind the primary. Read-after-write requests return stale rows, a failover would lose or delay recent commits, and replay_lag in pg_stat_replication keeps growing. The fix depends on where the WAL is stuck. WAL can be waiting to leave the primary, waiting to be written or flushed on the standby, or sitting on the standby's disk waiting for the startup process to replay it. On PostgreSQL 16, 17, and 18, each of those stages has its own column, and each has different causes: network bandwidth, standby disk I/O, heavy WAL from bulk loads and index builds, or queries on the standby that hold replay back. This guide shows how to find the lagging stage first, then fix the cause behind it, for both streaming and logical replication.
- Compare
sent_lsn,write_lsn,flush_lsn, andreplay_lsninpg_stat_replicationwithpg_wal_lsn_diff(). The first large gap names the stage that lags. - A gap before
write_lsnis network or sender capacity; between write and flush it is standby disk; between flush and replay it is replay speed or recovery conflicts. - WAL replay runs in one startup process, so bulk loads,
VACUUM FULL, and index builds on the primary can outrun it. Spread that work out rather than adding standby CPU. max_standby_streaming_delay(default 30s) andhot_standby_feedbacktrade canceled standby queries against replay lag and primary bloat. Pick per standby role.- Logical replication lag is a different problem: check
pg_stat_subscriptionon the subscriber and the slot'sconfirmed_flush_lsnon the publisher.
Scope and review date: November 2026. This post covers physical streaming replication and built-in logical replication on PostgreSQL 16, 17, and 18, with notes on PostgreSQL 19, released on 19 November 2026, and on Amazon RDS for PostgreSQL. Commands, defaults, and column names were checked against the PostgreSQL documentation and release notes. They were not run in a lab, so test them on a staging pair before you change production settings. Setting up lag monitoring and alerting is covered in PostgreSQL replication monitoring: lag, slots, and failover readiness; this post starts once the alert has fired.
Which stage of PostgreSQL replication is lagging?
Every WAL record goes through four positions on its way to a standby, and pg_stat_replication on the primary reports each of them per standby. The PostgreSQL 18 statistics documentation defines sent_lsn as the last WAL location sent on the connection, write_lsn as written to disk by the standby, flush_lsn as flushed to disk by the standby, and replay_lsn as replayed into the database on the standby.
The four WAL positions a standby reports
Each gap between neighbors points at a different cause
Read it left to right: the first large byte gap is the stage to fix. Gaps further right are usually a consequence of it.
Run this on the primary. It turns the positions into byte gaps between neighboring stages and shows the three time-based lag columns next to them.
SELECT application_name, client_addr, state, sync_state,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn)) AS not_sent,
pg_size_pretty(pg_wal_lsn_diff(sent_lsn, write_lsn)) AS sent_not_written,
pg_size_pretty(pg_wal_lsn_diff(write_lsn, flush_lsn)) AS written_not_flushed,
pg_size_pretty(pg_wal_lsn_diff(flush_lsn, replay_lsn)) AS flushed_not_replayed,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication
ORDER BY application_name;Interpretation: a large not_sent or sent_not_written means WAL is not reaching the standby fast enough: the network, TCP buffers, or the WAL sender. A large written_not_flushed points at standby disk fsync. A large flushed_not_replayed with small earlier gaps means the WAL has arrived safely and replay is the bottleneck. The time columns are cumulative: write_lag, flush_lag, and replay_lag each measure from the primary's local flush to the standby's acknowledgment of that stage.
A standby whose replay is the bottleneck
Illustrative output, shaped like pg_stat_replication on PostgreSQL 18
Diagnosis: WAL arrives and is flushed within milliseconds, but gigabytes wait for replay. Look at heavy WAL and recovery conflicts, not at the network.
The documentation notes that on a fully caught-up idle system the lag columns show the last measured value briefly and then revert to NULL. NULL with zero byte gaps means no lag, not missing data.
How do I confirm the lag from the standby itself?
The primary's view depends on feedback messages the standby sends at most every wal_receiver_status_interval (default 10s), and it shows nothing if the standby is disconnected. On the standby, compare what has been received with what has been replayed. The recovery information functions give both positions directly.
-- On the standby
SELECT pg_last_wal_receive_lsn() AS received,
pg_last_wal_replay_lsn() AS replayed,
pg_size_pretty(pg_wal_lsn_diff(pg_last_wal_receive_lsn(),
pg_last_wal_replay_lsn())) AS replay_backlog,
pg_get_wal_replay_pause_state() AS pause_state,
now() - pg_last_xact_replay_timestamp() AS since_last_replayed_commit;Interpretation: a growing replay_backlog confirms a replay problem. A pause_state of paused means someone called pg_wal_replay_pause(), and pg_wal_replay_resume() fixes it. since_last_replayed_commit also grows when the primary simply has no writes, so never alert on it alone.
Two more checks rule out causes that look like lag but are not. If the WAL receiver is down, the standby falls back to restore_command and replays from the archive in file-sized steps. If recovery_min_apply_delay is set, the lag is intentional.
SELECT status, sender_host, last_msg_receipt_time, latest_end_lsn
FROM pg_stat_wal_receiver;
SHOW recovery_min_apply_delay;Interpretation: no row, or a status other than streaming, means the standby is not streaming; fix the connection before tuning anything. A non-zero recovery_min_apply_delay delays each commit by that interval on purpose, so subtract it from the lag you measure.
PostgreSQL 19 adds a pg_stat_recovery view, documented in the PostgreSQL 19 monitoring chapter. It reports the last replayed WAL record, the record currently being replayed, the timestamp of the last replayed commit, and the pause state in one row. It also adds a connecting value to pg_stat_wal_receiver.status. On 16 to 18, the functions above give the same information.
How do I fix lag before the standby has written or flushed the WAL?
If the gap is in not_sent or sent_not_written, the standby cannot receive WAL as fast as the primary generates it. Start by measuring how much WAL the primary produces, because that is the bandwidth replication needs.
-- psql on the primary: WAL generated in one minute
SELECT pg_current_wal_lsn() AS start_lsn \gset
SELECT pg_sleep(60);
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'start_lsn')) AS wal_per_minute;Interpretation: compare the figure with the throughput the link between the two hosts can sustain. Run it at peak and during batch jobs, not at a quiet time.
The fixes, in order of effort:
- Compress full-page images.
wal_compressioncompresses the full-page images that make up a large share of WAL right after each checkpoint. It isoffby default and acceptspglz,lz4, andzstd; LZ4 and Zstandard arrived in PostgreSQL 15 and need a build with that library. It costs CPU on the primary and does not compress ordinary row records. - Move the standby closer or widen the link. No setting can push more bytes per second through a link than it carries.
- Reduce WAL volume at the source, covered in the next section.
SHOW wal_compression;
ALTER SYSTEM SET wal_compression = 'lz4'; -- errors if the build lacks LZ4
SELECT pg_reload_conf();Interpretation: no restart is needed. Measure wal_per_minute again across a few checkpoints to see the saving.
If the gap is in written_not_flushed, the standby's WAL disk is slow to fsync. On PostgreSQL 18, pg_stat_io includes WAL rows, including WAL receiver activity, so you can see write and fsync time on the standby without host tools.
-- On the standby, PostgreSQL 18 (set track_wal_io_timing = on for the time columns)
SELECT backend_type, context, writes, write_bytes, write_time, fsyncs, fsync_time
FROM pg_stat_io
WHERE object = 'wal' AND (writes > 0 OR fsyncs > 0);Interpretation: divide fsync_time by fsyncs for the average fsync in milliseconds. If it is high, the standby's storage is smaller or busier than the primary's. Give the standby the same storage class as the primary, and keep backups and reporting exports off the WAL volume.
Setting fsync = off or full_page_writes = off on a standby makes it unsafe to promote after a crash. The documentation warns that turning off full_page_writes risks unrecoverable or silent corruption.
Why does replay fall behind during bulk loads, VACUUM FULL, and index builds?
On a standby, WAL is replayed by a single startup process. The primary generates WAL from many backends at once, so any burst that is cheap to produce in parallel can be slow to apply serially. The usual sources are bulk COPY and large INSERT ... SELECT jobs, VACUUM FULL and CLUSTER, which write a new copy of the whole table, CREATE INDEX and REINDEX on large tables, and large UPDATE or DELETE backfills.
Checkpoints add to this. With full_page_writes = on (the default), the first change to each page after a checkpoint writes the whole page into WAL. The WAL configuration documentation notes that raising the checkpoint interval reduces how often full-page images are needed. Frequent requested checkpoints, triggered when WAL reaches max_wal_size (default 1 GB), mean more full-page images and more WAL to replay.
-- On the primary, PostgreSQL 17 and 18
SELECT num_timed, num_requested FROM pg_stat_checkpointer;
-- On the standby: what is the startup process waiting on?
SELECT pid, wait_event_type, wait_event
FROM pg_stat_activity
WHERE backend_type = 'startup';Interpretation: if num_requested grows faster than num_timed, checkpoints are driven by WAL volume; raise max_wal_size and consider a longer checkpoint_timeout (default 5min), accepting longer crash recovery. A startup process that mostly waits on data file reads is I/O bound. A startup process waiting on a recovery conflict wait event is held by standby queries, covered in the next section.
What helps replay itself:
- Recovery prefetch.
recovery_prefetch(PostgreSQL 15 and later, defaulttry) reads ahead in the WAL for blocks that are not in shared buffers. Its reach is set bywal_decode_buffer_size(default 512kB) andmaintenance_io_concurrency. Confirm it is not set tooff. - Match the standby to the primary. A standby with smaller
shared_buffersor slower storage reads more pages from disk during replay. - Change the job, not the standby. Batch backfills into chunks with pauses, run
VACUUM FULLand large index builds in a low-traffic window, and preferpg_repack, orREPACK CONCURRENTLYon PostgreSQL 19, where a full table rewrite is unavoidable. Have batch jobs checkreplay_lagbetween chunks and sleep while it is above your threshold.
Are queries on the standby holding replay back?
A hot standby that serves reads can conflict with incoming WAL. The hot standby documentation lists the causes: access exclusive locks from DDL on the primary, VACUUM cleanup of rows a standby snapshot can still see, cleanup of a page a standby query is reading, and visibility map updates that conflict with index-only scans. The standby has two choices: pause replay until the query ends, or cancel the query.
max_standby_streaming_delay decides between them. The default is 30s, and -1 waits forever. The documentation is specific that this limit is compared with the time since the WAL was received, not with each query's runtime, so once a standby is already behind, conflicting queries get less grace, not more. Queries that are canceled fail with an error that reports a conflict with recovery and can be retried.
-- On the standby: canceled queries by conflict type since the last reset
SELECT datname, confl_snapshot, confl_lock, confl_bufferpin,
confl_deadlock, confl_tablespace
FROM pg_stat_database_conflicts
WHERE datname = current_database();
-- Longest open transactions on the standby
SELECT pid, usename, now() - xact_start AS xact_age, state, left(query, 60) AS query
FROM pg_stat_activity
WHERE backend_type = 'client backend' AND xact_start IS NOT NULL
ORDER BY xact_start
LIMIT 10;Interpretation: rising confl_snapshot means VACUUM on the primary is removing rows that standby queries still need. Rising confl_lock points at DDL or explicit locks on the primary. If replay_lag climbs while one long query runs and drops the moment it finishes, that query is holding replay. Set log_recovery_conflict_waits = on to log every wait that exceeds deadlock_timeout.
hot_standby_feedback = on stops most snapshot conflicts by telling the primary which rows standby queries still need. The cost moves to the primary: the documentation warns that it can cause table bloat there, because VACUUM cannot remove those dead rows while the standby query runs. One standby cannot serve both roles well, so set each one for its job.
Failover standby and reporting standby settings
Switch roles to see which side of the trade-off each one takes
Failover standby
| Setting or effect | Failover standby |
|---|---|
max_standby_streaming_delay | Short, such as the 30s default or lower |
hot_standby_feedback | off |
| Long analytical queries | Not routed here |
| Replay lag from conflicts | Bounded by the delay setting |
| Standby queries | Canceled when they conflict |
| Bloat on the primary | Not caused by this standby |
Reporting standby
| Setting or effect | Reporting standby |
|---|---|
max_standby_streaming_delay | Long, such as 15min, or -1 |
hot_standby_feedback | on, with bloat monitored on the primary |
| Long analytical queries | Routed here |
| Replay lag from conflicts | Can grow while a long query runs |
| Standby queries | Rarely canceled |
| Bloat on the primary | Possible while long queries run |
Rule: never promote a reporting standby without checking its replay lag first. Keep failover candidates on short delays and route long queries elsewhere.
The settings are reloadable on the standby; setting them on the primary has no effect.
# postgresql.conf on a failover standby
hot_standby_feedback = off
max_standby_streaming_delay = 30s
log_recovery_conflict_waits = on
# postgresql.conf on a reporting standby
hot_standby_feedback = on
max_standby_streaming_delay = 15min
log_recovery_conflict_waits = onInterpretation: 15min is an example. Set it from the longest report you will let delay replay, and alert on that standby separately from failover candidates.
How does synchronous_commit change what lag costs you?
With asynchronous replication, lag costs freshness on the standby and recent commits at failover. With synchronous replication, lag moves into commit latency on the primary. The synchronous_commit level decides which stage each commit waits for, and the documentation maps each lag column to the level it measures: write_lag to remote_write, flush_lag to on, and replay_lag to remote_apply.
SELECT name, setting
FROM pg_settings
WHERE name IN ('synchronous_commit', 'synchronous_standby_names');
SELECT application_name, sync_state, write_lag, flush_lag, replay_lag
FROM pg_stat_replication;Interpretation: with synchronous_standby_names set and synchronous_commit = on, every commit waits for flush_lag. With remote_apply, every commit also waits for replay, so a recovery conflict on a synchronous standby stalls writes on the primary. Do not route long reports to a remote_apply standby.
Quorum syntax such as ANY 1 (s1, s2) lets a commit proceed when the faster standby acknowledges, and a batch job can run SET LOCAL synchronous_commit TO local so bulk work does not wait on standbys.
PostgreSQL 19 offers a different answer for read-after-write traffic. The WAIT FOR LSN command lets a session on a standby wait until a given LSN has been replayed, so the application can read its own write without making every commit synchronous.
-- PostgreSQL 19. On the primary, after the write:
SELECT pg_current_wal_insert_lsn(); -- for example 0/0306EE20
-- On the standby, before the read:
WAIT FOR LSN '0/0306EE20' WITH (TIMEOUT '200ms', NO_THROW);Interpretation: the command returns success, timeout, or not in recovery. On timeout, send that read to the primary. The default mode is standby_replay, and a timeout of 0 waits indefinitely, so always set one.
How do I fix logical replication lag?
Logical replication lag has different causes, and the streaming replication columns do not describe it well. The documentation notes that the lag time columns depend on the decoding plugin sending tracking messages. Measure it from both ends instead: the subscriber reports what it has received and applied, and the publisher's slot shows how far the subscriber has confirmed.
-- On the subscriber
SELECT subname, worker_type, received_lsn, latest_end_lsn,
last_msg_receipt_time, latest_end_time
FROM pg_stat_subscription;
-- On the publisher
SELECT slot_name, active, wal_status,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS behind
FROM pg_replication_slots
WHERE slot_type = 'logical';Interpretation: a growing behind with an active slot means the subscriber is applying more slowly than the publisher writes. An inactive slot means the subscription is disabled or erroring; check the subscriber log and pg_stat_subscription_stats. A wal_status of unreserved or lost means the slot is about to lose, or has lost, the WAL it needs.
The common causes and their fixes:
- One apply worker per subscription. Changes for a subscription are applied in commit order by its leader apply worker. PostgreSQL 16 added
streaming = parallel, which applies large in-progress transactions with parallel workers, and PostgreSQL 18 madeparallelthe default for new subscriptions. For many small transactions, split the tables across several publications and subscriptions so each has its own worker, withinmax_logical_replication_workers(default 4). - Updates and deletes without a usable key. With
REPLICA IDENTITY FULLand no index, each change can scan the table. PostgreSQL 16 lets the subscriber use a B-tree index in that case; a primary key on the subscriber is still the fix. - Decoding spill on the publisher. Transactions larger than
logical_decoding_work_memspill to disk unless they are streamed.
-- On the publisher: is decoding spilling to disk?
SELECT slot_name, spill_txns, spill_bytes, stream_txns, stream_bytes, total_bytes
FROM pg_stat_replication_slots;
-- On the subscriber: apply large transactions with parallel workers (PostgreSQL 16+)
ALTER SUBSCRIPTION app_sub SET (streaming = parallel);Interpretation: high spill_bytes relative to total_bytes means decoding is writing to disk; raise logical_decoding_work_mem or enable streaming. Parallel workers come from max_parallel_apply_workers_per_subscription (default 2), which itself draws from max_logical_replication_workers.
PostgreSQL 19 adds a mem_exceeded_count column to pg_stat_replication_slots and renames sync_error_count to sync_table_error_count in pg_stat_subscription_stats, so update monitoring queries before you upgrade. To stop a lagging logical slot from filling the primary's disk, cap it with max_slot_wal_keep_size, and on PostgreSQL 18 consider idle_replication_slot_timeout for slots that are abandoned rather than slow. Retention is covered in PostgreSQL WAL file retention.
What does the RDS ReplicaLag metric actually measure?
On Amazon RDS for PostgreSQL, the CloudWatch ReplicaLag metric is a time in seconds. The RDS replication monitoring guide states that it reports the result of this query on the replica:
SELECT extract(epoch from now() - pg_last_xact_replay_timestamp()) AS "ReplicaLag";Interpretation: the metric is the age of the last replayed commit, not a byte gap. If the source has no write traffic, it rises even though the replica is fully caught up, so read it next to the source's write activity. The same guide points to mismatched instance classes or storage types between source and replica as a common cause, and suggests watching TransactionLogsGeneration for WAL volume and OldestReplicationSlotLag and TransactionLogsDiskUsage for slot backlog. The stage diagnosis above still applies: connect to the source and run the pg_stat_replication query. For the choice between Multi-AZ and read replicas, see RDS Multi-AZ vs read replicas.
What is the step-by-step runbook for replication lag?
Work through the stages in order; each step finds the cause or rules out a stage.
Replication lag runbook for PostgreSQL 16 to 18
Read-only checks first; each later step changes one thing
-
Find the stage on the primary
Compute byte gaps between sent, write, flush, and replay. The first large gap names the stage.
SELECT application_name, pg_wal_lsn_diff(sent_lsn, write_lsn), pg_wal_lsn_diff(flush_lsn, replay_lsn), replay_lag FROM pg_stat_replication; -
Rule out the non-causes on the standby
Check that the WAL receiver is streaming, replay is not paused, and no apply delay is set.
SELECT status FROM pg_stat_wal_receiver; SELECT pg_get_wal_replay_pause_state(); SHOW recovery_min_apply_delay; -
Look for a job on the primary
Find bulk loads,
VACUUM FULL, index builds, or backfills that started when lag began, and measure WAL per minute.SELECT pid, now() - query_start, left(query, 50) FROM pg_stat_activity WHERE state = 'active' ORDER BY query_start; -
Check recovery conflicts on the standby
If replay waits on a conflict, find the long transaction holding it and decide whether to cancel it.
SELECT wait_event FROM pg_stat_activity WHERE backend_type = 'startup'; -
Relieve the immediate pressure
Pause or slow the batch job, or cancel the blocking standby query. Lag should start falling within minutes.
SELECT pg_cancel_backend(<pid>); -
Fix the stage for good
Network:
wal_compressionor a wider link. Disk: match standby storage. Replay: pace jobs and checkpoints. Conflicts: set the standby role. -
Confirm and record
Watch byte gaps return to near zero through the next peak, then add the cause to your alert's notes.
Main risk: do not promote a lagging standby to "fix" lag. Promotion stops replay where it is, and asynchronous commits it has not received are lost.
Frequently asked questions
How do I check replication lag in PostgreSQL?
On the primary, query pg_stat_replication for write_lag, flush_lag, and replay_lag, and use pg_wal_lsn_diff() on sent_lsn, write_lsn, flush_lsn, and replay_lsn for byte gaps. On the standby, compare pg_last_wal_receive_lsn() with pg_last_wal_replay_lsn(). The first large byte gap tells you which stage is slow.
Why is replay_lag high when write_lag and flush_lag are low?
The WAL has reached the standby's disk, but the startup process cannot apply it fast enough. The usual causes are heavy WAL from bulk loads, VACUUM FULL, or index builds on the primary, which a single replay process applies serially, or standby queries that conflict with replay and hold it for up to max_standby_streaming_delay. Check pg_stat_database_conflicts and the startup process wait event.
Does hot_standby_feedback reduce replication lag?
It reduces snapshot recovery conflicts, so fewer standby queries are canceled and replay pauses less for that reason. It does not speed up replay, and it can cause table bloat on the primary because VACUUM keeps dead rows that standby queries still need. Enable it on reporting standbys with bloat monitoring, and keep failover standbys on short delays instead.
Why does RDS ReplicaLag rise when the database is idle?
Amazon RDS for PostgreSQL computes ReplicaLag as the time since the last replayed transaction, using pg_last_xact_replay_timestamp(). When the source has no new commits, that time keeps growing even though the replica has replayed everything. Compare it with write activity on the source, or check byte gaps in pg_stat_replication, before treating it as real lag.
How do I fix logical replication lag in PostgreSQL?
Measure the slot's confirmed_flush_lsn against pg_current_wal_lsn() on the publisher and check pg_stat_subscription on the subscriber. Then fix the cause: add primary keys on subscriber tables, use streaming = parallel for large transactions (the default for new subscriptions from PostgreSQL 18), split busy tables into separate subscriptions, and raise logical_decoding_work_mem if decoding spills to disk.
Key takeaways
- Diagnose before tuning: byte gaps between
sent_lsn,write_lsn,flush_lsn, andreplay_lsnname the lagging stage. - Network lag is fixed with bandwidth, proximity, and
wal_compression; flush lag with standby storage that matches the primary. - Replay is serial, so pace bulk loads, rewrites, and index builds, and keep checkpoints from being forced by
max_wal_size. - Decide per standby whether queries or replay win: short
max_standby_streaming_delayfor failover, feedback and longer delays for reporting. - Treat logical replication and the RDS
ReplicaLagmetric separately; neither reads like streaming replication lag.
Fixing PostgreSQL replication lag with JusDB
Replication lag is often the first sign that a standby or a reporting workload has outgrown the replication design. JusDB's PostgreSQL engineers can review your replication topology, find which stage lags, and plan the settings and workload changes that bring each standby back within the lag your failover plan assumes.
If you are planning standbys, failover, or read scaling for PostgreSQL, see PostgreSQL high availability services for how JusDB can help design, test, and run the setup.