database-migrations
Database Migration Patterns
Safe, reversible database schema changes for production systems.
When to Activate
- Creating or altering database tables
- Adding/removing columns or indexes
- Running data migrations (backfill, transform)
- Planning zero-downtime schema changes
- Setting up migration tooling for a new project
Core Principles
- Every change is a migration — never alter production databases manually
- Migrations are forward-only in production — rollbacks use new forward migrations
- Schema and data migrations are separate — never mix DDL and DML in one migration
- Test migrations against production-sized data — a migration that works on 100 rows may lock on 10M
- Migrations are immutable once deployed — never edit a migration that has run in production
Migration Safety Checklist
Before applying any migration:
- [ ] Migration has both UP and DOWN (or is explicitly marked irreversible)
- [ ] No full table locks on large tables (use concurrent operations)
- [ ] New columns have defaults or are nullable (never add NOT NULL without default)
- [ ] Indexes created concurrently (not inline with CREATE TABLE for existing tables)
- [ ] Data backfill is a separate migration from schema change
- [ ] Tested against a copy of production data
- [ ] Rollback plan documented
PostgreSQL Patterns
Adding a Column Safely
-- Nullable column: no table rewrite, but takes ACCESS EXCLUSIVE lock
ALTER TABLE users ADD COLUMN avatar_url TEXT;
-- PostgreSQL 11+: a non-volatile default avoids a table rewrite
-- Still takes ACCESS EXCLUSIVE lock and may wait for other transactions
ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;
-- BAD on a populated table: existing rows would have NULL in the new column
ALTER TABLE users ADD COLUMN role TEXT NOT NULL;
-- Fails with not_null_violation (SQLSTATE 23502); does not backfill existing rowsAvoiding a table rewrite does not mean avoiding locks. These ADD COLUMN
operations take an ACCESS EXCLUSIVE lock, held until the transaction ends.
Keep the transaction short and use an appropriate lock_timeout to bound lock
acquisition waits. A volatile default such as clock_timestamp() requires a
table rewrite; the PostgreSQL 11+ fast path applies to non-volatile defaults.
Adding a NOT NULL column without a default can succeed on an empty table.
Run the self-checking reproduction SQL on
PostgreSQL 11+:
psql -X -v ON_ERROR_STOP=1 -f examples/postgres-add-column.sqlIt uses a temporary table, rolls back the ALTERs, and drops the fixture, checking
lock acquisition, rewrites, and the expected constraint violation.
Reference: PostgreSQL ALTER TABLE.
Adding an Index Without Downtime
-- BAD: Blocks writes on large tables
CREATE INDEX idx_users_email ON users (email);
-- GOOD: Non-blocking, allows concurrent writes
CREATE INDEX CONCURRENTLY idx_users_email ON users (email);
-- Note: CONCURRENTLY cannot run inside a transaction block
-- Most migration tools need special handling for thisRenaming a Column (Zero-Downtime)
For a pure rename (both columns represent the same value), use expand-contract.
Keep username authoritative until the read cutover:
-- Step 1: Expand (migration 001)
ALTER TABLE users ADD COLUMN display_name TEXT;
-- Step 2: Deploy app v2: read username, write BOTH columns atomically.
-- Cover every INSERT/UPDATE path, including jobs, imports, and admin tools.
-- Drain old-only writers and their in-flight transactions before backfilling.
-- Step 3: Backfill in bounded primary-key ranges (separate data migration).
-- Example range; advance bounds to cover every existing id.
BEGIN;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SET LOCAL lock_timeout = '2s';
UPDATE users SET display_name = username
WHERE id > 0 AND id <= 10000
AND display_name IS DISTINCT FROM username;
COMMIT;
-- Step 4: Validate AFTER all ranges complete, while dual writes continue.
-- Require zero mismatches before switching reads.
SELECT count(*) AS mismatched_rows FROM users
WHERE display_name IS DISTINCT FROM username;
-- Step 5: Deploy app v3: read display_name, still write BOTH columns.
-- Keep dual writes throughout the rollback window.
-- Step 6: After the rollback window, stop backfill/reconciliation workers.
-- Transfer required constraints/indexes/dependencies to the new column.
-- Make old-column constraints compatible with new-only INSERTs/UPDATEs.
-- Drain non-app readers of username and their in-flight transactions first.
-- Then deploy app v4 using ONLY display_name; drain remaining old-column users.
-- Step 7: Contract in a separate migration after checking dependencies.
ALTER TABLE users DROP COLUMN username;Commit each range independently; checkpoint only after commit and retry failed
batch transactions. Choose bounds for the actual key space (including zero or
negative IDs if present). IS DISTINCT FROM repairs stale non-NULL values and
handles NULL pairs without repeatedly updating them. Do not fetch username
into application memory and later write that stale snapshot: copy the target
row's current value in the same UPDATE. At Read Committed, concurrent updates
serialize on the row and PostgreSQL rechecks the predicate after waiting.
Deploying dual writes does not repair earlier drift by itself. Finish draining
old-only writers before backfill, and validate parity before read cutover. Once
new-only writes start, the old column may be stale: do not restart this backfill
or roll b
