SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • Deployment Strategies Overview
  • CI/CD Pipelines
  • Rolling Deployments
  • Blue-Green Deployments
  • Canary Releases
  • Feature Flags
  • A/B Testing Infrastructure
  • Schema Migrations
  • Rollbacks and Immutable Infrastructure
  • Multi-Region and Active-Active
  • Infrastructure as Code (Terraform)
  • Auto-Scaling Policies
  • Zero-Downtime Deployment
  • Chaos Engineering
  • Shadow Traffic and Dark Launches
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Deployment Patterns

Schema Migrations

Change the shape of a live database safely, without breaking the running app.

โฑ 14 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A schema migration is a planned change to the shape of a database: add a column, rename a table, change a type. The hard part is doing it while the app is live, with real users and several app versions running together.

  • During a deploy, old and new code run at the same time against one database. The schema must work for both.
  • The safe recipe is expand, migrate, contract: add the new thing, move to it step by step, and only then remove the old thing.
  • Big changes on big tables can lock the table. Do them in small batches.

02Concept: What is it?

Your database has a schema: the tables, columns, types and rules. When the product grows you must change it. A tool such as Flyway, Liquibase, Alembic, Rails migrations or Prisma Migrate keeps a numbered list of migration files. Each file says how to move the schema from version N to N+1. The tool records which ones have already run, so every environment ends up the same.

On a toy project you can stop the app, run the migration, and start again. A real service cannot stop. With a rolling deployment there is a time when some servers run the old code and some run the new code. Both talk to the same database. So every schema state in between must be compatible with both versions.

Why a one-step change breaks things
One-step rename
๐Ÿ–ฅ๏ธv1 (old)reads name
๐Ÿ–ฅ๏ธv2 (new)reads full_name
โ†“rename done
๐Ÿ—„๏ธusers(full_name)v1 fails: no column name
Expand and contract
๐Ÿ–ฅ๏ธv1 (old)reads name
๐Ÿ–ฅ๏ธv2 (new)writes both
โ†“both columns exist
๐Ÿ—„๏ธusers(name, full_name)works for both
The schema changes at one moment, but servers are replaced over minutes. In that gap, old code meets a schema it does not know.
๐Ÿง The golden rule
Never make a change that breaks the code that is running right now. Every migration must be safe for the old version of the app, and every app version must be safe for the old schema.

03Real-Life Example

๐ŸตRenovating a Shop That Stays Open
A shop wants to move its cash desk from the left wall to the right wall, but it cannot close. A bad plan: remove the left desk at 9 am and build the new one at 5 pm. Customers have nowhere to pay all day. A good plan: build the new desk on the right first (both desks work), tell staff to use either, wait until nobody uses the left desk, and only then remove it. At every moment of the day, customers can pay.
Shop
Schema migration
Building the new desk next to the old one
Expand: add the new column or table
Both desks work
Old and new code both work on the schema
Staff moving to the new desk
Deploy the new app version
Carrying stock to the new side
Backfill existing rows
Removing the old desk at the end
Contract: drop the old column
Closing the shop for a day
Downtime for a migration
Nobody can use the desk during building
A long lock on a big table
Expand and contract in five moments
โž•Expandadd new column
โ†’โ†“
๐Ÿš€Deploywrite both
โ†’โ†“
๐ŸššBackfillcopy old rows
โ†’โ†“
๐Ÿ‘€Switch readsuse new column
โ†’โ†“
๐ŸงนContractdrop old column

04Why Do We Need It?

โฑ๏ธNo downtime
Users keep working while the database changes under them.
โ†ฉ๏ธSafe to undo
Each small step can be reversed without losing data or breaking the app.
๐Ÿ”Same everywhere
Versioned migration files make dev, test and production match.
๐Ÿ”’Avoid long locks
Small steps and batches stop one big change from freezing a busy table.
๐ŸคRolling deploys work
Old and new app versions can run side by side during a release.
๐ŸงพA history
Every change is in version control, with a reason and an author.
The schema is shared by every running version of your code. Change it in small steps that are each safe for both the old and the new version.

05Where Do We Use It?

๐Ÿ› ๏ธMigration tools
Flyway, Liquibase, Alembic, Django and Rails migrations, Prisma Migrate and similar tools run numbered files in order.
๐ŸššCI/CD pipeline
The pipeline runs migrations before or after a deploy, depending on the plan.
๐ŸงฐOnline schema change tools
gh-ost and pt-online-schema-change (MySQL), pg_repack and careful DDL (PostgreSQL) change big tables without a long lock.
๐Ÿ“ฆEvent and API formats
The same idea applies to message formats and API versions: add first, remove last.
๐ŸƒDocument databases
Schemaless does not mean change-free. Old documents still have the old shape, so code must read both.
๐ŸขMulti-team services
Other services may read your tables or events, so removing a field needs a notice period.

06Types / Parts / How It Works

Safe and unsafe changes

