Run zero-downtime PostgreSQL migrations by adding compatible schema first, moving application behavior and data gradually, then removing obsolete structures. This expand-migrate-contract approach keeps your SaaS available while old and new application versions overlap.
However, PostgreSQL still takes locks, and heavy backfills can slow customer requests. Availability depends on controlling those risks, not simply choosing an “online” command. Start with a deployment sequence that preserves compatibility and gives you a safe stopping point.
Key takeaways
- Separate schema expansion, application rollout, data backfill, and destructive cleanup into independently controlled steps.
- Keep lock waits short, process data in bounded transactions, and monitor customer-facing latency alongside database load.
- Preserve the old representation until validation and the rollback window finish, because reverting code doesn’t repair changed data.
Plan an expand-migrate-contract deployment
Consider replacing accounts.plan with accounts.plan_code while preserving its values and meaning. A direct rename would break application instances still querying plan.
Instead, use this release sequence:
- Expand storage. Add nullable
plan_codewithout removing or changingplan. - Deploy compatibility code. Continue reading
plan, but write both columns in the same database transaction. - Drain old writers. Replace older web instances, queue workers, scheduled jobs, and scripts that update only
plan. - Migrate existing data. Backfill
plan_code, then reconcile it againstplan. - Switch reads gradually. Enable reads from
plan_codefor a small tenant cohort before broader rollout. Keep writing both columns. - Contract later. After the rollback window closes, remove old readers and writers, then drop the obsolete column in a separate migration.

Give each phase its own release gate. A completed deployment doesn’t prove that every long-running worker has stopped using the previous schema.
Also, run migrations through one controlled deployment job. Starting competing schema changes from every application replica creates avoidable contention.
Keep old and new application versions compatible
Prefer additive changes during expansion
Adding a nullable column or a separate table usually preserves existing queries. In contrast, dropping columns, renaming fields, narrowing types, or making nullable data mandatory can break older code.
PostgreSQL’s ALTER TABLE documentation describes the locks and validation behavior behind these changes. Adding a nullable column without a default avoids a table rewrite, but still requires a brief strong lock.
Avoid combining unrelated alterations in one statement. PostgreSQL takes the strictest lock required by any included subcommand.
Preserve meaning as well as structure
Compatibility also includes business behavior. Changing a stored price from cents to dollars breaks consumers even if the column remains numeric.
For the plan migration, keep plan authoritative during overlapping deployments. After old-only writers disappear, reconcile every mismatch, including non-null destination values. An older process could have changed plan after newer code populated plan_code.
Test mixed application versions against the expanded schema. Include background jobs and supported API responses, not only browser requests.
Bound lock waits before changing the schema
Set separate limits for waiting and execution
lock_timeout limits each wait to acquire a lock. Meanwhile, statement_timeout limits the statement’s overall duration.
For a short column addition, an example transaction is:
BEGIN;
SET LOCAL lock_timeout = '1s';
SET LOCAL statement_timeout = '5s';
ALTER TABLE accounts ADD COLUMN plan_code text;
COMMIT;
These values illustrate a short-DDL policy, not universal settings. Long-running index builds and constraint validation need different execution budgets.
SET LOCAL confines the settings to the transaction. If the alteration times out, roll back before retrying.
Prevent a waiting migration from blocking traffic
A long transaction can prevent DDL from acquiring its required lock. The waiting DDL can then cause later queries to queue behind it.
Citus explains this behavior in its PostgreSQL lock guidance. A short lock timeout reduces this risk by canceling the migration’s attempt rather than letting it wait indefinitely.
Inspect long transactions beforehand. Retry failed DDL with bounded backoff, and avoid an endless retry loop.
A fast metadata change can still disrupt traffic if it spends too long waiting for its lock.
Backfill data in controlled batches
Use an indexed cursor and short transactions
A single large update holds row locks until commit and generates substantial write-ahead log (WAL) traffic. Instead, process bounded batches using the primary key.
After old-only writers have drained, this parameterized batch repairs mismatches:
WITH batch AS (
SELECT id
FROM accounts
WHERE id > $1
AND plan_code IS DISTINCT FROM plan
ORDER BY id
LIMIT $2
FOR UPDATE
)
UPDATE accounts AS a
SET plan_code = a.plan
FROM batch AS b
WHERE a.id = b.id
RETURNING a.id;
$1 is the last committed ID; $2 controls batch size. IS DISTINCT FROM compares values safely when either side is null.
Commit each batch, then persist its highest returned ID. If a batch fails, retry without advancing the checkpoint. Persisting progress before commit can skip unprocessed records.

