---
name: safe-db-migration
description: Plan, write, test, and roll out a database schema or data migration without downtime or data loss, using expand-and-contract, batched backfills, lock-aware DDL, and a written rollback. Use when the user wants to add, rename, or drop a column or table, change a type or constraint, add an index on a large table, backfill data, or asks "is this migration safe?". Postgres-first, with notes that carry over to MySQL and SQLite. Always tests on a copy or branch database before production, and never runs production migrations without explicit approval. Not for designing a data model from scratch (use tech-spec).
license: MIT
metadata:
  title: Safe DB Migration
  summary: Ship schema and data changes with expand-and-contract, batched backfills, lock-aware DDL, a tested rollback, and a dry run on a copy first.
  category: engineering
  tags: [database, postgres, migrations, sql, zero-downtime]
  version: "1.0.0"
  author: Austin Christensen
  publisher: Christensen Equity
  related: [tech-spec, pr-description, incident-postmortem, launch-checklist]
---

# Safe DB Migration

Most migration outages come from three things: a lock that blocks traffic, app code and schema disagreeing during deploy, and a destructive step with no way back. This skill plans around all three.

## When to use

- Any change to tables, columns, types, constraints, or indexes on a database with real data.
- Backfills or data fixes that touch many rows.
- Reviewing a migration someone else wrote.

## Inputs

- The desired end state and why.
- The database engine and version, table sizes (`SELECT pg_size_pretty(pg_total_relation_size('orders'));`, row counts), and write traffic.
- The migration tool in use (Prisma, Drizzle, Rails, Django, Alembic, Flyway, plain SQL, Supabase CLI) and how deploys run.

## Workflow

1. **Classify the change.**
   - Additive and safe: new table, nullable column, column with a constant default (Postgres 11+).
   - Needs care: indexes on large tables, `NOT NULL`, foreign keys, type changes, renames.
   - Destructive: dropping columns or tables, narrowing types, deleting rows.
2. **Use expand and contract for anything not purely additive.** Never rename or drop in one step while old code is running.
   1. Expand: add the new column or table. Old code ignores it.
   2. Dual-write: deploy code that writes both old and new.
   3. Backfill existing rows in batches.
   4. Switch reads to the new shape; verify.
   5. Contract: stop writing the old shape, then drop it in a later release.
3. **Avoid long locks** (Postgres):
   ```sql
   SET lock_timeout = '5s';                       -- fail fast instead of queueing traffic
   CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);  -- outside a transaction
   ALTER TABLE orders ADD CONSTRAINT orders_customer_fk
     FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID;
   ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;  -- separate step, lighter lock
   ```
   For `NOT NULL` on a big table, add `CHECK (col IS NOT NULL) NOT VALID`, validate it, then set `NOT NULL`. Type changes that rewrite the table become add-column, backfill, swap.
4. **Batch backfills.** Update in chunks of a few thousand rows by primary key, commit each batch, pause briefly, and make it resumable and idempotent:
   ```sql
   UPDATE orders SET total_cents = round(total * 100)
   WHERE id > :last_id AND id <= :last_id + 5000 AND total_cents IS NULL;
   ```
5. **Write the rollback before running anything.** For each step: the down migration, or why none is needed. For destructive steps, take a backup or snapshot (or copy the affected rows to an archive table) and confirm it restores.
6. **Test on a copy.** Run the full sequence on a branch database, a staging restore, or a local copy with production-like volume. Time it. Run the app's tests against the migrated schema. Run the rollback too.
7. **Plan the rollout.** Order of migrations and deploys, who runs them, the expected duration, what to watch (errors, lock waits, replication lag), and the abort trigger.
8. **Run with approval and watch.** After each step, check row counts, constraint validity, error rates, and slow queries before the next.

## Output

A migration plan, saved next to the migration or in the PR body:

```markdown
## Migration: rename orders.total to total_cents (integer cents)
Class: needs care (type change on a 4M-row table)
Steps: 1) add total_cents nullable  2) dual-write deploy  3) batched backfill (~6 min on staging copy)
       4) read from total_cents  5) next release: drop total
Locks: add-column is metadata-only; no table rewrite
Rollback: steps 1-4 are reversible by deploying the previous release; step 5 only after a backup
Tested: staging restore 2026-03-03, app tests green, rollback exercised
Watch: error rate, lock waits, p95 on /orders
```

## Guardrails

- Never run migrations against production without the user's explicit go-ahead for that specific run.
- Never drop or narrow in the same release that stops using the data.
- Never backfill millions of rows in one transaction.
- Back up before anything destructive, and confirm the backup restores.
- Keep migrations in version control; don't hand-edit production schema outside them.
- Don't put credentials or connection strings in migration files or PR bodies.

## Handoff

Put the plan in the PR with `pr-description`. If a migration caused user-facing trouble, run `incident-postmortem`.
