Schema migrations without downtime
Change a live database schema in small steps that old and new code can both survive, with a way back at every step.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
GoCardless is a payments company. Its team wrote about a schema migration that went wrong. It renamed some invoicing tables and dropped and recreated their foreign keys. The tables were empty, and no production code used them yet. 1
Just after the migration started, alerts fired: API requests were timing out. This lasted about 15 seconds. Then the migration finished and the API came back. 1
The strange part: the same migration, run on a copy of the database, took a few hundred milliseconds. The ALTER TABLE itself was fast. 1
The cause was a lock. On their Postgres version, adding the foreign key needed an AccessExclusive lock on both tables. That included the busy parent table. A long-running read query was already using it. So the ALTER waited. And every normal query that arrived after it waited behind the ALTER. 1 Current Postgres docs list a weaker lock for this, SHARE ROW EXCLUSIVE. It still blocks writes. 2 3
For 15 seconds, the API's own reads and writes piled up, and clients timed out. The fix they suggest is short: set lock_timeout in migration scripts. "It's better to abort a deploy than take your application down." 1
The idea in simple words
A schema change on a live database can hurt you in three ways.
- Locks. Many changes need a strong lock on the table. While they wait for it or hold it, other queries stop.
- Table rewrites. Some changes copy the whole table. On a big table that can take a long time and double the disk space. 2
- Two versions of code. During a rolling deploy, new pods start while old ones still run. 10 Both versions must work with the schema at every moment.
The fix is to never make a big change in one step. Split it into small steps that each keep old and new code working. This is called expand and contract, or parallel change: expand to support old and new, migrate the users, then contract to remove the old. Sato writes that most database refactorings follow this pattern. 8
The key idea. Never change the schema and the code in a way that needs both to switch at the same moment. Add first, move slowly, remove last.
How it works
Step through a column rename done safely across several deploys. Use Next and Back, or the ← and → keys.
- Goal: rename users.name to full_name with no downtime. Step 1 adds the new column with no default and no NOT NULL. It is a quick metadata change, but it still needs a short lock, so set lock_timeout. Old code ignores the new column.
- Deploy app v2. It writes every change to both columns but still reads name. During the rolling deploy, v1 and v2 run side by side, and both work.
- Run a backfill job. It copies name into full_name for old rows, a small batch at a time, with a pause between batches. Start it only after every v1 pod is gone, so no new row misses full_name. Then check that no row differs.
- Deploy app v3. It reads full_name and still writes both columns. If v3 has a bug, you can roll back to v2, because name is still up to date.
- When v3 is stable, deploy v4, which stops writing name. If name is NOT NULL, drop that constraint first, or v4 inserts fail. Wait until no code, report or job reads name. Then drop it. Each step was a small change you could undo.
Know your locks
In Postgres, ALTER TABLE takes an ACCESS EXCLUSIVE lock unless the docs say otherwise. 2 That lock conflicts with every other lock mode. It is the only one that blocks a plain SELECT. 3 By default, a statement waits for a lock with no time limit. 3
So set lock_timeout in your migration session. It aborts a statement that waits too long for a lock. Its default is 0, which means no timeout. 5 If the migration times out, retry it later. A failed deploy is better than a down API. 1
Also find long-running queries and transactions before you migrate. GoCardless advises removing them, and splitting schema changes into smaller pieces. 1
Adding a column
In Postgres, adding a column with no default, or with a non-volatile default such as a constant, does not rewrite the table. A volatile default, such as clock_timestamp(), rewrites the whole table and its indexes. 2 Even the fast form takes an ACCESS EXCLUSIVE lock for a moment, so set lock_timeout. 2
In MySQL 8.4, ADD COLUMN uses the INSTANT algorithm by default, with some limits. 6
Our advice: add new columns as nullable or with a constant default. Old code that names its columns ignores them, so this step is safe on its own.
Renaming and changing types
Renaming a column in Postgres does not touch stored data. 2 MySQL 8.4 can often rename a column instantly, if the type stays the same. 6 But the fast rename is still a trap. Old pods ask for name the moment it becomes full_name, and they fail.
So rename with the five steps in the diagram. The same goes for changing a type. In Postgres, most type changes rewrite the table and its indexes. 2 In MySQL, a type change uses a full table copy with no writes allowed during it. 6 Add a new column of the new type instead, then move the data.
Adding NOT NULL and constraints
SET NOT NULL normally scans the whole table while it holds its lock. But if a valid CHECK constraint already proves there are no nulls, Postgres skips the scan. 2
So do it in three steps:
- Add
CHECK (full_name IS NOT NULL) NOT VALID. This skips the check of old rows. It still needs anACCESS EXCLUSIVElock for a moment. 2 - Run
VALIDATE CONSTRAINT. It scans the table, but takes only aSHARE UPDATE EXCLUSIVElock, so normal reads and writes continue. 2 - Run
SET NOT NULL, which now skips the scan. 2 You can then drop theCHECK.
The current docs also allow NOT VALID on a not-null constraint itself. 2 Check your version before you rely on it.
Foreign keys work the same way: add them NOT VALID, then validate. Adding a foreign key locks both tables, so set lock_timeout here too. 2
Adding indexes
A normal CREATE INDEX in Postgres lets reads continue but blocks inserts, updates and deletes until it is done. 4 On a busy table, that is an outage.
Use CREATE INDEX CONCURRENTLY. It does not block writes. The cost: it scans the table twice, waits for older transactions, and takes much longer. It cannot run inside a transaction block. If it fails, it leaves an "invalid" index that still slows writes. Drop it and try again. 4
In MySQL 8.4, adding a secondary index runs in place and allows reads and writes. 6 For changes that MySQL cannot do online, tools like GitHub's gh-ost build a "ghost" copy of the table, copy rows over in small pieces and follow new changes from the binary log. It can pause, and you choose when it swaps the tables. 7
Backfills and dual writes
A backfill copies or fixes data in old rows. Our advice: do not run it as one giant UPDATE, which can hold row locks for a long time and make replicas fall behind. Instead, update a small batch of rows by primary key, commit, pause, and repeat. Make the job safe to stop and restart. Watch replica lag and slow it down if lag grows.
While the backfill runs, the app writes both the old and new columns, so new rows stay correct. Stripe used this for hundreds of millions of objects: dual write, move reads, move writes, then remove the old data. 9 It ran old and new reads side by side with GitHub's Scientist library and alerted when results did not match. 9
Rollback plans and backups
Our advice: give each step a way back. Until the contract step, rollback is easy: deploy the previous app version. The old column is still complete. After you drop a column, the only way back is a restore.
So before the contract step, take a backup and know how long a restore takes. GitLab's 2017 outage shows why. Its pg_dump backups had been failing because of a version mismatch, and the failure emails were rejected. 11 After an engineer deleted data on the primary by mistake, about six hours of data was lost, and the site was down for about 18 hours. 11 A backup you have never restored is only a hope.
Trade-offs
| Approach | Downtime? | Old and new code both work? | Effort | Use it when |
|---|---|---|---|---|
| One big migration in a maintenance window | Yes Planned. | No Everything switches at once. | Low. | Small internal tools where a short outage is fine. |
Direct change with lock_timeout | No , if it is metadata only and gets its lock fast. 5 | Yes , for adds. No, for renames and drops. | Low. | Adding a nullable column, or a concurrent index. |
| Expand and contract | No | Yes , at every step. 8 | High. Several deploys over days. | Renames, type changes, splitting tables, anything a running app reads. |
| Online copy tool (gh-ost, similar) | Mostly no. You choose when the final swap happens. 7 | Yes , if the change itself is compatible. | Medium. Needs disk space and care. | Big MySQL tables where the change would rebuild the table. |
Simple rule: if a change removes or renames something that running code reads, it needs expand and contract. Otherwise, a single small migration with a lock timeout is usually fine.
At work: how a senior uses this
- For every migration, ask: "What lock does this take, and for how long?" Check the docs for that exact statement.
- Ask: "Does the code running right now still work after this migration? Does the next version work before it?"
- Keep schema changes and code changes in separate deploys. For an add, run the migration first. For a drop, deploy the code that stops using the column first.
- Set
lock_timeoutin every migration session. Also setstatement_timeout, but raise it for slow steps likeVALIDATE CONSTRAINT. - Run big backfills as a job, not inside the migration. Batch, pause, and make it restartable.
- Test the migration on a copy of production data size, not an empty test database.
- Write the rollback plan in the pull request. Say when the point of no return is.
- Test a restore from backup on a schedule, and alert when a backup job fails.
With AI
What to ask the agent
"Here is a Postgres migration. For each statement, tell me the lock it takes and whether it rewrites or scans the table. Quote the PostgreSQL docs."
"Split this column rename into expand and contract steps. Give me the migrations and code changes for each deploy, and the rollback for each step."
"Write a backfill job that copies name to full_name in batches of 1,000 rows by id, with a pause, a resume point and a progress log."
What to check yourself
- No migration renames or drops a column that the deployed code still reads.
- Index builds on big Postgres tables use
CONCURRENTLY, outside a transaction. Some migration tools wrap each file in a transaction, so check yours. NOT NULLand foreign keys are addedNOT VALIDfirst, then validated.- No volatile default on a new column, and no type change on a big table.
lock_timeoutis set. AI agents rarely add it unless asked.- The backfill is batched, restartable and does not run inside the schema migration.
- There is a tested backup before any step that deletes data.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 11 sources and related lessons
- Chris Sinjakli, “Zero-downtime Postgres migrations: the hard parts”, GoCardless blog (opens in a new tab)
A real 15-second API outage caused by a fast ALTER TABLE that waited for a lock, and the fixes. - PostgreSQL documentation, ALTER TABLE (opens in a new tab)
The lock each form takes, which changes rewrite the table, and NOT VALID constraints. - PostgreSQL documentation, Explicit Locking (section 13.3) (opens in a new tab)
The table lock modes, and why ACCESS EXCLUSIVE blocks even plain reads. - PostgreSQL documentation, CREATE INDEX (opens in a new tab)
How CREATE INDEX CONCURRENTLY avoids blocking writes, what it costs, and how it can fail. - PostgreSQL documentation, Client Connection Defaults: lock_timeout (opens in a new tab)
The setting that makes a statement give up if it waits too long for a lock. - MySQL 8.4 Reference Manual, Online DDL Operations (opens in a new tab)
Which ALTER TABLE operations in InnoDB are instant, in place or a full copy. - GitHub, gh-ost: triggerless online schema migration for MySQL (opens in a new tab)
A tool that changes a big MySQL table by copying it to a ghost table while traffic runs. - Danilo Sato, “ParallelChange”, martinfowler.com, 2014 (opens in a new tab)
The expand, migrate and contract pattern, and why most database refactorings use it. - Jacqueline Xu, “Online migrations at scale”, Stripe blog, 2017 (opens in a new tab)
How Stripe moved hundreds of millions of objects with dual writes, backfills and checks. - Kubernetes documentation, Deployments (opens in a new tab)
How a rolling update replaces old pods with new ones step by step. - GitLab, “Postmortem of database outage of January 31” (2017) (opens in a new tab)
How every backup method failed silently, and what it cost.
Real incident: GitLab, 31 Jan 2017: GitLab outage: the primary database was wiped by mistake
Case studies: Stripe: Online data migrations in four safe steps
Related: Transactions and isolation levels · API versioning and deprecation · Safe deploys and config changes · Running large migrations (coming soon) · Feature flags and entitlements · Disaster recovery and backups · Sagas, outbox and CDC
- Safe deploys: how to roll out the code side of each step.
- Transactions and isolation levels: what locks are and why they wait.
- Coming next on this line: Running large migrations, API versioning and lifecycle and Disaster recovery and backups.