A migration that works perfectly on a laptop with 200 rows can lock a production table with 400 million rows for twenty minutes. During that time every request touching the table queues, connection pools fill up, and the application appears to be down even though nothing crashed. Most outages caused by schema changes share this shape: a harmless-looking statement that takes a heavy lock, or a code deployment that assumed the schema had already changed (or had not yet).
Zero-downtime migrations are less about clever tools and more about discipline: small steps, each backward compatible, deployed in a safe order. This article covers the core pattern, the practical mechanics on PostgreSQL and MySQL, and how to apply them with Prisma and Flyway.
Why deployments and schema changes collide
During a rolling deployment, old and new versions of your application run simultaneously against the same database. The same is true for background workers and scheduled jobs that deploy on a different cadence. Whatever schema you migrate to must therefore be compatible with both the version currently running and the version being released.
That gives us the central rule: every migration must be compatible with the previous application version, and every application version must be compatible with the previous schema. If you honor both halves, you can deploy in any order, roll back code safely, and stop treating releases as events requiring a maintenance window.
The expand/contract pattern
Also called parallel change, expand/contract splits a breaking change into several non-breaking ones. Suppose you want to rename users.full_name to users.display_name. A direct ALTER TABLE ... RENAME COLUMN breaks every running instance that still reads full_name. Instead:
- Expand. Add the new column
display_nameas nullable, with no default that would rewrite the table. Deploy this migration alone. - Dual write. Release application code that writes to both columns and still reads from the old one.
- Backfill. Copy existing data from
full_nametodisplay_namein batches. - Switch reads. Release code that reads from
display_nameand still writes to both. - Stop writing the old column. Release code that no longer references
full_name. - Contract. Drop
full_namein a later migration, after a safe waiting period during which you could still roll back.
It looks like six steps for a rename, and it is. The price is paid in calendar time and pull requests, not in downtime or risk. For small tables or internal tools with a maintenance window, you can skip it. For anything with real traffic, the pattern converts a scary event into routine work.
The same approach handles changing a column type (add new column, backfill, swap), splitting a table, moving data to a new service, and changing constraints.

