Skip to content

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.

20 min read0/5 questions

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:

Pythonlock_queue.py
# A small model of how Postgres queues lock requests on one table.# A plain SELECT takes ACCESS SHARE; ALTER TABLE takes ACCESS EXCLUSIVE.def conflicts(a, b): return "ACCESS EXCLUSIVE" in (a, b) def simulate(lock_timeout=None): reqs = [{"who": "report", "mode": "ACCESS SHARE", "at": 0.0, "runs": 30.0}] reqs.append({"who": "ALTER", "mode": "ACCESS EXCLUSIVE", "at": 1.0, "runs": 0.1}) for t in range(2, 9): reqs.append({"who": f"api@{t}s", "mode": "ACCESS SHARE", "at": float(t), "runs": 0.05}) done = [] for r in reqs: t = r["at"] moved = True while moved: moved = False for p in done: if not conflicts(p["mode"], r["mode"]): continue if p["start"] is not None and p["start"] <= t < p["end"]: t, moved = p["end"], True # it holds a conflicting lock elif p["at"] <= t < p["wait_end"]: t, moved = p["wait_end"], True # it waits ahead of us if lock_timeout is not None and r["mode"] == "ACCESS EXCLUSIVE" and t - r["at"] > lock_timeout: r.update(start=None, end=None, wait_end=r["at"] + lock_timeout) print(f"{r['who']:8} gave up after {lock_timeout:.0f}s (lock_timeout), retry later") else: r.update(start=t, end=t + r["runs"], wait_end=t) print(f"{r['who']:8} waited {t - r['at']:5.2f}s") done.append(r) print("Without lock_timeout:")simulate()print("\nWith SET lock_timeout = '3s':")simulate(lock_timeout=3)
Output
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.

One ALTER behind one slow query
ReportMigrationAPIPostgresSELECT ... (30 s)ALTER TABLE orders ADD COLUMN ...SELECT * FROM orders WHERE id = $1(no reply for 28 s)SET lock_timeout = '3s'

A long analytics query takes ACCESS SHARE on orders. Harmless on its own.

1/5

Rule one: every migration sets a lock timeout

Start every migration session with a short lock timeout, and retry with backoff when it fires:

migrations/0042_add_gift_note.sql
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.

ChangeWhat Postgres doesSafe recipe
ADD COLUMN x int (nullable, no default)Catalog change onlySafe with a lock timeout
ADD COLUMN x int DEFAULT 0Since Postgres 11, a constant default is stored in the catalog: no rewriteSafe
ADD COLUMN x uuid DEFAULT gen_random_uuid()Volatile default: every row needs its own value, so the table is rewrittenAdd nullable, set the default for new rows, backfill in batches
ALTER COLUMN x TYPE bigint (from int)Rewrites the table and rebuilds its indexesNew column, dual-write, backfill, swap
ALTER COLUMN x TYPE text (from varchar(50))Binary-compatible, no rewriteSafe
SET NOT NULLScans the whole table under ACCESS EXCLUSIVECHECK ... NOT VALID, then VALIDATE, then SET NOT NULL
ADD FOREIGN KEYChecks every row while blocking writes on both tablesNOT VALID, then VALIDATE CONSTRAINT
CREATE INDEXBlocks writes for the whole buildCREATE INDEX CONCURRENTLY
RENAME COLUMN, DROP COLUMNInstantInstant, 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:

migrations/0043_orders_tenant_not_null.sql
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.

Renaming customers.city to home_city in six steps
  1. Migration 1

    Expand

    Add home_city as a nullable column. Add a trigger (or app code) that copies writes between city and home_city.

  2. Job

    Backfill

    Copy city into home_city for existing rows, in small batches, outside the migration.

  3. Release A

    Switch reads

    Deploy code that reads home_city and writes both. Old instances still write city, and the trigger covers them.

  4. Release B

    Stop writing the old column

    Deploy code that never touches city. Wait until no old instance, job or report uses it.

  5. Migration 2

    Contract

    Drop the trigger, then drop city. Old code that still referenced it would break now, which is why this comes last.

  6. 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:

