FULL AI ANALYSIS

PostgreSQL replica apply stalls 'waiting for lock' during bursts of DDL on primary

Generated Oct 22, 2026, 9:30:52 AM

Analysis summary

Recovery waits when WAL contains operations that require exclusive locks (DDL) if local queries hold conflicting locks or snapshots. The logs and pg_locks indicate long-lived read-only queries on the replica are holding ACCESS SHARE and preventing application of WAL records for DDL. Most likely cause: reporting queries or long snapshots on replica conflict with DDL on primary. Secondary causes include hot_standby_feedback off leading to VACUUM on primary behaving differently (less likely to directly cause waits) and logical replication or extensions interfering.

Possible causes

Long-running read-only queries on replica hold ACCESS SHARE locks, blocking WAL apply of DDL that needs stronger locks.

95%

hot_standby_feedback disabled causing bloat/autovacuum activity on primary, indirectly increasing DDL duration and conflicts.

40%

Background tasks (autovacuum or custom maintenance) on replica holding locks at inopportune times.

35%

Replication bug or extension that serializes WAL apply (less likely given manual kill fixes the problem).

10%

Suggested fixes

1

Diagnostic step 1

Identify and list long-running sessions on replica: SELECT pid, query, state, backend_start FROM pg_stat_activity WHERE state <> 'idle' ORDER BY backend_start DESC; consider setting statement_timeout or canceling old queries automatically during maintenance windows.

2

Diagnostic step 2

If reporting queries must run long, schedule DDL on primary during windows when replica is quiescent or use transactional DDL strategies (CREATE INDEX CONCURRENTLY, ALTER TABLE ... ADD COLUMN with default NULL then backfill) to reduce exclusive locks.

3

Diagnostic step 3

Consider enabling hot_standby_feedback = on on the replica to prevent query cancellations on the primary, but be aware it can delay vacuum on primary (trade-off with bloat).

4

Diagnostic step 4

Automate conflict handling: setup near-real-time monitoring to detect WAL apply stalls and either notify operators or run pg_cancel_backend/pg_terminate_backend for identified blocking read-only sessions during critical DDL windows.