---
title: 'Zero-Downtime PostgreSQL Migrations on High-Write Tables'
description: 'Why ALTER TABLE locks production traffic, and how the expand-and-contract pattern eliminates maintenance windows.'
pubDate: 2026-10-21
tags: ['Databases', 'PostgreSQL', 'Migrations']
canonical: 'https://callmeenji.com/blog/zero-downtime-postgres-migrations-at-scale'
---

Even a seemingly harmless schema change in PostgreSQL can stall every incoming query if it waits behind a long-running analytics read for an ACCESS EXCLUSIVE lock.

## 1. Always set lock_timeout and statement_timeout

Wrap every migration in a short lock timeout (for example, 2 seconds) and retry with backoff rather than queueing up production web requests behind your DDL statement.

```sql title="migration.sql"
SET lock_timeout = '2s';
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_events_org_created
  ON telemetry_events (org_id, created_at DESC);
```

## 2. Expand, backfill, and contract

Never rename or change a column type in place on a busy table. Instead, add the new nullable column first, dual-write from your application layer, backfill historical rows in bounded primary-key batches, and drop the old column in a later deploy.

- Prefer NOT VALID check constraints followed by VALIDATE CONSTRAINT.
- Backfill large columns in batched primary-key ranges rather than one massive UPDATE.
- Keep old and new columns compatible across at least one application deploy cycle.

## 3. Automate safety checks in CI

Catching locking DDL statements during code review scales poorly once a team grows past ten engineers. Running static SQL migration lint rules in pull requests turns institutional Postgres knowledge into instant feedback.
