Introduction
A product manager asks for a small change: rename a column, split a field into two, and make an optional value required. The developer writes a migration, it passes in staging, and in production it locks a 40-million-row table for six minutes while every API request that touches it queues up. Support tickets arrive before the migration finishes.
The migration was not wrong. It was written as if the application and the database change at the same instant, which never happens in a system with rolling deploys, background workers, and multiple app versions running at once.
In this article you will learn the expand-contract pattern, which ensures Postgres operations are safe online, how to backfill large tables without hurting production, and how to sequence deploys so old and new code can run side by side.
Why Migrations Cause Downtime
Most migration outages come from locks, not from the work itself. Many ALTER TABLE forms take an ACCESS EXCLUSIVE lock, which blocks reads and writes. Even a fast operation can cause an outage if it waits behind a long-running query: while it waits for its lock, every new query on that table queues behind it.
The second source is code and schema drifting apart. During a rolling deploy, some app servers run the old version and some run the new one. If the migration removes or renames something the old code still uses, those servers start failing until the deploy completes.
The Expand-Contract Pattern
Expand-contract splits a breaking change into steps that are each backward compatible. Take renaming customers. phone to customers. phone_e164 as an example:
Expand: add the new column, nullable, with no default that requires a rewrite.
Dual write: deploy code that writes to both columns and still reads the old one.
Backfill: copy existing data into the new column in small batches.
Switch reads: deploy code that reads the new column, still writing both.
Contract: stop writing the old column, then drop it in a later release.
Each step can be deployed and rolled back on its own. At no point does running code depend on a schema that does not exist yet or has already been removed.
Postgres Operations That Are Safe Online
Some operations are cheap in modern Postgres. Adding a nullable column is a catalog change. Since Postgres 11, adding a column with a constant default is also a catalog change rather than a table rewrite. Others need a different technique:
`-- never wait long for a lock
SET lock_timeout = '3s';
-- build indexes without blocking writes
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);
-- Add NOT NULL without a long scan under an exclusive lock
ALTER TABLE customers ADD CONSTRAINT phone_e164_nn
CHECK (phone_e164 IS NOT NULL) NOT VALID;
ALTER TABLE customers VALIDATE CONSTRAINT phone_e164_nn;
ALTER TABLE customers ALTER COLUMN phone_e164 SET NOT NULL; -- uses the valid check (PG12+)
-- Foreign keys follow the same NOT VALID then VALIDATE pattern.
ALTER TABLE orders ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;`
A short lock_timeout is the most important line. If the migration cannot get its lock in three seconds, it fails, and you retry later, instead of silently blocking the whole application. Note that CREATE INDEX CONCURRENTLY cannot run inside a transaction block, so your migration tool must support running it on its own.
Backfilling Large Tables
A single UPDATE over millions of rows holds locks on every row it touches, generates a burst of WAL that can lag replicas, and is hard to stop safely. Backfill in batches keyed by primary key, commit each batch, and pause between them.
UPDATE customers
SET phone_e164 = normalize_phone(phone)
WHERE id > $last_id AND id <= $last_id + 5000
AND phone_e164 IS NULL;
Run the backfill as a resumable background job that records its progress. Watch replication lag and database CPU while it runs, and make the batch size configurable so you can slow it down during peak hours.
Practical Examples: Real-World Use Cases
A B2B ordering platform needed to split a single address text field into structured fields for a logistics integration. Using expand-contract over three releases, the team added the new columns, dual-wrote from the API, backfilled 12 million rows overnight in batches of 5,000, and switched reads with a feature flag. Customers saw no interruption.
A SaaS billing product had to make invoices. Currency is required. Adding NOT NULL directly would have scanned the table under an exclusive lock. Instead, the team added a NOT VALID check constraint, validated it during normal traffic, and then set NOT NULL instantly.
A multi-tenant CRM moved from integer to UUID primary keys for one table by adding a UUID column, doing dual writing, backfilling, and switching foreign keys table by table across several weeks.
Common Mistakes to Avoid
Running migrations without lock_timeout. One long analytics query can turn a millisecond change into an outage.
Dropping or renaming a column in the same release that stops using it. Old app servers will still query it during the rollout.
Backfilling in one statement. Batch it, commit often and make it resumable.
Creating indexes without CONCURRENTLY on busy tables. A normal CREATE INDEX blocks writes for its full duration.
Testing migrations only on small staging data. Lock and rewrite behavior only shows up at production size.
Best Practices: Actionable Tips
Add a migration linter to CI that flags dangerous operations such as non-concurrent index creation or volatile defaults.
Keep schema migrations and data backfills as separate steps with separate deploys.
Make every application release compatible with both the current and the next schema.
Restore a recent production snapshot to a staging database and time risky migrations against it.
Schedule the contract step a release or two later, after confirming nothing reads the old column.
Conclusion
Zero-downtime migrations come from sequencing, not luck. Expand the schema in backward-compatible steps, use online techniques such as CONCURRENTLY and NOT VALID constraints, backfill in small resumable batches, and contract only after all code has moved on. The takeaway: never let a single deploy require the database and the application to change at the same moment.
Ship Schema Changes Safely With Parallaxis
Parallaxis builds and maintains B2B SaaS platforms on Postgres, including migration pipelines, CI checks, and release processes that keep customers online through schema changes. If maintenance windows are slowing your releases, visit Parallelaxis.in to explore our cloud and development services or talk to our team about your database.
Top comments (0)