Skip to content

Changing a PostgreSQL schema without taking the application down

Expand, migrate, contract: how to add columns, indexes and constraints to a live table without long locks or a maintenance window.

Published
Reading time
3 minutes
Written by
Cyber Vision engineering

Most schema changes are safe in development because the tables are tiny and nobody else is connected. In production the same statement can queue behind a long transaction, take an exclusive lock and stall every request that touches the table. The fix is not a better migration tool. It is splitting one risky change into several boring ones.

Why a simple ALTER can stop traffic#

Every ALTER TABLE takes a lock. Many forms take ACCESS EXCLUSIVE, which blocks reads as well as writes. The statement itself may finish in milliseconds, but it has to acquire the lock first. If a slow report holds a conflicting lock, your migration waits, and every new query on that table waits behind your migration.

Two settings turn that silent pile-up into a fast, retryable failure:

Before any migration on a busy table
SET lock_timeout = '3s';       -- give up instead of queueing traffic
SET statement_timeout = '15min';

Expand, migrate, contract#

The application and the schema are deployed separately, so for a while both the old and the new code run against the same database. Every step must be compatible with both.

  1. 01Expandadd new structure
  2. 02Deploywrite to both
  3. 03Migratebackfill
  4. 04Deployread new
  5. 05Contractremove old
Each phase ships on its own. The application is deployed between phases, never in the middle of one.
PhaseSchema changeApplication changeSafe to roll back?
ExpandAdd nullable column, new table or indexNone yetYes, drop the new structure
Dual writeNoneWrite old and newYes, old path still complete
BackfillBatched updatesNoneYes
Switch readsNoneRead from newYes, old data still current
ContractDrop old column, add constraintsStop writing oldNo, plan this one

Adding a required column#

Adding a column with a constant default is cheap on PostgreSQL 11 and later: the default is stored in the catalogue, not written to every row. The expensive part is making it NOT NULL for existing rows, so do that last.

1. Expand
ALTER TABLE orders ADD COLUMN fulfilment_status text;

Backfill in small batches so each transaction is short and replication can keep up:

2. Backfill, repeated until it updates 0 rows
UPDATE orders
SET fulfilment_status = 'unfulfilled'
WHERE id IN (
  SELECT id FROM orders
  WHERE fulfilment_status IS NULL
  LIMIT 5000
);

SET NOT NULL normally scans the whole table under an exclusive lock. Since PostgreSQL 12 it can skip that scan if a validated CHECK constraint already proves there are no nulls, and validating a constraint only needs a weaker lock:

3. Contract
ALTER TABLE orders
  ADD CONSTRAINT orders_fulfilment_status_not_null
  CHECK (fulfilment_status IS NOT NULL) NOT VALID;      -- instant
 
ALTER TABLE orders
  VALIDATE CONSTRAINT orders_fulfilment_status_not_null; -- scans, allows writes
 
ALTER TABLE orders ALTER COLUMN fulfilment_status SET NOT NULL; -- no scan
ALTER TABLE orders DROP CONSTRAINT orders_fulfilment_status_not_null;

Indexes and foreign keys#

A plain CREATE INDEX blocks writes for as long as it takes to build. Use CONCURRENTLY, which cannot run inside a transaction block, so keep it in its own migration:

CREATE INDEX CONCURRENTLY orders_status_created_idx
  ON orders (fulfilment_status, created_at);

If a concurrent build fails it leaves an INVALID index behind. Drop it with DROP INDEX CONCURRENTLY and run the build again.

Foreign keys follow the same pattern as the check constraint: add with NOT VALID, then VALIDATE CONSTRAINT separately.

Renames are two migrations, not one#

Renaming a column breaks every running instance that still uses the old name. Treat it as add, dual-write, backfill, switch, drop. It is slower, and it never pages anyone.

A short checklist#

  • Set lock_timeout on every migration that touches a hot table.
  • One risky statement per migration, so a failure is easy to retry.
  • Never combine a schema change and the code that depends on it in one deploy.
  • Run the contract phase only after the new code has been live long enough to be trusted.
  1. AI Engineering · 3 min read

    Why operational AI needs an approval boundary

    Separate analysing information from taking consequential actions, bind every approval to a specific change, and make each decision traceable.

  2. Software Architecture · 3 min read

    Idempotency keys in PostgreSQL: a pattern that survives retries

    Clients retry, webhooks repeat and networks time out. A small table and one unique constraint make a write safe to repeat.

  3. Commerce Engineering · 3 min read

    A storefront is only the beginning of commerce operations

    Orders become operational work. Design the connection to inventory and fulfilment around that reality, not around the checkout.