Lesson 22 of 29Postgres in production
Zero-Downtime Migrations
Change the schema of a busy Postgres table without an outage: the lock queue, expand and contract, safe constraints, concurrent indexes and batched backfills.
You now know how Postgres locks rows and tables. This unit puts that to work on a live production database, starting with schema changes. It is 2 p.m. on a Tuesday and you merge a migration that adds one column to orders. On your laptop it took 4 milliseconds. In production the checkout API stops responding for forty seconds, the on-call channel lights up, and the migration finally finishes as if nothing happened. Nothing in the SQL was wrong. The problem was when and how it took its lock, and what the running application expected the schema to be. This lesson is the playbook senior engineers follow so that schema changes on large, busy tables are boring: which operations are safe, which need a multi-step dance, and how to sequence migrations with deploys.
Why a fast migration causes an outage
Three things turn a correct migration into an incident.
Locks. Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock, the strongest lock Postgres has. It conflicts with everything, including a plain SELECT. Holding it for a few milliseconds is fine. The trouble is getting it.
The lock queue. Postgres grants locks in order. If a long query already holds a weaker lock on the table, your ALTER waits. While it waits, every new query that conflicts with the ALTER queues behind it, even queries that would not conflict with the long query. You covered the queue in the locking lesson; here is what it does to traffic:
Press Run (⌘ Enter) to see what happens.A 30-second report and a 0.1-second ALTER produced 20-plus seconds of waiting for every API call. Your connection pool fills, health checks fail, and the load balancer starts returning errors. With a lock timeout, the ALTER gives up after 3 seconds, the queue drains, and you retry later.
Table rewrites. Some changes make Postgres copy every row into a new file, under ACCESS EXCLUSIVE, for the whole duration. On a 200 GB table that is minutes to hours of a fully blocked table.
Old code on a new schema. During a rolling deploy, old and new versions of your app run side by side for minutes. A migration that drops or renames a column the old version still reads breaks every request those instances serve, even if the lock was instant.
A long analytics query takes ACCESS SHARE on orders. Harmless on its own.
Rule one: every migration sets a lock timeout
Start every migration session with a short lock timeout, and retry with backoff when it fires:
SET lock_timeout = '3s'; -- give up if the lock is not granted quickly
SET statement_timeout = '15s'; -- and never run long while holding it
ALTER TABLE orders ADD COLUMN gift_note text;lock_timeout limits time spent waiting for a lock. statement_timeout limits the statement itself, which protects you when an operation turns out to rewrite the table. A failed attempt costs nothing: the transaction rolls back and the schema is unchanged. Migration tools usually let you run this in a loop, and teams often schedule big changes away from the nightly batch jobs and long reports that hold locks.
Also keep migrations small. Postgres DDL is transactional, which is a gift (a failed migration leaves no half-applied state), but every lock a transaction takes is held until it commits. Ten ALTERs in one transaction hold ten exclusive locks until the last one finishes. One change per migration, or a few on the same table, keeps lock time short.
Safe and unsafe operations
Learn this table. It is what migration reviewers check, and what linters like squawk (for Postgres SQL files) and strong_migrations (for Rails) flag automatically.
| Change | What Postgres does | Safe recipe |
|---|---|---|
ADD COLUMN x int (nullable, no default) | Catalog change only | Safe with a lock timeout |
ADD COLUMN x int DEFAULT 0 | Since Postgres 11, a constant default is stored in the catalog: no rewrite | Safe |
ADD COLUMN x uuid DEFAULT gen_random_uuid() | Volatile default: every row needs its own value, so the table is rewritten | Add nullable, set the default for new rows, backfill in batches |
ALTER COLUMN x TYPE bigint (from int) | Rewrites the table and rebuilds its indexes | New column, dual-write, backfill, swap |
ALTER COLUMN x TYPE text (from varchar(50)) | Binary-compatible, no rewrite | Safe |
SET NOT NULL | Scans the whole table under ACCESS EXCLUSIVE | CHECK ... NOT VALID, then VALIDATE, then SET NOT NULL |
ADD FOREIGN KEY | Checks every row while blocking writes on both tables | NOT VALID, then VALIDATE CONSTRAINT |
CREATE INDEX | Blocks writes for the whole build | CREATE INDEX CONCURRENTLY |
RENAME COLUMN, DROP COLUMN | Instant | Instant, but breaks old code: expand and contract |
The pattern behind the constraint recipes is split the check from the lock. NOT VALID adds the constraint for new writes immediately, with only a brief lock. VALIDATE CONSTRAINT then scans the existing rows under a weaker lock (SHARE UPDATE EXCLUSIVE) that lets reads and writes continue:
SET lock_timeout = '3s';
-- 1. Instant: enforced for new and updated rows, old rows not yet checked.
ALTER TABLE orders
ADD CONSTRAINT orders_tenant_id_not_null CHECK (tenant_id IS NOT NULL) NOT VALID;
-- 2. Slow scan, but reads and writes keep flowing. Run it in its own migration.
ALTER TABLE orders VALIDATE CONSTRAINT orders_tenant_id_not_null;
-- 3. Instant: Postgres 12+ sees the valid CHECK and skips its own scan.
ALTER TABLE orders ALTER COLUMN tenant_id SET NOT NULL;
ALTER TABLE orders DROP CONSTRAINT orders_tenant_id_not_null;
-- Foreign keys follow the same two-step shape.
ALTER TABLE orders
ADD CONSTRAINT orders_tenant_fk FOREIGN KEY (tenant_id) REFERENCES tenants (id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_tenant_fk;Postgres 18 also lets you add a NOT NULL constraint itself as NOT VALID and validate it later, which removes the temporary CHECK. Check the docs for your version before relying on it.
Indexes: CONCURRENTLY, and what can go wrong
A plain CREATE INDEX blocks every write to the table until the build finishes. CREATE INDEX CONCURRENTLY does not. It scans the table twice and waits for older transactions to finish, so it takes longer, but inserts and updates continue throughout.
It has rules you must know:
- It cannot run inside a transaction block. Most migration tools wrap each migration in a transaction, so you must opt out for that migration. In Alembic that means
op.get_context().autocommit_block(), which Database Migrations with Alembic in the Python Backend course shows in full. - If it fails (a duplicate value for a unique index, a deadlock, a cancel), it leaves an INVALID index behind. The planner ignores it, but every write still pays to maintain it. Find it, drop it with
DROP INDEX CONCURRENTLY, and retry. - A unique constraint or primary key can be added the same way: build the unique index concurrently, then attach it with
ALTER TABLE ... ADD CONSTRAINT ... UNIQUE USING INDEX, which is instant.
CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_customer_created_idx
ON orders (customer_id, created_at);
-- After a failed build: find invalid indexes.
SELECT indexrelid::regclass AS index_name
FROM pg_index WHERE NOT indisvalid;
DROP INDEX CONCURRENTLY IF EXISTS orders_customer_created_idx;Watch the IF NOT EXISTS: after a failed build, the invalid index does exist, so a rerun silently skips the build and you think you have an index you do not. Check indisvalid after every concurrent build.
REINDEX CONCURRENTLY rebuilds a bloated index the same way. For a bloated table, VACUUM FULL rewrites it under ACCESS EXCLUSIVE, so teams use the pg_repack extension instead. Postgres 19, now at release candidate, adds a built-in REPACK command with a CONCURRENTLY option; check the release notes before you plan around it.
Expand and contract
Some changes cannot be made safe with a flag: renaming a column, changing its type, splitting a table. For those you use expand and contract (also called parallel change). The idea is that at every moment, the schema works for both the old and the new release of your app.
Migration 1
Expand
Add home_city as a nullable column. Add a trigger (or app code) that copies writes between city and home_city.
Job
Backfill
Copy city into home_city for existing rows, in small batches, outside the migration.
Release A
Switch reads
Deploy code that reads home_city and writes both. Old instances still write city, and the trigger covers them.
Release B
Stop writing the old column
Deploy code that never touches city. Wait until no old instance, job or report uses it.
Migration 2
Contract
Drop the trigger, then drop city. Old code that still referenced it would break now, which is why this comes last.
Cleanup
Tighten
Add NOT NULL or constraints on home_city with the NOT VALID recipe, if needed.
Here is the whole dance on the course dataset. Watch both releases write while the triggers keep the columns in agreement:
Press Run (⌘ Enter) to see what happens.The WHEN NEW.city IS NOT OLD.city guards matter. Without them, each trigger's update fires the other trigger. SQLite does not recurse triggers by default, but Postgres triggers do, so always write the guard.
The same shape fixes the classic int primary key running out at 2,147,483,647. You add an id_new bigint column, dual-write it with a trigger, backfill, build a unique index concurrently, and then, in one short transaction under a lock timeout, swap the names and the primary key. It is days of work for a table with billions of rows, which is why new tables should use bigint identity columns from the start.
Deploy ordering
Expand and contract only works if migrations and code ship in the right order. Two rules cover nearly every case:
- Additive changes go before the code that needs them. Run the migration that adds
home_city, then deploy code that uses it. Many teams run migrations as a pre-deploy step for exactly this reason. - Destructive changes go after the code that stopped needing them. Remove every read and write of
city, deploy, wait for the old instances to drain, and only then drop it in a later release.
So each release is backwards compatible with the schema before and after it, and you can roll back the app without rolling back the database. That matters, because a down migration that drops a column full of new data is not a rollback, it is data loss. In practice, teams roll database changes forward with a new fix rather than backwards.
ORMs add a twist. Some cache the column list at start-up, or select every mapped column by name. If you drop a column the model still maps, old instances fail even if no code path reads it. Remove the field from the model in the release before the drop. Rails has ignored_columns for this; in SQLAlchemy you remove the mapped attribute.
Backfills: batched, idempotent, resumable
A backfill is a data change, not a schema change, so keep it out of the migration transaction. One UPDATE across 80 million rows holds row locks for its whole run, creates a burst of write-ahead log that replicas lag behind, leaves millions of dead row versions for VACUUM, and rolls back completely if it fails at 95 percent.
A good backfill job walks the table by primary key range, commits each batch, records its progress, and only touches rows that still need it, so you can kill it and start it again at any time:
Press Run (⌘ Enter) to see what happens.Details that separate a safe backfill from a risky one:
- Range by primary key, not
OFFSET. Each batch is an index range scan, and gaps in the ids are harmless. - Write the progress in the same transaction as the batch, so the checkpoint and the data can never disagree.
total_cents IS NULLmakes a rerun skip rows that are already done, and new rows written by the app (which now fills the column) are never overwritten.- Pause between batches and watch replication lag. Size batches so each one takes well under a second.
- Rows the app keeps writing during the backfill must be handled by the app or a trigger from the expand step, or you finish with a gap.
Order 11 has no items yet. The loop has a safety limit of 10 batches. What does it print?
from shopdb import connect
db = connect()
db.execute("INSERT INTO orders VALUES (11, 4, 'pending', '2025-07-20')") # no items yet
db.execute("ALTER TABLE orders ADD COLUMN total_cents INTEGER")
batches = 0
while batches < 10: # safety limit for this demo
cur = db.execute("""
UPDATE orders SET total_cents = (
SELECT SUM(quantity * unit_price_cents)
FROM order_items WHERE order_id = orders.id)
WHERE id IN (SELECT id FROM orders WHERE total_cents IS NULL ORDER BY id LIMIT 4)
""")
if cur.rowcount == 0:
break
batches += 1
print(batches)Tools and habits at work
You rarely do all of this by hand. Know what exists and what each one is for:
- Linters: squawk reads migration SQL and flags missing
CONCURRENTLY, missingNOT VALID, volatile defaults and more. strong_migrations does the same for Rails. Run them in CI on every migration. - Expand and contract automation: pgroll creates versioned views so old and new app versions see their own schema while it backfills underneath. Check its current status and limits before adopting it.
- Big table maintenance: pg_repack, and in MySQL gh-ost or pt-online-schema-change.
- Review checklist: Does it set
lock_timeout? Does any statement rewrite or scan a large table under a strong lock? Is the backfill separate? Does the deploy order keep old code working? Can it be retried safely?
CREATE UNIQUE INDEX CONCURRENTLY and fails halfway because of a duplicate email. What state is the database in?Put the steps for renaming a column with zero downtime in order.
- Tap the steps below in the right order.
Match each risky change to its safe recipe.
- ACCESS EXCLUSIVE
- The strongest Postgres table lock. Taken by most ALTER TABLE forms, it blocks even plain SELECTs while held or queued.
- lock queue
- Postgres grants conflicting lock requests in order, so a waiting ALTER blocks every later query that conflicts with it.
- lock_timeout
- A setting that makes a statement give up if it cannot get a lock within the limit, so a migration fails fast instead of stalling traffic.
- expand and contract
- Changing a schema in backwards-compatible steps: add the new shape, migrate data and code, then remove the old shape.
- NOT VALID
- Adds a CHECK or foreign key that applies to new writes immediately, leaving existing rows to a later VALIDATE CONSTRAINT under a weak lock.
- CREATE INDEX CONCURRENTLY
- Builds an index without blocking writes. It cannot run in a transaction and leaves an INVALID index if it fails.
- backfill
- A job that fills a new column or table for existing rows, ideally batched, idempotent and resumable.