Skip to content
GitShowcase Forum

Postgres migration locked a big table in production, how do I add a column or index safely next time?

Asked by Teodor M. · Databases and Vector Stores1 replyupdated

Short answer

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:

Written by Teodor M. ·
CiteGitShowcase 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.
  1. Member ·
    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:

    1. Adding a column, with and without a default.
    2. Adding a NOT NULL constraint to an existing column.
    3. Adding a foreign key or check constraint.
    4. 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?

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

  1. Anand R.Member ·

    Set a short lock_timeout for 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.

GitShowcase Forum. Questions and answers on shipping developer projects: dev tools, APIs, infrastructure and portfolios.