Know your locks
Safe DDL requires knowing which statements take which locks on your database. On PostgreSQL:
| Operation | Behavior | Safe approach |
|---|---|---|
ADD COLUMN nullable, no default |
Metadata only, fast | Safe |
ADD COLUMN ... DEFAULT x |
Fast since PostgreSQL 11 for constant defaults | Safe on modern versions; volatile defaults still rewrite |
ALTER COLUMN TYPE |
Often rewrites the table under an exclusive lock | Use expand/contract |
CREATE INDEX |
Blocks writes for the duration | CREATE INDEX CONCURRENTLY |
ADD CONSTRAINT ... FOREIGN KEY |
Validates under heavy lock | Add NOT VALID, then VALIDATE CONSTRAINT |
ADD CONSTRAINT ... CHECK |
Scans the table | Add NOT VALID, then validate |
SET NOT NULL |
Full scan under lock | Add CHECK (col IS NOT NULL) NOT VALID, validate, then set NOT NULL |
DROP COLUMN |
Fast, but breaks readers | Only after code stops using it |
RENAME |
Fast, but breaks readers | Avoid; use expand/contract |
Two details trip up even experienced teams. First, a statement that needs an ACCESS EXCLUSIVE lock must wait for every running transaction on that table to finish, and while it waits, it blocks all new queries behind it. A fast DDL statement stuck behind one long-running report query can therefore stall the whole table. Defend yourself by setting a short lock_timeout in migrations:
SET lock_timeout = '3s';
SET statement_timeout = '15min';
-- Fails fast instead of queueing the whole app behind it
ALTER TABLE orders ADD COLUMN shipped_at timestamptz;
If it times out, retry with backoff during a calmer moment. Second, CREATE INDEX CONCURRENTLY cannot run inside a transaction block, and if it fails it leaves an invalid index that you must drop. Check pg_index.indisvalid after.
On MySQL, InnoDB supports many online DDL operations (ALGORITHM=INPLACE, LOCK=NONE), but not all; verify per operation and version. For heavy changes on large MySQL tables, teams use external tools such as gh-ost or pt-online-schema-change, which create a shadow table, copy rows incrementally, and swap it in at the end.
Backfills done right
Backfilling is where most migrations hurt production, because a single UPDATE users SET display_name = full_name runs as one huge transaction. It holds row locks for the duration, generates a mountain of write-ahead log, bloats the table, delays replicas, and can be impossible to cancel cleanly.
Do it in small batches, outside the schema migration:
-- Run repeatedly from a script until it affects 0 rows
WITH batch AS (
SELECT id FROM users
WHERE display_name IS NULL
ORDER BY id
LIMIT 5000
FOR UPDATE SKIP LOCKED
)
UPDATE users u
SET display_name = u.full_name
FROM batch
WHERE u.id = batch.id;
Practical guidelines:
- Batch by primary key range or with
SKIP LOCKED, 1,000 to 10,000 rows per batch depending on row width. - Sleep between batches and adapt: monitor replication lag, CPU and lock waits, and slow down or pause when thresholds are exceeded.
- Make it idempotent and resumable. The
WHERE display_name IS NULLcondition lets you stop and restart at will. - Run as a separate job, not inside the deploy pipeline’s migration step, so a backfill taking hours does not block releases.
- Handle writes during backfill. That is why dual writing comes first: new and updated rows are already correct, and the backfill only handles history.
- Verify afterward. Count mismatches (
WHERE display_name IS DISTINCT FROM full_name) before switching reads. - Vacuum and watch bloat. Large updates create dead tuples; autovacuum should keep up, but monitor it.
For huge tables, consider alternatives to updating in place: create a new table, copy data in batches, keep it in sync with triggers or logical replication, and swap names in a quick transaction. This is exactly what the online schema change tools automate.
Large tables: indexes, constraints and partitioning
On tables with hundreds of millions of rows, even “safe” operations need planning.
- Indexes: build concurrently, ideally during low traffic, and make sure disk space and I/O can take it. Drop unused or duplicate indexes after confirming via statistics that they are unused.
- Adding a foreign key on a large table is a two-phase operation:
NOT VALIDfirst (fast, enforces for new rows), thenVALIDATE CONSTRAINT, which takes only a weaker lock and can run while traffic continues. - Adding NOT NULL: use the check-constraint approach in the table above. Since PostgreSQL 12, a validated
CHECK (col IS NOT NULL)letsSET NOT NULLskip the scan. - Changing types:
inttobigintfor exhausted ID columns is a classic emergency. Plan early: add abigintcolumn, dual write, backfill, swap, and update foreign keys, which is a long project when done late. - Partitioning: if a table keeps growing, partitioning by time can make retention (dropping old partitions) instant and keeps maintenance bounded. Introducing it later is itself a migration, so decide before the table becomes enormous.
Prisma, Flyway and friends
The tools generate and apply SQL; they do not make it safe automatically.
Prisma Migrate generates SQL from schema diffs. Always read the generated file before applying. Common hazards: a renamed field is interpreted as drop-and-add, which loses data, and adding an index emits a plain CREATE INDEX that blocks writes. Use prisma migrate dev --create-only to produce the file without applying it, edit the SQL (for example to use CONCURRENTLY, which requires the statement to run outside a transaction, so keep it in its own migration), and then commit. Apply in production with prisma migrate deploy as a separate pipeline step, not on application start, so multiple instances do not race. Treat the shadow database used by migrate dev as development-only.
Flyway runs versioned SQL (V12__add_display_name.sql) in order and records checksums in a history table. It encourages exactly the hand-written, reviewable SQL that safe migrations need. Keep each migration small and single-purpose. For operations that cannot run in a transaction, Flyway supports per-script configuration to disable it. Use repeatable migrations (R__) only for idempotent objects like views. Avoid editing applied migrations; a checksum mismatch will block the next deploy, which is a feature. Also consider that Flyway’s community edition does not support automatic undo scripts, which is fine because forward-only fixes are the more reliable strategy anyway.
Other tools like Liquibase, Alembic, Rails migrations and Atlas follow similar principles. Whatever you choose, adopt these team rules:
- One logical change per migration, small enough to review in minutes.
- Lint migrations in CI. Tools such as Squawk for PostgreSQL flag unsafe operations (non-concurrent indexes,
NOT NULLadditions, type changes) automatically. - Run every migration against a copy of production-sized data in staging at least once, and record how long it took and which locks it held.
- Apply migrations before deploying code that needs them, and keep destructive changes in a separate, later release.
Rollbacks: plan forward, not backward
A “down” migration sounds reassuring but rarely helps in an actual incident. Dropping a column you just added is easy; restoring a column you dropped, with its data, is impossible without a backup. Reverting a type change after new data was written in the new format can lose information.
A more dependable rollback philosophy:
- Roll back code, not schema. Because migrations are backward compatible, redeploying the previous application version works against the new schema. This is the main payoff of expand/contract.
- Delay destructive steps. Only drop old columns and tables after the new path has run cleanly for a period, such as two weeks. Until then, rollback is a code revert.
- Use feature flags to switch reads between old and new columns instantly, without a deploy.
- Roll forward when necessary. For a faulty migration, write a new corrective migration quickly rather than improvising a reverse one.
- Back up before irreversible changes and verify the backup can be restored. Point-in-time recovery gives you a safety net for data mistakes.
- Rehearse. Practice the rollback procedure in staging so nobody is reading the runbook for the first time during an incident.
The safest migration is the one you can abandon halfway through without anyone noticing.
Observability during migrations
Migrations deserve the same monitoring as any risky release. Watch these during execution: lock waits (pg_stat_activity and pg_locks), replication lag, long-running transactions, error rates and p95 latency, connection pool saturation, disk usage and WAL generation. Define abort criteria in advance, such as “if replication lag exceeds 30 seconds or error rate doubles, pause the backfill.” Run large operations when traffic is low and with someone watching; at Datainter we pair the engineer running the change with a second person monitoring dashboards, which sounds heavy until the first time it saves you.
Key takeaways
- Because old and new application versions overlap during deploys, every migration must stay backward compatible with the code currently running.
- Use expand/contract: add, dual-write, backfill, switch reads, stop writing, then drop in a later release.
- Learn the lock behavior of your database; use
lock_timeout, concurrent index creation andNOT VALIDconstraints with later validation. - Backfill in small, idempotent, throttled batches in a separate job, and verify data before switching reads.
- Review generated SQL from Prisma or Flyway, lint migrations in CI and test them on production-sized data.
- Prefer rolling code back over rolling schema back, delay destructive steps, and keep tested backups for the irreversible ones.

