← back to the blog

Changing a Column on a Big Postgres Table Without a Long Table-Rewrite Lock

A one-line ALTER TABLE events ALTER COLUMN user_id TYPE bigint; can leave requests waiting behind a table rewrite. I use this illustrative schema to explain the staged alternative; it is not a report of a measured production incident.

For an integer-to-bigint change, Postgres rewrites the table under ACCESS EXCLUSIVE: reads and writes wait. Not every type change requires a rewrite.

For a rewrite like this, I'd avoid changing a big table in one statement. I split the change into steps, and each step takes either a short lock or a weak one. You may know this as expand/contract. The examples require Postgres 12 or later. These scripts assume an indexed, non-null id column containing nonnegative integers, with enough bigint headroom for the batch bounds, and an existing user_id integer NOT NULL column.

  1. Expandadd a nullable new column
  2. Synctrigger copies new writes
  3. Backfillold rows, in small batches
  4. ValidateNOT NULL, indexes
  5. Switchrename in one transaction
  6. Contractdrop the old column
Strong locks are still needed for several DDL steps; keep those transactions short. The backfill and validation scans use weaker locks, but lock waits still need a timeout.

The lock you don't see coming

Even a statement that should be instant can stall production. To get ACCESS EXCLUSIVE, an ALTER TABLE has to wait for conflicting transactions to finish, including idle-in-transaction sessions that previously accessed the table. Finishing a query does not normally release its table lock; ending the transaction does. While the ALTER waits, new queries needing conflicting locks queue up behind it. So one open transaction plus one "instant" migration can add up to an outage.

The fix is to give up quickly rather than wait. Every DDL statement in this post runs with a lock_timeout.

Expand: add the new column

01_expand.sql
1SET lock_timeout = '3s';

2ALTER TABLE events ADD COLUMN user_id_new bigint;
  1. If the lock isn't granted in 3 seconds, the statement fails instead of blocking everyone behind it.
  2. Nullable with no default, so Postgres only updates the catalog. No rewrite.

Sync: keep the new column in sync

From the moment the column exists, new and updated rows need to fill it, or the backfill will never catch up. A trigger does that without touching application code.

02_sync_trigger.sql
SET lock_timeout = '3s';

CREATE OR REPLACE FUNCTION events_sync_user_id() RETURNS trigger AS $$
BEGIN
1  NEW.user_id_new := NEW.user_id;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

2CREATE TRIGGER events_sync_user_id
  BEFORE INSERT OR UPDATE ON events
  FOR EACH ROW EXECUTE FUNCTION events_sync_user_id();
  1. BEFORE trigger: the value is written as part of the same row version, so there's no second update.
  2. CREATE TRIGGER takes a lock that blocks writes, so the timeout still applies.

Backfill in batches

One UPDATE events SET user_id_new = user_id would lock every row it touches until it commits, create one huge burst of WAL, and leave you with nothing if it fails halfway. Small batches that commit one at a time avoid all three.

03_backfill.sql
1SET lock_timeout = '3s';

DO $$
DECLARE
  batch_start bigint := 0;
2  batch_size  bigint := 10000;
  max_id      bigint;
BEGIN
3  SELECT max(id) INTO max_id FROM events;
  WHILE batch_start <= max_id LOOP
    UPDATE events
       SET user_id_new = user_id
     WHERE id >= batch_start
       AND id <  batch_start + batch_size
4       AND user_id_new IS NULL;
5    COMMIT;
    batch_start := batch_start + batch_size;
  END LOOP;
END;
$$;
  1. Session-level setting: lock waits time out even after the DO block's internal commits.
  2. Illustrative batch width: 10,000 ID values, not a measured production batch size.
  3. Rows inserted after this point are covered by the trigger.
  4. Makes the script safe to re-run after a failure.
  5. COMMIT inside DO needs Postgres 11+ and must not run inside an explicit transaction.

Validate without a full-table lock