ChangeSafe for old code?How to do it well
Add a nullable columnYesUsually the easy first step. Old code ignores it.
Add a column with a defaultDependsNewer versions of some databases do it instantly. Older ones rewrite the whole table. Check your version.
Add a NOT NULL columnNo, if old code does not set itAdd it nullable, backfill, then add the constraint.
Add an indexYes, but can lockBuild it online or concurrently (for example CREATE INDEX CONCURRENTLY in PostgreSQL).
Rename a column or tableNoAdd the new one, write both, backfill, switch reads, drop the old one.
Change a column typeOften noAdd a new column of the new type and copy over, same as a rename.
Drop a columnNo, if any code still uses itStop all use first, deploy, wait, and only then drop.
Add a foreign key or a unique ruleCan fail or lockAdd it as not validated, clean the data, then validate.

The expand, migrate, contract pattern

  1. 1
    Expand
    Add the new column, table or index. Do not remove anything. Old code is unaffected.
  2. 2
    Dual write
    Deploy code that writes both the old and the new column and reads the new one, falling back to the old.
  3. 3
    Backfill
    Copy old rows to the new column in small batches, pausing if the database is busy.
  4. 4
    Switch reads
    Once every row is filled, read only from the new column.
  5. 5
    Contract
    After a safe waiting period, stop writing the old column and drop it.
Compatible in both directions
๐Ÿ“œSchema N
โ†”old app and new app both fine
๐Ÿ“œSchema N+1
Backward compatible Forward compatible
Between the two changes, the app and the schema must be compatible with each other in both directions.

Two ways to run migrations

WayHow it worksWatch out
Before the deployRun the migration, then roll out the new codeThe schema must work for the OLD code. Fits expand steps.
After the deployRoll out the new code, then run the migrationThe NEW code must work on the old schema. Fits contract steps.
At app startEach server runs migrations when it bootsMany servers may race. Use a lock, or run it as one separate job.
VisualizerRename a column while the app is being deployedStep through the one-step rename and watch the old servers fail. Then switch to expand and contract and see that nothing ever errors.
How do we rename the column?
๐Ÿ–ฅ๏ธ
v1
works
๐Ÿ–ฅ๏ธ
v1
works
๐Ÿ–ฅ๏ธ
v1
works
๐Ÿ–ฅ๏ธ
v1
works
โ†“ โ†‘
๐Ÿ—„๏ธ
Database table
namefull_name
users(name)
0% of requests fail now
Step 1 of 4
Start: 4 old servers (v1)
Everything works. v1 reads and writes the column name.
Worst moment
100%
requests failing
Steps with errors
2 of 4
of the plan
Database changes
1
each one small and safe
Can the app roll back?
No
old code needs name
One-step rename: the database and the app change at different moments, and for a while old code meets the new schema. Failures are built in. A rolling deploy makes this window long.

A simplified model: 4 app servers behind a load balancer, an even spread of requests, and a rename done as a single instant change. Real databases differ in how long a change locks a table, so large tables need extra care (batches, online schema tools).

07How to Use It / Steps / Implementation

Changing a live table safely

  1. 1
    Keep migrations in version control
    One numbered file per change, reviewed like code. Never edit a migration that has already run in production. Add a new one.
  2. 2
    Make each migration small
    One idea per file. A small step is easy to review, test and undo.
  3. 3
    Expand first
    Add the new column nullable, or the new table. Do not drop or rename anything yet.
  4. 4
    Deploy code that handles both
    Write both columns. Read the new one, and fall back to the old one if it is empty.
  5. 5
    Backfill in batches
    Update a few thousand rows at a time, with a short pause between batches, so you do not lock the table or flood replicas with lag.
  6. 6
    Verify before you contract
    Check that no row is missing the new value and that no running code still reads the old column. Look at query logs.
  7. 7
    Contract later
    Wait at least one full release cycle, so you could still roll the app back. Then drop the old column in its own migration.
  8. 8
    Test on a copy of production data
    A migration that takes 1 second on a small test table can take an hour on a table with millions of rows.
Example: add a column the safe way (generic SQL)
-- 1. Expand (migration 1)
ALTER TABLE users ADD COLUMN full_name TEXT NULL;

-- 2. Deploy app v2: write name AND full_name, read full_name (fallback to name)

-- 3. Backfill, in batches, repeated until 0 rows are updated
UPDATE users SET full_name = name
 WHERE id IN (SELECT id FROM users WHERE full_name IS NULL LIMIT 5000);

-- 4. Contract (a later migration, after v1 is gone for good)
ALTER TABLE users DROP COLUMN name;
โš ๏ธRolling back the app is easy. Rolling back data is not.
If a migration drops or changes data, going back to the old app code does not bring the data back. That is why the contract step comes last, and why you take a backup before any destructive change.
๐Ÿ’กUse a feature flag for the switch
Put the read-from-new-column step behind a flag. If the new column turns out to be wrong, flip the flag back in seconds without a deploy.

08Key Terms to Know

