How do you run schema migrations on a large PostgreSQL table without downtime?
Some DDL takes an ACCESS EXCLUSIVE lock. Even a fast change can cause an outage if it waits behind a long query, because every new query then queues behind the waiting DDL.
Safe patterns
- Always set
lock_timeout(for example 3 s) for migrations and retry, so a blocked DDL fails fast instead of stalling traffic. - Add a column with a constant default: instant since PostgreSQL 11 (no rewrite). Avoid volatile defaults on big tables.
- Indexes:
CREATE INDEX CONCURRENTLY(andDROP INDEX CONCURRENTLY). - NOT NULL / foreign keys / checks: add the constraint
NOT VALID(quick), thenVALIDATE CONSTRAINTseparately (does not block writes). For NOT NULL, validate aCHECK (col IS NOT NULL)first, thenSET NOT NULLuses it. - Changing a column type or renaming: use expand and contract: add the new column, dual-write from the application, backfill in batches, switch reads, then drop the old column in a later release.
- Backfills: update in batches of a few thousand rows with pauses, not one huge
UPDATE(which bloats the table and holds locks).
Flyway and Liquibase run these steps; mark concurrent operations as non-transactional.
Example
sql
SET lock_timeout = '3s';
-- 1. Expand: new column, nullable, no rewrite
ALTER TABLE orders ADD COLUMN total_cents BIGINT;
-- 2. Backfill in batches (repeat until 0 rows)
UPDATE orders SET total_cents = (amount * 100)::BIGINT
WHERE id IN (SELECT id FROM orders WHERE total_cents IS NULL LIMIT 5000);
-- 3. Constraint without a long lock
ALTER TABLE orders ADD CONSTRAINT total_cents_not_null CHECK (total_cents IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT total_cents_not_null;
ALTER TABLE orders ALTER COLUMN total_cents SET NOT NULL; -- uses the validated check
-- 4. Index online
CREATE INDEX CONCURRENTLY idx_orders_total ON orders (total_cents);
-- 5. Contract (a later release, after the app stops using amount)
-- ALTER TABLE orders DROP COLUMN amount;Follow-up questions interviewers ask
Try answering each one before you open it.
How does the application stay compatible during expand and contract?
Each release must work with both the old and the new schema: release 1 writes both columns and still reads the old one, release 2 reads the new one, release 3 stops writing the old one, and only then is it dropped. This allows rolling deployments and rollbacks without errors.