FULL AI ANALYSIS

PostgreSQL replica SQL apply thread stalls 'waiting for table metadata lock' after large ALTER TABLE on primary

Generated Oct 20, 2026, 9:41:02 AM

Analysis summary

WAL replay may need to acquire locks to modify system catalogs or relation metadata when applying DDL. If WAL application collides with other activities on standby (autovacuum, extension background workers) that hold incompatible locks, the replay can block waiting for those locks. The most likely root cause is the DDL on primary generates catalog changes that must be applied exclusively and the standby has a process holding a conflicting metadata lock (most likely autovacuum or background activity). Less likely is corruption or a replication bug but those are rarer.

Possible causes

Standby has background worker (autovacuum or user process) holding a metadata lock that conflicts with WAL-applied DDL changes

85%

Large DDL produced catalog changes that require exclusive locks; simultaneous activity on standby caused replay to block

70%

WAL apply encountering sequence that expects a different object identity due to prior out-of-band manual catalog change (rare)

20%

PostgreSQL bug in WAL application ordering for certain DDL shapes (unlikely but possible in complex partitioned scenarios)

10%

Suggested fixes

1

Diagnostic step 1

On the standby, inspect pg_locks and pg_stat_activity to identify which process holds the conflicting lock (look for relation or meta-lock types) and consider terminating nonessential background workers (autovacuum) temporarily to let replay proceed.

2

Diagnostic step 2

If replay remains blocked and no clear blocker is present, stop the standby and start in single-user or recovery mode to examine logs, but prefer safe restart over forcing catalog changes.

3

Diagnostic step 3

To prevent recurrence: avoid running heavy DDL with non-null defaults on huge tables during peak replication; instead create columns NULL, backfill in batches, then set NOT NULL in a quick transactional step.

4

Diagnostic step 4

For planned large catalog changes, schedule a maintenance window, temporarily pause autovacuum on the standby (with caution) and ensure no long-running queries will hold metadata locks.

5

Diagnostic step 5

If you cannot clear the block, prepare to rebuild standby from a fresh basebackup during a low-traffic window; document exact recovery steps and consider logical replication for more flexible DDL handling.