How do you run database migrations without downtime on PostgreSQL?
By the Keel team · Last checked · 5 min read
Short answer
Use the expand and contract pattern. First expand: add new columns or tables in a way that does not break the current code. Then deploy code that works with both structures, and finally contract: remove the old structures in a later release. Every step stays backwards compatible, so you can roll back the code at any point.
What is the expand and contract pattern?
Expand and contract splits one risky schema change into several safe ones, each compatible with the code before it and after it.
You expand the schema, move the code across, then contract by removing what is no longer used.
The point is that the old and new versions of your application run at the same time during any rolling deployment, and may do so again if you roll back. A migration that only the new code understands breaks the old code the moment it runs.
How do you rename a column with no downtime?
You never rename it in one step; you add the new column, move the data and code across in stages, and drop the old column in a later release.
A single rename would break every running task still using the old name.
- Expand: add the new column as nullable, with no default that forces a rewrite.
- Deploy: code writes to both columns and reads from the old one.
- Backfill: copy existing data to the new column in small batches.
- Deploy: code reads from the new column and still writes to both.
- Contract: in a later release, stop writing the old column, then drop it.
Five steps for a rename sounds slow. It is faster than an outage, and each step can ship on a normal day.
Which PostgreSQL operations lock a table?
Many ALTER TABLE forms take an ACCESS EXCLUSIVE lock, which the PostgreSQL documentation says conflicts with locks of every mode and means the holder is the only transaction accessing the table.
The ALTER TABLE page says this lock is acquired unless a subform is explicitly noted otherwise.
| Operation | The risk | Safer approach |
|---|---|---|
| Create an index | A plain CREATE INDEX takes a SHARE lock that blocks writes | CREATE INDEX CONCURRENTLY, which does not block inserts, updates or deletes |
| Add a column with a volatile default | Rewrites the whole table and its indexes | Add it nullable, backfill in batches; a non-volatile default is stored in metadata with no rewrite |
| Change a column type | Normally rewrites the table and indexes and can need up to double the disk space | Add a new column, backfill, switch over |
| Add NOT NULL | Scans the whole table while holding the lock | Add a CHECK (col IS NOT NULL) NOT VALID constraint, validate it, then set NOT NULL; PostgreSQL skips the scan when a valid check exists |
| Add a constraint | Most forms take ACCESS EXCLUSIVE | Add it NOT VALID, then VALIDATE CONSTRAINT, which takes a lighter SHARE UPDATE EXCLUSIVE lock |
How do you add an index without blocking writes?
Use CREATE INDEX CONCURRENTLY, which PostgreSQL documents as building the index without taking locks that prevent concurrent inserts, updates or deletes.
A standard build locks out writes, though not reads, until it finishes.
There are costs. The documentation says a concurrent build takes significantly longer and does more total work, and that it cannot run inside a transaction block, so your migration tool needs a way to run that statement outside one. If it fails part-way, it can leave an invalid index that is ignored by queries but still adds update overhead, and you drop it and try again.
CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);What safety settings should every migration use?
Set lock_timeout in migrations so a statement that cannot get its lock gives up instead of waiting and holding up everything behind it.
PostgreSQL describes it as aborting any statement that waits longer than the set time for a lock, with zero as the default, which disables it.
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN shipped_at timestamptz;The documentation advises against setting lock_timeout in postgresql.conf, because it would affect every session. Set it for the migration's own session, and retry on failure at a quieter moment. A migration that fails fast is a nuisance; one that queues behind a long-running query and blocks the table is an outage.
- Run long backfills as background jobs, not inside the deploy.
- Never combine a destructive change with the code change that depends on it.
- Keep each migration small enough to describe in one sentence.
How do you run migrations in the pipeline?
Run migrations as a separate step before the new code takes traffic, so a failure stops the release while the old version is still serving.
On ECS a common order is to build and push the image, run a one-off task from that image to migrate, and deploy the service only if that task succeeds.
Because each migration is backwards compatible, the old code carries on while the migration runs, and rolling back the code afterwards is safe. Rolling back an ECS deployment when database migrations already ran covers the case where it still goes wrong, and rolling back automatically with GitHub Actions covers the code side.
How do you backfill a large table safely?
Update in small batches, ordered by primary key, committing each batch and pausing between them.
A practical starting point is a few thousand rows at a time, adjusted by watching database load, because the right size depends on your hardware and indexes.
Make the job resumable by recording the last key processed, so it can stop and carry on after a deploy or a spike. Do not backfill in the same transaction as a schema change: the transaction would hold locks for as long as the backfill runs.
Mobile clients add another constraint, because old app versions keep calling the backend for months. See keeping a backend compatible with old mobile app versions.
Is your next migration safe to run?
Tick each item that is true for the migration you are about to ship.
- It works while the previous version of the code is still running.
- It cannot take a long ACCESS EXCLUSIVE lock on a large table.
- It sets a lock timeout and can be retried.
- It has been run against production-sized data, not production data itself.
- Indexes are built concurrently and outside a transaction.
- There is a way back if it goes wrong.
Decision point: Five or six ticks: ship it. Three or fewer: split it into smaller steps first.
Sources
- PostgreSQL docs, CREATE INDEX (checked November 2026)
- PostgreSQL docs, ALTER TABLE (checked November 2026)
- PostgreSQL docs, Explicit Locking (checked November 2026)
- PostgreSQL docs, Client Connection Defaults (lock_timeout) (checked November 2026)
Keep reading
Keel is an AWS release and recovery operations service for SaaS teams of 3 to 15 developers, provided by Bargainn Services Ltd, a UK company registered at Companies House (16497746). Registered office: 3rd Floor, 86-90 Paul Street, London, EC2A 4NE, United Kingdom.