How would you handle a database schema change without downtime?
In one line: Use the expand-and-contract pattern: make backward-compatible changes in small steps so old and new versions of the app can both work with the database during the rollout, and remove old structures only later.
Why it's tricky: during rolling, blue/green or canary deployments, the old and new app versions run at the same time against the same database. If the new version renames a column, the old version breaks immediately. And if you need to roll back, the old version must still work.
Expand and contract — example: renaming name to full_name
- Expand — add the new column (
full_name), nullable. Old code ignores it. ✅ safe. - Dual write — deploy app code that writes to both
nameandfull_name, and still readsname. - Backfill — copy existing data from
nametofull_namein small batches (to avoid locking big tables). - Switch reads — deploy code that reads from
full_name(still writing both, so rollback is safe). - Stop writing the old column — once you're confident.
- Contract — in a later release, drop the
namecolumn.
Each step is a separate, small, reversible deployment.
Other good practices:
- Migrations as code with tools like Flyway, Liquibase, Alembic, Prisma or Django/Rails migrations — versioned in Git and run by the pipeline.
- Avoid long locks — on big tables, use online schema change tools (gh-ost, pt-online-schema-change) or database features (for example
CREATE INDEX CONCURRENTLYin PostgreSQL). - Run migrations separately from the app rollout (a pre-deploy job), and make them idempotent.
- Test migrations on a production-sized copy of the data to know how long they take.
- Back up before risky changes.
- Never make destructive changes (drops, renames, type changes) in the same release as the code that stops using them.
Tip for interviews: naming "expand and contract" and walking through the steps is exactly what interviewers want here.