Zero Downtime Database Migrations: Safe Expand-Contract Playbook
In this article
- Background: Why Traditional Migrations Cause Downtime
- How Expand-Contract Works: The Three Phases
- Step-by-Step Playbook for a Safe Migration
- Common Problems and How to Avoid Them
- When to Use Expand-Contract vs. Alternatives
- Costs and Risks of Expand-Contract
- Safety and Verification Best Practices
- Frequently Asked Questions
Zero downtime database migrations are achievable with the expand-contract (or parallel change) pattern, which lets you deploy schema and application changes without taking the database offline. This playbook explains how to use it safely, covering the three phases—expand, migrate, and contract—along with the risks, rollback strategies, and when to choose an alternative. You'll learn the exact steps, common pitfalls, and how to verify each stage before moving on.
Background: Why Traditional Migrations Cause Downtime
Most database migrations fail because they assume the application and schema change at the same instant. In a typical expand-contract migration, you first add new columns or tables (expand), then backfill and migrate data while the old code still runs, and finally remove the old schema (contract) after the application has fully switched. The key is that each step is backward-compatible: the database works with both old and new application versions at every moment.
The alternative—a single atomic migration that alters tables and changes code in one deploy—requires locking tables, which blocks reads and writes. For large tables, locks can last minutes or hours, causing downtime. Expand-contract avoids this by making each migration step non-blocking and reversible.
How Expand-Contract Works: The Three Phases
The pattern has three distinct phases, each with its own deploy and verification step.
1. Expand
Add the new schema objects without removing or changing existing ones. For example, if you're renaming a column old_name to new_name, you add a new column new_name with a default value or allow NULL. You do not drop old_name yet. The application still uses old_name.
2. Migrate
Backfill the new column with data from the old one, and then deploy a new version of the application that reads from new_name and writes to both columns (dual-write). This is the critical step: the application must be able to handle both old and new code paths during a rolling deploy. Once the new code is fully deployed, you can verify that reads and writes are consistent.
3. Contract
After the new code has been running for a while and you're confident there are no issues, you remove the old column. This is a second migration that drops old_name. You also remove the dual-write logic from the application in a separate deploy. The contract phase is only safe after the migrate phase is fully complete and verified.
Step-by-Step Playbook for a Safe Migration
Here is a concrete checklist for executing an expand-contract migration with zero downtime:
- Identify the change: Determine what schema change you need (add column, rename, split table, etc.) and whether it's backward-compatible.
- Expand: Run a migration that adds the new schema (e.g.,
ALTER TABLE users ADD COLUMN new_name varchar(255)) without touching existing columns. Use a tool that supports online DDL (likept-online-schema-changefor MySQL orONLINEin PostgreSQL) to avoid long locks. - Backfill: Update the new column with data from the old one. For large tables, do this in batches to avoid long transactions. Example:
UPDATE users SET new_name = old_name WHERE id BETWEEN ? AND ?repeated until done. - Deploy application with dual-write: Update the code to read from
new_nameand write to bothnew_nameandold_name. Deploy this version to all instances, but keep the old code running on some instances during the rollout. - Verify consistency: Run checks to ensure that both columns have the same data and that reads return correct values. For example, compare counts of rows where
new_namediffers fromold_name. - Contract: After a soak period (hours or days), run a migration that drops the old column. Then deploy a new application version that only uses
new_name. - Cleanup: Remove any temporary indexes or triggers created during the migration.
Common Problems and How to Avoid Them
Even with expand-contract, things can go wrong. Here are the most frequent issues and their mitigations:
- Backfill takes too long: For huge tables, a single UPDATE can lock rows for minutes. Use batched updates and run them during low traffic.
- Dual-write inconsistency: If the application writes to both columns but one write fails (e.g., due to a trigger), you get drift. Use transactions that write to both columns atomically, or use a trigger to keep them in sync.
- Rollback complexity: If you need to roll back after the expand phase, you can simply drop the new column. But after the contract phase, rolling back is harder because the old column is gone. To mitigate, keep a backup or allow a longer soak period.
- Application code not fully backward-compatible: If the new code reads from
new_namebut some instances still run old code, you get errors. Ensure the deploy is truly rolling and that any instance running old code can still write to the old column.
When to Use Expand-Contract vs. Alternatives
Expand-contract is the go-to for most online schema changes, but it's not the only option. Consider these alternatives:
- Blue-green deployment: Run two separate database schemas and switch traffic. This is more complex but allows instant rollback.
- Online schema change tools: Tools like
gh-ostorpt-online-schema-changeautomate the expand-contract pattern for specific databases. They handle the backfill and dual-write for you, but you still need to coordinate application changes. - Eventual consistency with a message queue: For very large data migrations, you might use a queue to replay changes after the fact. This is more advanced and usually overkill.
Choose expand-contract when you need zero downtime and can manage a multi-step deploy. If you can afford a brief maintenance window, a simple offline migration might be easier.
Costs and Risks of Expand-Contract
The main cost is complexity: you have to write dual-write code, manage a longer deploy window, and maintain both old and new schema temporarily. There's also a risk of data drift if the dual-write isn't atomic. However, the benefit—zero downtime—often outweighs these costs for high-traffic systems.
Another risk is that the contract phase might fail if you haven't verified that all reads are using the new column. Always run a soak test and monitor error rates after the migrate phase.
Safety and Verification Best Practices
To ensure a safe migration, follow these practices:
- Use transactions where possible: For dual-write, wrap writes to both columns in a single transaction to avoid partial updates.
- Monitor performance: Watch for slow queries or lock contention during backfill.
- Have a rollback plan: Before each phase, know how to revert. For expand, drop the new column. For migrate, redeploy old code. For contract, restore from backup if needed.
- Test on a staging environment: Always rehearse the migration on a copy of your production data.
Frequently Asked Questions
Can I do a zero-downtime migration without dual-writes?
Sometimes, if the change is additive (e.g., adding a new column with a default), you can skip dual-writes and just expand, then deploy new code that reads the new column. But for renames or changes that affect existing data, dual-writes are usually necessary to keep old and new code working during the transition.
How long should the soak period be?
It depends on your traffic and confidence. A common practice is 24-48 hours, but for critical systems, a week is safer. The goal is to catch any issues with the new code before you drop the old schema.
What if I need to roll back after the contract phase?
Rolling back after dropping a column is difficult. You'd need to restore from a backup or re-add the column and backfill from logs. To avoid this, ensure the contract phase is only done after a long soak period and after monitoring shows no errors.
Does expand-contract work with foreign keys?
Yes, but you need to be careful. Adding a foreign key can lock the table. Use online DDL tools that support foreign key operations, and consider deferring constraint checks if possible.
Is it safe to run backfill while the application is writing?
Yes, but you must handle concurrent writes. The backfill should be idempotent—running it multiple times should produce the same result. Use batched updates and ensure they don't conflict with application writes.
Can I use expand-contract for sharded databases?
Yes, but you need to apply the pattern per shard. The complexity increases because you have to coordinate migrations across multiple databases. Tools like gh-ost can be run per shard, but you need a way to track which shards are done.