r/webdev • • 4h ago

3 Postgres migration patterns that silently lock production tables (and how to catch them in PRs)

We’ve all seen a migration pass staging in 50ms and then lock a production table for 20 seconds under real traffic. After reviewing dozens of incident post-mortems, almost all avoidable Postgres migration outages come down to three patterns: 1. Adding a NOT NULL column without a DEFAULT Running `ALTER TABLE users ADD COLUMN email text NOT NULL;` acquires an ACCESS EXCLUSIVE lock and rewrites/validates the table. On a busy table, every read and write queues up behind it. Fix: Add the column as nullable first, backfill in batches, then add a `NOT NULL` constraint using `NOT VALID` + `VALIDATE CONSTRAINT`. 2. Creating an index without CONCURRENTLY `CREATE INDEX idx_users_email ON users (email);` blocks all writes (`INSERT`, `UPDATE`, `DELETE`) on `users` until the index build finishes. Fix: Always use `CREATE INDEX CONCURRENTLY` (outside a transaction block). 3. Running ALTER TABLE without a lock_timeout Even a fast metadata-only `ALTER TABLE` needs an `ACCESS EXCLUSIVE` lock. If a long-running analytics query is holding a read lock on that table, your migration waits in the queue—and every subsequent query piles up behind your migration, causing a cascading outage. Fix: Always prepend `SET lock_timeout = '2s';` so the migration fails fast instead of taking down the app. To stop relying on human code review for this, I put together a lightweight static analyzer (`pgguard`) that parses SQL migrations in PRs and flags these exact lock risks before merge. Curious what other Postgres migration footguns you’ve hit in production that static checks should catch?

1 Upvotes

1 comment sorted by