How to Migrate a Database Schema at Scale
In this article
Migrating a database schema at scale means changing the structure of tables, indexes, or constraints across a large, production database—often with millions of rows and high availability requirements. The goal is to apply the change without downtime, data loss, or performance degradation. This guide covers a safe, repeatable process using expand-and-contract (parallel change) and online migration tools, plus rollback planning.
What You'll Need
- Access to a staging environment that mirrors production data size and load
- Database admin credentials (read/write) and the ability to create backups
- A schema migration tool: e.g., Flyway, Liquibase, or a database-specific tool like pgroll (PostgreSQL), gh-ost (MySQL), or online DDL in cloud databases
- Monitoring dashboards for query latency, CPU, disk I/O, and replication lag
- A rollback plan: either a reversible migration or a backup/restore strategy
- Communication channel with the team to coordinate deploys
Step-by-Step
- Assess the current schema and workload. Document all tables, indexes, foreign keys, and triggers. Identify which tables are large (e.g., >1M rows) and which queries are hot paths. This tells you where the risk is highest.
- Choose a migration strategy. For small tables, a simple ALTER TABLE may be fine. For large tables, use an online tool that copies data in the background (e.g., gh-ost for MySQL, pgroll for Postgres) or use the database's native online DDL if available. Avoid locking the table for the duration.
- Write the migration script. The script should be idempotent (can run multiple times safely) and include checks for existing columns/indexes. Use version-controlled migration files.
- Test on a staging copy. Restore a recent production backup to staging, then run the migration. Measure: duration, lock time, replication lag, and any errors. Compare query performance before and after.
- Plan for expand-and-contract (if adding a column or changing a constraint). First, add the new column or index without dropping the old one. Deploy application code that reads/writes to both old and new structures during a transition period. Then, backfill data if needed. Finally, drop the old structure in a later release.
- Take a full backup. Before starting on production, take a consistent backup (or ensure point-in-time recovery is enabled). This is your safety net.
- Schedule the migration during low traffic. Even with online tools, CPU and I/O spikes are common. Pick a window with minimal writes (e.g., early Sunday morning) and alert the team.
- Run the migration in production with monitoring. Execute the tool and watch: lock waits, replication lag, disk space, and error logs. Most online tools have a throttle option—use it if latency spikes.
- Validate the schema and data integrity. After completion, run checks: row counts, sample queries, and foreign key integrity. Compare a few hashes of critical columns.
- Update application code (if needed). Deploy the application changes that rely on the new schema. Ensure the code is backward-compatible with the old schema during the transition.
- Clean up old structures. After the new schema is stable for a few days (or a release cycle), drop old columns, indexes, or tables. This is the “contract” phase.
- Document the migration. Record what changed, why, and any issues encountered. This helps future migrations.
Common Mistakes
- Running a blocking ALTER on a large table without an online tool—this can lock writes for hours.
- Not testing on a full-size staging copy—small data hides performance problems.
- Forgetting to backfill new columns before deploying code that reads them—this causes nulls or errors.
- Dropping the old column too soon, before the application is fully rolled back-compatible.
- Ignoring replication lag—if you have read replicas, the migration can fall behind and serve stale data.
- Not having a rollback plan that is actually tested.
Tips
- Break large migrations into smaller, reversible steps. For example, add a column, then backfill, then add a constraint.
- Use a shadow table approach: create a new table with the desired schema, copy data in batches, then swap names.
- Use database tools that support online schema changes, such as gh-ost for MySQL or pgroll for Postgres.
- Set a lock timeout (e.g., lock_timeout in Postgres) to prevent indefinite waits.
- Monitor replication lag continuously; if it exceeds a threshold, throttle or pause the migration.
- Have a runbook with exact commands and rollback steps, so any on-call engineer can execute it.
Troubleshooting
- Migration is stuck or locking. Check active queries and locks. If it's a blocking ALTER, cancel it and switch to an online tool. If using an online tool, check if it's paused due to high load.
- Replication lag is increasing. Throttle the migration (most tools have a --max-lag flag). If it persists, pause and resume during off-peak.
- Data inconsistency after migration. Restore from backup and re-run with more validation. Use checksums or row counts to identify mismatches.
- Application errors after deploy. If the app expects the old schema, roll back the app code first, then revert the schema (if reversible) or plan a forward fix.
- Disk space runs out. Online tools often need extra space for temporary tables. Stop the migration, free space, and resume.
- Migration tool crashes mid-way. Most online tools are resumable. Check logs, clean up partial data, and re-run.
Frequently Asked Questions
Can I just run ALTER TABLE on a large table?
For tables under a few hundred thousand rows, it's usually fine. For millions of rows, it will lock the table and block writes—use an online migration tool instead.
What is expand-and-contract?
It's a pattern where you add a new schema element while keeping the old one, deploy app code that works with both, then remove the old element later. This allows zero-downtime changes.
How do I know if my migration is safe?
Test on a staging copy with production-sized data. Monitor lock time, replication lag, and query performance. If any metric degrades beyond thresholds, abort.
What if I need to roll back?
If the migration is reversible (e.g., you added a column), you can drop it. If not, restore from backup. Always have a tested rollback plan.
Do I need to update application code first or after?
It depends. For expand-and-contract, deploy app code that supports both old and new schema first, then migrate. For simple additive changes, migrate first, then deploy app code that uses the new column.
How long does a large-scale migration take?
It varies widely: from minutes for small tables to hours or days for terabytes of data. Use online tools that can run in the background and throttle based on load.