Pythonexpand_contract.py
from shopdb import connect, showimport sqlite3db = connect() # Old release: reads and writes customers.city.def old_app_insert(name, city): db.execute("INSERT INTO customers (name, city, created_at) VALUES (?, ?, '2025-08-01')", (name, city)) # New release: reads and writes customers.home_city.def new_app_insert(name, city): db.execute("INSERT INTO customers (name, home_city, created_at) VALUES (?, ?, '2025-08-01')", (name, city)) # Step 1, expand: add the new column and keep both columns in sync with triggers.db.executescript("""ALTER TABLE customers ADD COLUMN home_city TEXT; CREATE TRIGGER customers_sync_insert AFTER INSERT ON customersBEGIN UPDATE customers SET home_city = COALESCE(NEW.home_city, NEW.city), city = COALESCE(NEW.city, NEW.home_city) WHERE id = NEW.id;END;CREATE TRIGGER customers_sync_old AFTER UPDATE OF city ON customersWHEN NEW.city IS NOT OLD.cityBEGIN UPDATE customers SET home_city = NEW.city WHERE id = NEW.id;END;CREATE TRIGGER customers_sync_new AFTER UPDATE OF home_city ON customersWHEN NEW.home_city IS NOT OLD.home_cityBEGIN UPDATE customers SET city = NEW.home_city WHERE id = NEW.id;END;""") # Step 2, backfill existing rows (in batches on a real table).db.execute("UPDATE customers SET home_city = city WHERE home_city IS NULL AND city IS NOT NULL") # Step 3, both releases run side by side during the rolling deploy.old_app_insert("Edsger Dijkstra", "Austin")new_app_insert("Donald Knuth", "Stanford")db.execute("UPDATE customers SET city = 'Cambridge' WHERE id = 1") # old code editsshow(db, "SELECT id, name, city, home_city FROM customers WHERE id IN (1, 9, 10)") # Step 4, contract: once no running code touches city, drop the triggers and the column.db.executescript("""DROP TRIGGER customers_sync_insert;DROP TRIGGER customers_sync_old;DROP TRIGGER customers_sync_new;ALTER TABLE customers DROP COLUMN city;""")try: old_app_insert("Barbara Again", "Boston")except sqlite3.OperationalError as exc: print("an old instance still running would now fail:", exc)
Output
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:

Pythonbackfill.py
from shopdb import connect, showdb = connect() # The schema migration: fast, metadata only.db.executescript("""ALTER TABLE orders ADD COLUMN total_cents INTEGER;CREATE TABLE backfill_progress (job TEXT PRIMARY KEY, last_id INTEGER NOT NULL);INSERT INTO backfill_progress VALUES ('orders_total', 0);""") BATCH = 3 def run_backfill(crash_after=None): batches = 0 while True: (last_id,) = db.execute( "SELECT last_id FROM backfill_progress WHERE job = 'orders_total'").fetchone() upper = last_id + BATCH if last_id >= db.execute("SELECT MAX(id) FROM orders").fetchone()[0]: print("backfill complete") return with db: # one short transaction per batch cur = db.execute(""" UPDATE orders SET total_cents = COALESCE(( SELECT SUM(quantity * unit_price_cents) FROM order_items WHERE order_id = orders.id), 0) WHERE id > ? AND id <= ? AND total_cents IS NULL """, (last_id, upper)) db.execute("UPDATE backfill_progress SET last_id = ? WHERE job = 'orders_total'", (upper,)) print(f"ids {last_id + 1}-{upper}: updated {cur.rowcount}") batches += 1 if batches == crash_after: print("worker killed by a deploy") return # time.sleep(0.1) in production, to let replicas and VACUUM keep up run_backfill(crash_after=2)run_backfill() # the restart resumes from the checkpointshow(db, "SELECT id, status, total_cents FROM orders ORDER BY id")
Output
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 NULL makes 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.
Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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, missing NOT 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?
Quick check
On Postgres 18, which of these takes a long, table-blocking rewrite on a 300 million row table?
Need a nudge? A hint rules out a wrong answer.
Quick check
A migration runs CREATE UNIQUE INDEX CONCURRENTLY and fails halfway because of a duplicate email. What state is the database in?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put the steps for renaming a column with zero downtime in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each risky change to its safe recipe.

Choose an item, then its match on the other side.
Key terms
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.