Full answer
The lock queue is the trap. Even if the ALTER itself would take milliseconds, it cannot start until existing readers release their locks. Meanwhile it sits first in the queue, and later SELECTs, which would normally share the table freely, wait behind it.
Safer migration habits:
SET lock_timeout = '3s';before each DDL statement, with automatic retries, so a blocked ALTER gives up instead of stalling traffic.- Check
pg_stat_activityfor long transactions before deploying. - Prefer operations that do not rewrite the table: adding a nullable column or one with a constant default is fast in modern PostgreSQL; changing a type usually rewrites.
- Build indexes with
CREATE INDEX CONCURRENTLY. - Split migrations into small steps instead of one big transaction holding many locks.
Described from PostgreSQL's locking rules, not run here.
Key points
- DDL needs strong locks
- A waiting ALTER blocks later queries
- Use lock_timeout and retries
- Avoid table rewrites
- Create indexes concurrently
Common mistakes
- Assuming a fast DDL is safe at any time
- Running migrations while reports hold long transactions
Follow-ups
- Which ALTER operations rewrite the table?
- Why can CREATE INDEX CONCURRENTLY not run inside a transaction?
Tips
- Explain the lock queue