TermMeaning in easy words
SchemaThe structure of a database: tables, columns, types, keys and rules
MigrationA versioned script that moves the schema from one version to the next
Expand and contractAdd the new thing first (expand), move over, and remove the old thing last (contract)
Parallel changeAnother name for expand and contract
BackfillFilling a new column with values for rows that already exist
Backward compatibleThe new schema still works for the old code
Rolling deploymentReplacing servers with a new version a few at a time
Online schema changeChanging a big table without blocking reads and writes for long
LockA hold on a table or row that makes other queries wait
Down migrationA script that undoes a migration. Often impossible if data was lost
Dual writeWriting the same data to the old and the new place during a move

09Pros, Cons and Trade-offs

โœ… Pros
  • No downtime for users
  • Each step is small and reversible
  • Works with rolling, canary and blue-green releases
  • Clear history of every change
  • Old and new code can coexist safely
โš ๏ธ Cons
  • One change takes several releases
  • Temporary extra columns and extra code
  • Backfills on big tables are slow
  • Needs discipline and reviews
  • Easy to forget the final cleanup

Trade-offs

ChoiceWe gainWe lose
One-step change in a maintenance windowSimple, one releasePlanned downtime, and a risky all-at-once change
Expand and contractNo downtime, easy undoMore releases and temporary clutter
Backfill in small batchesNo long locks, less replica lagA longer total time
Backfill in one big updateFast to writeA long lock, slow queries and possible timeouts
Drop the old column at onceA clean schema right awayNo way to roll the app back
Wait before droppingA safe rollback pathExtra storage and a task to remember

10Common Problems and Mistakes

Common mistakes

  1. Renaming or dropping in one step. Old servers fail the moment the schema changes.
  2. Adding a NOT NULL column without a default. Old code that does not set it fails on every insert.
  3. A huge update in one transaction. It locks rows for a long time and makes replicas fall behind.
  4. Editing an old migration. Environments that already ran it now differ from the file.
  5. Never testing on real-sized data. The migration is quick in test and takes the site down in production.
  6. Forgetting other readers. A report job, another service or a data pipeline still reads the old column.
  7. No cleanup. The old column stays forever and confuses the next developer.

Things to watch

๐Ÿ”’Lock waits
A quick ALTER can wait behind a long query, and then block everything else queued behind it.
๐ŸขReplica lag
A big write on the primary may reach read replicas slowly, so reads look stale.
๐Ÿ’พDisk space
Some changes copy the whole table and need extra room while they run.
๐Ÿ”€Two migrations at once
Two servers starting together may both try to run the same migration. Use a lock.

11Real-World Examples

๐ŸฌMySQL at scale
Teams use tools such as gh-ost or pt-online-schema-change to copy a big table in the background and swap it in.
๐Ÿ˜PostgreSQL
Teams use concurrent index builds, not-validated constraints and small backfill batches to avoid long locks.
๐Ÿ›’Always-open shops
Online services that cannot stop use expand and contract for almost every change that touches live data.
๐Ÿ”Rails, Django and others
Frameworks ship migration tools. Add-ons warn when a migration is unsafe for a live system.
๐Ÿ“จEvent schemas
The same rules apply to message formats: add optional fields first, and remove them only after every reader is updated.
๐ŸงฏIncident lesson
Many outages start with a migration that locked a hot table. Reviews often look for this one thing.
๐Ÿ“Note
Lock behaviour and speed depend on the database and its version. Read the docs for the exact command you plan to run.
Mini case: renaming a column on a big table
๐Ÿ“…Day 1add full_name
โ†’โ†“
๐Ÿ“…Day 2deploy dual write
โ†’โ†“
๐Ÿ“…Day 3backfill in batches
โ†’โ†“
๐Ÿ“…Day 4switch reads (flag)
โ†’โ†“
๐Ÿ“…Week 3drop name
Illustrative timeline.

12Related Topics to Read Next

Rolling Deploymentsโ†’

The reason old and new code run together, and why the schema must fit both.

Rollbacks and Immutable Infrastructureโ†’

Rolling back code is easy. Rolling back data is the hard part.

Feature Flagsโ†’

Switch reads to the new column with a flag you can flip back.

Blue-Green Deploymentsโ†’

Both environments share one database, so the schema must fit both.

ACID Transactionsโ†’

How a migration can succeed or fail as a whole.

Replicationโ†’

Big changes on the primary can make replicas lag.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Rule: every step must be safe for the old AND the new code.
  • โœ”Pattern: expand, dual write, backfill, switch reads, contract.
  • โœ”Never: rename or drop a column in one step on a live system.
  • โœ”Backfill: small batches, restartable, watch locks and replica lag.
  • โœ”Safe: add nullable column, add index concurrently. Risky: NOT NULL, type change, drop.
  • โœ”Order: additive changes before the deploy, destructive changes after.
  • โœ”Test: on real-sized data. Back up before anything destructive.
  • โœ”One line: โ€œAdd the new, move over slowly, and remove the old last.โ€
โ† Previous
A/B Testing Infrastructure
Next โ†’
Rollbacks and Immutable Infrastructure