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.
- Expandadd a nullable new column
- Synctrigger copies new writes
- Backfillold rows, in small batches
- ValidateNOT NULL, indexes
- Switchrename in one transaction
- Contractdrop the old column
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
1SET lock_timeout = '3s';
2ALTER TABLE events ADD COLUMN user_id_new bigint;- If the lock isn't granted in 3 seconds, the statement fails instead of blocking everyone behind it.
- 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.
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();- BEFORE trigger: the value is written as part of the same row version, so there's no second update.
- 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.
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;
$$;- Session-level setting: lock waits time out even after the DO block's internal commits.
- Illustrative batch width: 10,000 ID values, not a measured production batch size.
- Rows inserted after this point are covered by the trigger.
- Makes the script safe to re-run after a failure.
- 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.
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);- NOT VALID skips the initial scan of existing rows; subsequent inserts and updates must satisfy the check.
- Scans the table, but under SHARE UPDATE EXCLUSIVE, so traffic keeps flowing.
- Uses the validated constraint as proof and skips the scan.
- 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.
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;- Without this, inserts that only set the new user_id fail on the old column's NOT NULL.
- The catalog-only switch is normally brief.
lock_timeoutbounds 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.
SET lock_timeout = '3s';
ALTER TABLE events DROP COLUMN user_id_old;
DROP FUNCTION events_sync_user_id();- 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.
- Changing
integertobigintrewrites the table underACCESS EXCLUSIVE. Split that change into expand, sync, backfill, validate, switch, contract. - Set
lock_timeouton 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 VALIDcheck plusVALIDATE, and build indexesCONCURRENTLY. - Keep the old column for recovery, but plan reconciliation before rollback: after the switch it no longer receives writes, and new
bigintvalues may not fit ininteger.
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.