Zero-downtime schema changes with expand and contract
Changing a busy Postgres table without stopping the app: the lock queue that turns a 1 ms ALTER into an outage, lock_timeout, fast defaults, NOT NULL as NOT VALID in Postgres 18, renaming a column with expand and contract, batched backfills and CREATE INDEX CONCURRENTLY.
Most schema changes in Postgres finish in a few milliseconds. See, the trouble is what they wait for before they start, and what queues up behind them while they wait. A one line ALTER TABLE can stop every request that touches the table, and the migration log will say it took 3 seconds and succeeded.
In this blog we will look at changing tables while the app keeps running: the lock queue, lock_timeout, adding columns, adding NOT NULL, renaming a column with expand and contract, backfilling in batches and building indexes with CONCURRENTLY. It is an intermediate post in my Postgres in production series, after index design and transactions and isolation levels. I ran everything on Postgres 18.7 (postgres:18-alpine) with shorty's links table (200k rows) and a clicks table with 2 million rows, same data as the index post.
The lock queue
Almost every ALTER TABLE needs an ACCESS EXCLUSIVE lock, the one lock that conflicts with plain SELECT. It's held only for a moment. But to get it, the ALTER has to wait for every transaction that has touched the table to finish. And while it waits, every new query on that table queues behind it.
I reproduced it with four sessions started at the same time. A slow report keeps a transaction open:
-- s1-report.sql
BEGIN;
SELECT count(*) FROM links;
SELECT pg_sleep(4) \g /dev/null
COMMIT;
Half a second later the migration starts, and half a second after that a normal redirect lookup from the app:
-- s2-migration.sql
SELECT pg_sleep(0.5) \g /dev/null
\timing on
ALTER TABLE links ADD COLUMN title text;
-- s3-app.sql
SELECT pg_sleep(1) \g /dev/null
\timing on
SELECT url FROM links WHERE code = 'c4ca4238a0';
A fourth session looks at pg_stat_activity at the 2 second mark. Here is what came back:
===== s2-migration.sql
ALTER TABLE links ADD COLUMN title text;
Time: 3496.294 ms (00:03.496)
===== s3-app.sql
SELECT url FROM links WHERE code = 'c4ca4238a0';
Time: 2977.054 ms (00:02.977)
===== s4-watch.sql
pid | wait_event_type | wait_event | blocked_by | query
-----+-----------------+------------+------------+------------------------------------------
338 | Timeout | PgSleep | {} | SELECT pg_sleep(4)
344 | Lock | relation | {338} | ALTER TABLE links ADD COLUMN title text;
350 | Lock | relation | {344} | SELECT url FROM links WHERE code = 'c4ca
The redirect, normally under a millisecond, took 3 seconds. It wasn't blocked by the report (two readers don't conflict), it was blocked by the ALTER, which was blocked by the report. pg_blocking_pids() shows the chain nicely. With a real app every request on that table piles up the same way, the connection pool fills and the health checks start failing.
The query I used to watch it:
SELECT pid, wait_event_type, wait_event, pg_blocking_pids(pid) AS blocked_by, left(query, 40) AS query
FROM pg_stat_activity
WHERE datname = current_database() AND state <> 'idle' AND pid <> pg_backend_pid()
ORDER BY pid;
lock_timeout first, always
The fix is to let the migration give up quickly instead of holding the queue:
SET lock_timeout = '1s';
ALTER TABLE links ADD COLUMN title text;
===== s2-migration.sql
SET lock_timeout = '1s';
ALTER TABLE links ADD COLUMN title text;
psql:/tmp/s2.sql:5: ERROR: canceling statement due to lock timeout
Time: 1004.039 ms (00:01.004)
===== s3-app.sql
SELECT url FROM links WHERE code = 'c4ca4238a0';
Time: 485.507 ms
The app still waited, but half a second only, not three. The migration failed and you run it again later, ideally in a loop with a few retries. I'd put SET lock_timeout at the top of every migration file. A failed migration you rerun is a much better day than an outage you explain.
Adding a column
Adding a nullable column, or a column with a constant default, is only a catalogue change since Postgres 11. A volatile default is different, every row needs its own value so the table gets rewritten under the exclusive lock:
ALTER TABLE clicks ADD COLUMN source text NOT NULL DEFAULT 'web';
-- Time: 4.685 ms
ALTER TABLE clicks ADD COLUMN click_uuid uuid NOT NULL DEFAULT gen_random_uuid();
-- Time: 2215.610 ms (00:02.216)
2 seconds of nobody reading clicks on my laptop, much more on a real table. For that kind of column, add it nullable, backfill in batches (below) and add the default and the constraint afterwards.
Adding NOT NULL to an existing column
ALTER COLUMN ... SET NOT NULL scans the whole table under the exclusive lock. The old workaround was a CHECK (col IS NOT NULL) NOT VALID constraint, validate it, then SET NOT NULL. Postgres 18 makes it simpler, a real not-null constraint can now be added as NOT VALID:
ALTER TABLE links ADD CONSTRAINT links_title_not_null NOT NULL title NOT VALID;
-- Time: 1.725 ms
ALTER TABLE links VALIDATE CONSTRAINT links_title_not_null;
-- Time: 14.459 ms
NOT VALID checks only new writes. VALIDATE scans the old rows but with a weaker lock, so reads and writes keep going. One thing that actually confused me: right after the NOT VALID step \d+ links already shows not null in the Nullable column. You have to look further down, at the "Not-null constraints" list, to see NOT VALID.
Not-null constraints:
"links_title_not_null" NOT NULL "title"
"links_target_url_not_null" NOT NULL "target_url" NOT VALID
Renaming a column with expand and contract
ALTER TABLE ... RENAME COLUMN is instant. That's the problem: the old version of the app is still running during a deploy and it breaks the moment the name changes. Expand and contract splits the change so every step works with both versions of the code. Say we rename links.url to target_url.
First, expand. Add the new column and a trigger that keeps both in sync, whichever one the code writes:
SET lock_timeout = '2s';
ALTER TABLE links ADD COLUMN target_url text;
CREATE FUNCTION links_sync_target_url() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.target_url IS NULL THEN
NEW.target_url := NEW.url; -- old code wrote url only
ELSIF NEW.url IS NULL OR NEW.url IS DISTINCT FROM NEW.target_url THEN
NEW.url := NEW.target_url; -- new code wrote target_url
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER links_sync_target_url
BEFORE INSERT OR UPDATE ON links
FOR EACH ROW EXECUTE FUNCTION links_sync_target_url();
An insert from the old code now fills both:
INSERT INTO links (code, url, owner_id, title)
VALUES ('oldapp0001', 'https://example.com/from-old-code', 1, 'untitled')
RETURNING code, url, target_url;
code | url | target_url
------------+-----------------------------------+-----------------------------------
oldapp0001 | https://example.com/from-old-code | https://example.com/from-old-code
Then backfill the old rows. One big UPDATE would hold row locks on the whole table for its whole run and produce one huge burst of WAL. Earlier in the same session I did exactly that for the title column, 200k rows in one statement, 1.2 seconds, and on bigger table that turns into minutes. Batches with a commit after each are kinder:
DO $$
DECLARE
last_id bigint := 0;
max_id bigint;
n bigint;
BEGIN
SELECT max(id) INTO max_id FROM links;
WHILE last_id < max_id LOOP
UPDATE links SET target_url = url
WHERE id > last_id AND id <= last_id + 10000
AND target_url IS NULL;
GET DIAGNOSTICS n = ROW_COUNT;
last_id := last_id + 10000;
COMMIT;
IF last_id % 50000 = 0 THEN
RAISE NOTICE 'up to id %, last batch % rows', last_id, n;
END IF;
PERFORM pg_sleep(0.05); -- give the app and autovacuum some room
END LOOP;
END $$;
NOTICE: up to id 50000, last batch 10000 rows
NOTICE: up to id 100000, last batch 10000 rows
NOTICE: up to id 150000, last batch 10000 rows
NOTICE: up to id 200000, last batch 10000 rows
DO
Time: 3961.824 ms (00:03.962)
COMMIT inside a DO block works since Postgres 11, as long as you don't run it inside an outer transaction. Walking by primary key range keeps each batch an index range scan. After it, SELECT count(*) FILTER (WHERE target_url IS NULL) FROM links returned 0, and I added the not-null constraint with the NOT VALID then VALIDATE pair from above.
Now deploy the code that reads and writes target_url only. The trigger fills url for it, which matters because url is still NOT NULL:
INSERT INTO links (code, target_url, owner_id, title)
VALUES ('newapp0001', 'https://example.com/from-new-code', 1, 'untitled')
RETURNING code, url, target_url;
code | url | target_url
------------+-----------------------------------+-----------------------------------
newapp0001 | https://example.com/from-new-code | https://example.com/from-new-code
Finally, contract, once no running version touches url. That means after the deploy has fully finished, not in the same release:
SET lock_timeout = '2s';
BEGIN;
DROP TRIGGER links_sync_target_url ON links;
DROP FUNCTION links_sync_target_url();
ALTER TABLE links DROP COLUMN url;
COMMIT;
Four steps and three deploys for a rename. It's quite a lot. For a small internal table that nobody hits during the deploy I'd still just rename, honestly. For the table behind every redirect, this is the way.
CREATE INDEX CONCURRENTLY
A normal CREATE INDEX blocks writes for the whole build. CONCURRENTLY doesn't, but it has two catches. It can't run inside a transaction:
BEGIN;
CREATE INDEX CONCURRENTLY clicks_country ON clicks (country);
ERROR: CREATE INDEX CONCURRENTLY cannot run inside a transaction block
Most migration tools wraps each file in a transaction, so you'll hit this. With goose, which shorty uses (see the local dev stack post), put -- +goose NO TRANSACTION at the top of that migration file:
-- +goose NO TRANSACTION
-- +goose Up
CREATE INDEX CONCURRENTLY clicks_country ON clicks (country);
-- +goose Down
DROP INDEX CONCURRENTLY clicks_country;
The second catch is worse. If the build fails, the index stays behind marked invalid. I made it fail on purpose with a unique index over duplicate values:
CREATE UNIQUE INDEX CONCURRENTLY links_target_url_key ON links (target_url);
ERROR: could not create unique index "links_target_url_key"
DETAIL: Key (target_url)=(https://example.com/a) is duplicated.
CONTEXT: parallel worker
SELECT indexrelid::regclass AS index, indisvalid
FROM pg_index WHERE indrelid = 'links'::regclass;
index | indisvalid
----------------------+------------
links_pkey | t
links_code_key | t
links_target_url_key | f
The invalid index is never used for reads but is still updated on every write. If your migration says CREATE INDEX CONCURRENTLY IF NOT EXISTS, a rerun sees the name and skips it, which is the worst of both. Drop it with DROP INDEX CONCURRENTLY and run again. I'd add the indisvalid query to whatever checks you run after a deploy.
Where the migration runs
None of this helps if the migration and the new code go out in the wrong order. I run migrations as a separate one-off step before the service update, as in running goose migrations as a one-off ECS task, so an expand step is always in place before code that needs it. And if several branches add migrations at once, goose version collisions is worth a read too.
All SQL from this post is in plain files, I ran them with docker exec -i pg18 psql -U postgres -d shorty -f, and docker rm -f pg18 cleans up afterwards.