ALTER COLUMN ... SET NOT NULL normally scans the whole table under ACCESS EXCLUSIVE. Since Postgres 12 it skips the scan if a valid CHECK constraint already proves there are no nulls, and you can validate that constraint under a lock that doesn't block reads or writes. Run 04_validate.sql with autocommit enabled and migration-runner transaction wrapping disabled: each ALTER must commit separately so the strong lock from adding the constraint is released before validation scans the table.

04_validate.sql
SET lock_timeout = '3s';

ALTER TABLE events
  ADD CONSTRAINT events_user_id_new_not_null
1  CHECK (user_id_new IS NOT NULL) NOT VALID;

2ALTER TABLE events VALIDATE CONSTRAINT events_user_id_new_not_null;

3ALTER TABLE events ALTER COLUMN user_id_new SET NOT NULL;

ALTER TABLE events DROP CONSTRAINT events_user_id_new_not_null;

4CREATE INDEX CONCURRENTLY events_user_id_new_idx ON events (user_id_new);
  1. NOT VALID skips the initial scan of existing rows; subsequent inserts and updates must satisfy the check.
  2. Scans the table, but under SHARE UPDATE EXCLUSIVE, so traffic keeps flowing.
  3. Uses the validated constraint as proof and skips the scan.
  4. Can't run inside a transaction block. If it fails, drop the INVALID index it leaves behind and retry.

Switch, then contract

The switch drops the sync trigger, relaxes the old column's NOT NULL constraint, and renames the columns and new index in one transaction. The application never sees a half-done state. This example assumes no dependent views or foreign keys and that the target index name is free.

05_switch.sql
BEGIN;
SET LOCAL lock_timeout = '3s';

DROP TRIGGER events_sync_user_id ON events;
1ALTER TABLE events ALTER COLUMN user_id DROP NOT NULL;
2ALTER TABLE events RENAME COLUMN user_id TO user_id_old;
ALTER TABLE events RENAME COLUMN user_id_new TO user_id;
ALTER INDEX events_user_id_new_idx RENAME TO events_user_id_idx;

COMMIT;
  1. Without this, inserts that only set the new user_id fail on the old column's NOT NULL.
  2. The catalog-only switch is normally brief. lock_timeout bounds acquisition waits, not execution time or how long an acquired lock is held.

Contract is the last step: once nothing reads user_id_old, drop it and the trigger function. DROP COLUMN marks the column as dropped rather than rewriting the table, but still needs ACCESS EXCLUSIVE. Keeping it does not make rollback a rename: once the switch commits, the old column stops receiving writes. After any new writes, rolling back requires reconciling the old column, including checking that values still fit in integer, before switching back.

06_contract.sql
SET lock_timeout = '3s';

ALTER TABLE events DROP COLUMN user_id_old;
DROP FUNCTION events_sync_user_id();
There are no dumb questions
Q: Why not just run the ALTER at 3 a.m.?
A: That works if the rewrite fits in your quiet window. A rewrite's duration grows with the table, and "quiet" is rarely zero traffic.
Q: Isn't this six migrations instead of one?
A: Yes. I split the work into independently staged steps so a failed backfill batch can be retried without restarting the whole rewrite. That is not blanket reversibility: recovery after switching requires reconciliation, and dropping the old column removes its data from the live table.
Bullet points
  • Changing integer to bigint rewrites the table under ACCESS EXCLUSIVE. Split that change into expand, sync, backfill, validate, switch, contract.
  • Set lock_timeout on every DDL statement, because a waiting ALTER blocks every query queued behind it.
  • Backfill in small batches that commit one at a time and can be re-run.
  • Prove NOT NULL with a NOT VALID check plus VALIDATE, and build indexes CONCURRENTLY.
  • Keep the old column for recovery, but plan reconciliation before rollback: after the switch it no longer receives writes, and new bigint values may not fit in integer.

Cite this article

Mohamed Hosny, “Changing a Column on a Big Postgres Table Without a Long Table-Rewrite Lock”, www.mohamed-hosny.dev, . https://www.mohamed-hosny.dev/blog/changing-a-column-without-locking-production

Referencing this? Please credit Mohamed Hosny and link to the original page.

Keep reading

More from the notebook