Reconcile progress without overwhelming production
Tune batch size and pauses against observed transaction duration, customer latency, and replica lag. Because the update assigns the authoritative value, repeating a batch is safe while compatible writers maintain both fields.
After traversal, count remaining mismatches and nulls where nulls are forbidden. Compare sampled records and tenant-level distributions, too. Aggregate totals alone can hide records assigned to the wrong customer.
These checks also consume resources, so schedule expensive reconciliation deliberately. For tenant-scoped workers, retain tenant authorization and RLS context rather than weakening isolation to simplify the job.
Build indexes and validate constraints separately
Create indexes while writes continue
When query patterns justify it, create the new index with:
CREATE INDEX CONCURRENTLY accounts_plan_code_idx
ON accounts (plan_code);
PostgreSQL’s concurrent index documentation explains that this permits ordinary inserts, updates, and deletes during construction. However, it performs two table scans, waits for relevant transactions, and consumes CPU and I/O.
Run it outside a transaction block. Migration frameworks that automatically wrap files in transactions need a separate nontransactional migration for this command.
A failed build can leave an invalid index that adds write overhead without helping queries. Include detection and cleanup in the failure procedure before retrying.
Separate constraint installation from validation
For supported constraints, use NOT VALID to avoid scanning historical rows during installation:
ALTER TABLE accounts
ADD CONSTRAINT accounts_plan_code_present
CHECK (plan_code IS NOT NULL) NOT VALID;
This still enforces the rule on subsequent inserts and updates. Therefore, install it only after writers supply the field and the backfill has removed incompatible rows.
Then validate separately:
ALTER TABLE accounts
VALIDATE CONSTRAINT accounts_plan_code_present;
Validation scans existing data with a lock that permits ordinary concurrent updates. However, initial constraint installation still requires a stronger lock.
If you later set the column NOT NULL, PostgreSQL can skip its table scan when a validated check proves non-nullness. The final alteration still needs its schema lock.
Monitor correctness and prepare rollback
Watch database health and business outcomes
Use pg_stat_activity to identify long transactions and waiting sessions. Combine pg_locks with pg_blocking_pids() to trace blocking. For index construction, pg_stat_progress_create_index exposes progress.
Also track connection saturation, storage headroom, WAL generation, replica lag, and application latency. Updates create dead tuples, so watch autovacuum activity during sustained backfills.
Correctness needs separate signals. Compare old and new field values, authorization failures, and account entitlements. A plan migration can grant incorrect access while HTTP error rates remain unchanged. Log affected record IDs without exposing unnecessary customer data.
Define the stopping point before launch
Name the person authorized to pause the worker or disable new reads. Define triggers for excessive latency, lock queues, replication lag, and incorrect writes before deployment.
Rehearse recovery in staging, including interrupted batches and mixed-version application traffic. Retain migration checkpoints and enough protected audit information to trace changed records.
Before contraction, roll back to the compatibility release that reads the old field while maintaining both writes. An older, single-write release can reintroduce drift.
If the migration corrupted data, application rollback alone won’t fix it. Recovery needs targeted repairs or a tested restore procedure, followed by reconciliation.
Frequently asked questions
Can PostgreSQL guarantee zero disruption?
No. Even metadata-only changes acquire locks, and concurrent operations compete for resources. Zero-downtime PostgreSQL migrations reduce disruption through compatible releases, bounded waits, and controlled workload. They don’t eliminate database contention.
A representative staging rehearsal helps expose expensive operations, but production monitoring remains necessary.
Can the entire migration run in one transaction?
A large transaction keeps locks and row versions alive until completion. It also prevents using CREATE INDEX CONCURRENTLY, which cannot run inside a transaction block.
Use short transactions for schema steps and individual backfill batches. Coordinate the overall process through release gates and durable checkpoints.
Remove old schema only when recovery is ready
Reliable zero-downtime PostgreSQL migrations preserve compatibility until both application behavior and stored data have passed validation. Keeping the old column temporarily provides a practical recovery path.
Before destructive cleanup, establish that no supported application, worker, report, or integration still depends on it. Then remove it as a separate, timeout-protected change.
The safest migration has small steps, visible progress, and a tested response when one step fails.