The Wild

Zero Downtime Database Migrations: Step-by-Step Guide

· 6 min read · Mammals

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Zero downtime database migrations let you change your database schema (like adding a column or creating an index) while your application stays fully available to users. The goal is to avoid locking tables or breaking queries during the migration, so there is no service interruption. This guide covers the core techniques—expand, migrate, contract—and how to apply them safely. You will need a database that supports transactional DDL (like PostgreSQL, MySQL with InnoDB, or SQL Server), a versioned migration tool (e.g., Flyway, Liquibase, Alembic), and the ability to deploy application code separately from the migration.

What You'll Need

  • A database with transactional DDL support (PostgreSQL, MySQL/InnoDB, SQL Server, etc.)
  • A migration tool that tracks applied versions (Flyway, Liquibase, Alembic, or similar)
  • Separate deployment pipelines for application code and database migrations
  • Access to a staging environment that mirrors production
  • Monitoring tools for database performance and query latency

Step-by-Step

  1. Plan the migration in phases. Break the schema change into three stages: expand (add new columns or tables), migrate (backfill or transform data), and contract (remove old columns or tables). Each phase must be deployable independently.
  2. Write the migration for the expand phase. Add the new column, table, or index without removing anything old. For example, if you are renaming a column, add a new column with the new name first. Ensure the new column is nullable or has a default so existing rows don't block the ALTER.
  3. Run the expand migration in staging first. Apply it to a copy of your production data to verify it completes quickly and doesn't lock the table for an unacceptable duration. Use tools like pt-online-schema-change (Percona) or gh-ost for MySQL if you need to avoid long locks.
  4. Deploy the expand migration to production. Run it during low traffic if possible, but the migration itself should not block reads or writes. Monitor database locks and query performance during the run.
  5. Update the application code to use the new schema. Deploy a new version of your app that reads and writes using the new column or table, while still being backward compatible (e.g., it can also read the old column if needed). This is the “migrate” phase—the app now writes to both old and new locations if necessary.
  6. Backfill or transform data. If you added a column that needs values, run a background job or a series of batched UPDATE statements to populate it. Do this in small batches (e.g., 1000 rows at a time) to avoid long transactions and locks.
  7. Verify data consistency. Run queries to compare old and new columns or tables to ensure the backfill is correct. Check for nulls or mismatches.
  8. Deploy the contract phase. Once the new schema is fully used and verified, write a migration that drops the old column, table, or index. This is the final step and should only be done after the app no longer references the old schema.
  9. Run the contract migration in staging, then production. Monitor for any errors or long locks. After it completes, verify the application still works as expected.
  10. Clean up. Remove any temporary backfill scripts, and update your migration tool’s baseline if needed.

Common Mistakes

  • Running a contract migration before the app is fully switched over—this causes downtime.
  • Backfilling a large table in a single transaction, which locks the table and blocks writes.
  • Adding a NOT NULL column without a default to an existing table—this locks the table and fails if there are rows.
  • Creating an index on a large table without using a concurrent method (like CREATE INDEX CONCURRENTLY in PostgreSQL) which blocks writes.
  • Forgetting to test the migration on a production-sized dataset.

Tips

  • Use online schema change tools for large tables—they copy the table incrementally and swap, avoiding long locks.
  • Keep migrations small and reversible. If a migration fails, you should be able to roll back to the previous version.
  • Automate the process with a CI/CD pipeline that runs migrations in staging and then production, with a manual approval gate.
  • Monitor query performance after each phase—sometimes a new index or column changes the query plan.
  • Have a rollback plan: if the app update fails, you can revert the app code without reverting the migration, as long as the schema is backward compatible.

Troubleshooting

  • Migration takes too long or locks the table. Stop the migration, roll back if possible, and switch to an online schema change tool. For PostgreSQL, use CREATE INDEX CONCURRENTLY for indexes; for adding columns, use ADD COLUMN ... DEFAULT NULL which is fast in PostgreSQL 11+.
  • Application errors after the expand phase. Check that the app is using the new column name correctly. If it still references the old column, the app code wasn't updated—revert the app to the previous version until the code is fixed.
  • Backfill job times out or fails. Break the backfill into smaller batches and run them in a loop with a delay. Use a primary key range to select batches.
  • Data inconsistency between old and new columns. Run a reconciliation query to find mismatches. Fix the data manually or re-run the backfill for the affected rows.
  • Contract migration fails because of a foreign key constraint. Drop the constraint first, then drop the column, then re-add the constraint if needed.

Frequently Asked Questions

Can I do a zero-downtime migration on any database?

Most relational databases support it, but the exact techniques vary. MySQL with InnoDB supports online DDL, but large tables may still lock. PostgreSQL is more flexible with concurrent indexes and fast column adds. SQL Server has online index operations. Always test on your specific version.

What if my migration requires changing a column's data type?

Use the expand-migrate-contract pattern: add a new column with the new type, update the app to write to both, backfill the new column from the old, then drop the old column. This avoids locking the table during a type change.

How do I handle a migration that must be atomic (all or nothing)?

Some migrations, like adding a constraint, can be done in a single transaction. For those, ensure the transaction is short. For larger changes, you may need to accept a brief lock or use a tool that supports online operations. Atomicity and zero downtime are sometimes trade-offs.

Is it safe to run migrations during peak hours?

It's safer to run during low traffic, but with proper online techniques, you can run during peak hours. However, always monitor performance and be ready to abort if latency spikes.

Do I need a separate migration tool?

Not strictly, but a versioned migration tool helps track what's been applied and ensures consistency across environments. Manual SQL scripts are error-prone.

What if I need to roll back a migration?

For expand and migrate phases, you can often just revert the app code and leave the schema changes (they are backward compatible). For contract phases, you may need to re-add the dropped column, which is possible if you have a backup or a reverse migration script.