The migration that looked harmless
A team I worked with once shipped a one-line change on a Friday afternoon: add a column to the orders table, give it a default value, deploy, go home. The change had passed code review, the tests were green, and it had run in under a second on every developer's laptop. Forty minutes later the site was down, the on-call engineer was staring at a database with thousands of queries queued behind a single locked statement, and the rollback — reverting the code — did nothing, because the problem was in the database, not the code.
That is the shape of most migration incidents. The reason is not that databases are fragile. It is that a migration changes the thing that is also serving live traffic, holding data you cannot lose, and shared by every version of your code currently running. Code deploys reverse in minutes; a bad schema change can be irreversible in seconds.
This article is about relational databases — the SQL systems that most business applications run on — why their schema changes break production, and what to do instead. Choosing between SQL and NoSQL stores is a separate question with its own trade-offs. It covers the mechanics that actually cause outages — locks, table rewrites, backfills, renames — the expand-and-contract pattern that makes most changes safe, the testing and rollback habits that catch the rest, and the tooling that turns all of this from folklore into a repeatable process.
Why a schema change is not like a code change
Code and schema change under different rules, and most migration trouble starts with treating them as if they were the same. When you deploy code, the old version stops and the new version starts. When you change a schema, there is no clean switch. During a rolling deploy, the old code and the new code run side by side against the same database. In a blue-green deploy, you may need to roll back to old code while the new schema is already in place. The database has to work for both versions at once, and a migration that only works for the new code breaks the old one while it still serves traffic.
The second difference is reversibility. Reverting a code deploy means starting the previous version again. Reverting a schema change means undoing a change to live data, and some changes cannot be undone at all: drop a column and the data in it is gone; change a column's type and the old values may not come back; rename a table and every query, report, and background job using the old name breaks at once. The cost of a mistake is set by the data, not by the size of the change.
The third difference is scale. Your development database has a few thousand rows, or none at all. Production has millions, and the difference is not just speed: an operation that is instant on an empty table can take 45 minutes on a table with 80 million rows, while holding a lock that blocks everything else. Testing a migration on a small database proves the SQL is valid. It proves almost nothing about what it will do in production.
Locks: the mechanism behind most migration outages
Almost every migration outage I have seen comes down to a lock. Databases protect the structure of a table while it changes, and the way they do it is to block other work. In PostgreSQL, most ALTER TABLE statements take an ACCESS EXCLUSIVE lock, the heaviest lock there is. It conflicts with every other lock mode, including the one a plain SELECT takes, which means that while the statement runs, nothing can read from or write to the table at all.
Whether that matters depends on how long the lock is held. Adding a nullable column with no default is a metadata-only change in PostgreSQL: the lock is held for milliseconds, and nobody notices. Adding a column with a volatile default, such as now(), forces the database to rewrite every row in the table to fill in the value, and the lock is held for the whole rewrite. On a large table, that is minutes or hours of total blockage. Changing a column's type usually rewrites the table too, with the same result. Creating an index the ordinary way blocks writes for the entire build.
The lock queue makes this worse than it sounds. A migration that only needs its lock for two milliseconds can still freeze a table for minutes, because it must wait for every open transaction on that table to finish before it can take the lock — and while it waits, every new query queues up behind it. The migration itself was fast. The queue it created was the outage.
Two habits prevent most of this. The first is to set a lock timeout before running DDL in production — SET lock_timeout = '3s' in PostgreSQL — so a blocked statement fails quickly instead of queueing every query behind it. A failed migration is a small problem; a queued one is an outage. The second is to know, before you run it, which lock your statement takes and how long it will hold it. The PostgreSQL documentation lists the lock mode for each form of ALTER TABLE, and guides such as Canner's zero-downtime Postgres reference lay out the table operation by operation: which changes are metadata-only, which rewrite the table, and which safe alternative to use.
PostgreSQL 11 changed one important case: adding a column with a constant default, like DEFAULT 0 or DEFAULT 'pending', became a catalog-only operation instead of a full rewrite, because the default is stored in the table's metadata and filled in when rows are read. On PostgreSQL 10 and earlier, the same statement rewrites the whole table. That is the kind of version detail that turns a safe migration into an outage when a team upgrades its habits slower than its database.
Backfills: the slow killer
Adding a column is usually the easy part. Filling it in for the millions of rows that already exist is where migrations go wrong. A backfill is a data migration disguised as a schema migration, and it behaves like one: a single UPDATE over a whole table takes a long transaction, holds locks, generates a flood of write-ahead log entries, and on a replicated setup, pushes replication lag up while replicas struggle to keep up.
The safe way to backfill is boring, and that is the point. Update rows in small batches — a thousand or a few thousand at a time — with a pause between batches, committing each batch separately. That keeps each transaction short, keeps locks brief, and lets you stop the job at any point. It also lets you watch the database while it runs: if replication lag climbs or write latency rises, slow the batches down or stop entirely.
One more trap: the NOT NULL constraint. Adding a column as nullable, backfilling it, and then adding NOT NULL in a later deploy is safe. Adding the column as NOT NULL with a default in one step forces the database to check or fill every row at once — the rewrite you were trying to avoid.
The expand-and-contract pattern
There is one pattern behind almost every safe production migration, and it has several names: expand and contract, parallel change, expand-contract. The idea is simple. Never make a breaking change in one step. Instead, split it into phases, each deployed separately, each compatible with both the old and the new version of the code.
Phase one is expand. Add the new structure alongside the old one, without removing anything. A new nullable column next to the old one. A new table next to the old table. A new index built with CREATE INDEX CONCURRENTLY, which in PostgreSQL builds without blocking writes. Old code ignores the new structure and keeps working. New code can start using it.
Phase two is migrate. Deploy code that writes to both the old and the new place — a dual-write — and backfill the existing rows into the new structure in batches. Reads still come from the old place, so nothing changes for users. Reconciliation queries check the two copies agree: row counts, checksums, a sample of rows compared side by side.
Phase three is switch. Once the backfill is complete and verified, switch reads to the new structure, usually behind a feature flag so it can be turned off in seconds if something looks wrong. The old structure is still there, still being written to, so rolling back is a matter of flipping the flag.
Phase four is contract. Only now, after the new structure has run in production for days and the old code is gone, do you remove the old column, the old table, or the old constraint. This is the only phase that cannot be rolled back, which is why it comes last and waits the longest.
Renaming a column is the classic example, because the naive version is so tempting. ALTER TABLE users RENAME COLUMN full_name TO display_name is instant, and it breaks every running instance of the old code immediately, because full_name no longer exists. The expand-and-contract version takes four deploys: add display_name with a trigger keeping the two in sync; deploy code that uses display_name; drop the trigger once the old code is gone; then drop full_name. Slower — and the difference between a rename and an outage.
Zero-downtime techniques, by database
The pattern is the same everywhere, but the tools differ by engine, and using the wrong one is its own kind of outage.
In PostgreSQL, the online toolkit is built in. CREATE INDEX CONCURRENTLY builds an index without blocking writes, though it cannot run inside a transaction block. Adding a check constraint with NOT VALID and then running VALIDATE CONSTRAINT separately avoids the full-table scan holding a heavy lock. REINDEX CONCURRENTLY, available since PostgreSQL 12, rebuilds an index the same way. For a table that needs a full rewrite, pg_repack rebuilds it online with no table lock.
In MySQL, the story is the online schema change executor. MySQL 8.0 introduced ALGORITHM=INSTANT for a growing set of operations — adding, dropping, and renaming columns — and ALGORITHM=INPLACE, LOCK=NONE covers most of the rest. Anything outside that set needs an external tool. The two established ones are gh-ost, from GitHub, and pt-online-schema-change, from Percona Toolkit. Both work by building a copy of the table, copying rows across in batches, replaying ongoing writes, and then swapping the tables. How the two compare, and how they pair with versioning tools, is covered in detail in recent tooling comparisons. The difference is in how they replay the writes: pt-online-schema-change uses triggers on the original table, while gh-ost reads the binary log instead, which tends to hold up better under heavy write load. Both need the table to have a primary key.
For either engine, the rule is the same: if a change rewrites a large table or blocks writes, assume it is risky, use the online tooling, and run it behind a canary deploy.
Testing a migration before it touches production
Most teams test migrations on a staging database that is a fraction of production's size, with data generated by a seed script. That catches syntax errors and not much else. The failures that matter — a rewrite that takes an hour, a backfill that doubles replication lag, a constraint that fails on real data — only show up at production scale, with production-shaped data.
The single most useful improvement is a staging database restored from a recent production snapshot, with sensitive data masked. Even a tenth of production, with the same distribution of values, catches most of the surprises. Run the migration against it with timing on, and watch the same things you would watch in production: how long each statement takes, what locks it holds, and how much replication lag it creates.
A migration also deserves a dry run in the deployment pipeline itself. Apply it, run the application's test suite against the migrated schema, roll it back, and apply it again. That loop catches the two most embarrassing failures: a migration that cannot run twice, and a rollback that does not restore the previous state. If the rollback has never been run anywhere, it is a hope, not a plan.
Rollback: plan it before you need it
Every migration plan needs a rollback section, written before the migration runs, and the honest version admits something uncomfortable: some migrations cannot be rolled back. Dropping a column destroys data. A contract-phase change has no reverse. Pretending otherwise is how teams end up improvising a recovery at 3 a.m.
For the expand and migrate phases, rollback is usually straightforward: revert the application code, and the old schema is still there, still populated, still working. That is one of the main reasons to split changes into phases — each phase keeps its own way back. For the contract phase, there is no way back, which is why it waits until the new schema has proved itself and the old code is gone. If the contract phase goes wrong, the recovery is a forward fix: a new migration that restores what was removed, or a restore from backup. Both are slower and more stressful than a code revert, so the contract phase gets the most review and the quietest deploy window.
A practical rule: if a migration's rollback is "restore from backup", say so in the plan, and make sure the restore time is acceptable — restoring a multi-terabyte database can take hours. If the business cannot accept that, the migration needs to be split into reversible phases, however long that takes.
Tooling: versioning, executors, and keeping the two apart
Two different kinds of tool solve two different problems, and confusing them is a common mistake. A versioning tool decides which change runs, in what order, and records that it ran. An online schema change executor decides how a change runs on a large, busy table without blocking writes. You usually need one of each.
The versioning tools are the familiar ones. Flyway keeps each change as a numbered SQL file, such as V1__create_orders.sql, applies the pending ones in order, and records each in a flyway_schema_history table. Liquibase uses a changelog of changesets that can be written in SQL, XML, YAML, or JSON, which lets one changelog target several engines. Alembic, for Python teams, generates migrations from SQLAlchemy models and can also run raw SQL. golang-migrate and dbmate cover the same ground for Go projects, and framework-native tools — Prisma Migrate, Django migrations, Rails migrations — do it inside the framework. A recent comparison of the MySQL migration tools lays out the differences in file format, language runtime, and how each one handles a partial run. The details differ, but the job is the same: every environment ends up with the same schema, applied in the same order, with a record of what ran.
The executors are gh-ost and pt-online-schema-change for MySQL, and pg_repack, pgroll, and pg-osc for PostgreSQL, plus the built-in online operations described earlier. A versioning tool on its own will happily run a statement that copies a huge table under a lock, because to it that is just one more migration. An executor on its own has no idea which migrations an environment has already applied. Several tools bridge the gap — Liquibase can hand a change to an executor through its Percona integration, and Bytebase drives gh-ost — but with most combinations you wire the hand-off in CI yourself: the versioning tool owns the order and the record, and the executor owns the execution for the risky changes.
The pre-deploy checklist
Run through this before any migration that touches a table with real traffic. If any answer is no, the migration is not ready.
- The change is split into expand, migrate, and contract phases, each a separate deploy.
- Every statement's lock mode is known, and nothing holds
ACCESS EXCLUSIVEon a hot table for longer than milliseconds. lock_timeoutis set, so a blocked statement fails instead of queueing.- Indexes are built with
CREATE INDEX CONCURRENTLYor the engine's online equivalent. - Backfills run in small batches with pauses, and can be stopped and resumed.
- The migration has run against a staging database restored from production data, with timing measured.
- The rollback has been run somewhere, not just written down.
- A backup was taken before the change, and the restore time is acceptable.
- Old and new code versions both work against the schema at every phase.
- Someone is watching error rates, latency, and replication lag during the deploy, with a named person who can stop it.
Questions teams actually ask
What about ORMs and auto-generated migrations?
ORM migrations are fine as a starting point, and they are where most teams begin. The risk is treating the generated file as finished. An auto-generated migration will happily emit a column rename as a drop-and-add, destroying data, or a type change as a rewrite. Read every generated migration before it ships, and rewrite the dangerous ones by hand. The ORM writes the migration; the engineer owns it.
How do I rename a column without downtime?
Use expand-and-contract: add the new column, keep both in sync with a trigger or a dual-write, backfill, switch reads behind a flag, then drop the old column in a later deploy. The rename itself is instant. The breakage comes from old code that still uses the old name, and the pattern exists to protect that code.
What if two migrations conflict?
Two developers adding migrations at the same time can produce the same version number or two changes that assume different starting schemas. Versioning tools detect the conflict when the second migration runs — Flyway will refuse to run out of order — but the fix is a human one: rebase, renumber, and check the combined result against staging. The cheapest prevention is a rule that every migration is reviewed with the schema diff it produces, not just the code around it.
What to do next
If your team has never had a migration incident, the most valuable thing you can do this week is small: add lock_timeout to your migration runs, and start checking the lock each statement takes before it ships. Those two habits alone prevent the most common outage in this article.
If you have had one, pick the pattern that would have prevented it and make it the default. Usually that means expand-and-contract for renames and type changes, batched backfills for data moves, and a staging restore from production data for anything touching a large table. Write the pattern down, put the checklist in the deployment runbook, and add a migration linter to CI so the next dangerous statement gets caught by a machine instead of by a customer.
Migrations break production because they are the one change where a small mistake meets live data, live traffic, and no undo button. The fix is not to fear schema changes. It is to split them into steps small enough th
Comments
Post a Comment