← Back to SQL, page 18

sql-0358 · Hard senior

A simple ALTER TABLE ADD COLUMN froze the whole application for minutes. Why, and how do you avoid it?

ALTER TABLE needs an ACCESS EXCLUSIVE lock. It waited behind a long-running query or transaction, and every new query on the table queued behind the waiting ALTER, so the table became unusable. Set a short lock_timeout before DDL and retry, and make sure no long transactions are running when migrations deploy.

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_activity for 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