Postgres migration locked a big table in production, how do I add a column or index safely next time?
Embarrassing one. Last week a routine migration on our events table (a few hundred million rows) blocked writes for several minutes during business hours. The migration was two statements:
Cite
GitShowcase Forum, "Postgres migration locked a big table in production, how do I add a column or index safely next time?", https://gitshowcase.com/forum/discuss/postgres-migration-locked-a-big-table-in-production-how-do-i-add/, accessed 2026-12-02.ALTER TABLE events ADD COLUMN source text NOT NULL DEFAULT 'web'; CREATE INDEX events_source_idx ON events (source);Our migration tool wraps each file in a transaction. While it ran, inserts piled up in the application, connections filled and the on call person had a bad hour. We are on a managed Postgres, a recent major version.
I know in general that some DDL takes heavy locks, but I never internalised which forms are safe and which are not. I would like a reliable rule set for the common cases:
- Adding a column, with and without a default.
- Adding a NOT NULL constraint to an existing column.
- Adding a foreign key or check constraint.
- Creating an index.
I would also like to know how to make a migration fail fast instead of queuing behind a long transaction and then blocking everyone behind it. What is your checklist before running DDL on a hot table?
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.
1 answer
- Anand R.Member ·
Set a short
lock_timeoutfor the migration session so it gives up instead of waiting forever for its lock. A DDL statement that queues behind a long running transaction also blocks every query that arrives after it, and that is usually the real outage. Fail, retry in a quiet moment, and alert on long transactions.