Audit Database Migrations Before Production: How-To
In this article
Database migrations are the riskiest changes most teams ship. A single bad migration can lock a table, drop a column in use, or take the database down during peak hours. Auditing migrations before they reach production catches these problems early, when they are cheap to fix. This guide walks through a practical, step-by-step audit process you can apply to any SQL migration, whether you use Rails, Django, Flyway, Liquibase, or plain SQL scripts. You will learn what to check, how to check it, and what to do when something goes wrong.
What You'll Need
- Access to the migration files (the SQL or ORM migration scripts) for the current branch and the target branch.
- A local database that matches your production version (PostgreSQL, MySQL, etc.) and a way to restore a recent production-like backup into it. If you cannot get a full backup, use a schema dump.
- Read-only access to production schema metadata (table definitions, indexes, foreign keys) or a recent schema dump. You do not need production data for most checks.
- A tool to run the migration in a controlled way: your ORM's migration command, a database client, or a CI pipeline that can run migrations against a test database.
- Optional but helpful: a staging environment that mirrors production, and a monitoring dashboard for database metrics (lock waits, connection count, slow queries).
Step-by-Step
- List all migrations in the change set. Compare the migrations in your feature branch against the ones already applied in production. Use your migration tool's status command (e.g.,
rails db:migrate:status,django showmigrations,flyway info) to see which are new. Write them down in the order they will run. - Read each migration like a code review. For each new migration, open the file and ask: What does it change? Does it add, remove, or alter a column? Does it create or drop an index? Does it modify data? Does it lock a table? Write a one-line summary for each migration. This forces you to understand the intent before you check the mechanics.
- Check for destructive operations. Look for
DROP TABLE,DROP COLUMN,ALTER COLUMN TYPE(which often rewrites the table),TRUNCATE, orDELETE FROMwithout a WHERE clause. These are red flags. If you see one, verify that the data is truly no longer needed, that backups exist, and that the operation is reversible. If it is not reversible, you need a rollback plan. - Verify index changes carefully. Adding an index on a large table can lock writes for minutes or hours. Check if the migration uses
CREATE INDEX CONCURRENTLY(PostgreSQL) or an online index operation (MySQL'sALGORITHM=INLACE). If it does not, the migration may block production traffic. Also check for redundant indexes: adding an index that is a prefix of an existing one is wasteful. - Test the migration on a copy of production data. Restore the most recent production backup into a local database. Run the migration against it. Time how long it takes. If it takes more than a few seconds, it will likely cause lock contention in production. If it takes minutes, you need a maintenance window or an online migration strategy.
- Run the migration in a transaction (if supported). Many databases (PostgreSQL, MySQL with InnoDB) support transactional DDL. Wrap the migration in a transaction and test that you can roll it back cleanly. If the migration fails halfway, the transaction should leave the schema unchanged. If your database does not support transactional DDL, plan for manual rollback steps.
- Check for data integrity issues. If the migration adds a NOT NULL constraint to a column with existing NULLs, it will fail. If it changes a column type, verify that the existing data can be cast without loss. Run a query on your test database to find rows that would violate the new constraint. For example, before adding a CHECK constraint, run
SELECT COUNT(*) FROM table WHERE NOT (condition). - Review the migration's dependencies. Does the migration reference tables or columns that are created by an earlier migration in the same batch? Does it depend on data that is inserted by a seed script? Run the migration from a clean schema (not just from the previous migration) to catch ordering issues. Your migration tool should handle ordering, but it is worth verifying.
- Simulate the migration on a read replica or staging. If you have a staging environment, apply the migration there first and run a smoke test: execute a few typical queries that your application uses. This catches issues like a missing column in a SELECT * or a changed column name that breaks an ORM mapping.
- Document the audit results. For each migration, record: the file name, the summary, the time it took on the test database, any locks it will take, and the rollback plan. Share this with the team before merging. If any migration is risky, flag it for a manual review or a scheduled maintenance window.
Common Mistakes
- Skipping the data copy. Testing against an empty database never reveals lock contention or data conversion issues. Always test against a copy of production data.
- Ignoring lock duration. A migration that runs in 200ms on a small table might take 20 minutes on a 100GB table. Always time it on a realistic dataset.
- Assuming rollback works. Many migration tools do not support automatic rollback for DDL. Test your rollback manually before you rely on it.
- Not checking for NULLs before adding NOT NULL. This is the most common cause of failed migrations in production. Always run a count query first.
- Mixing data changes with schema changes. A migration that both alters a column and updates data is harder to audit and roll back. Split them into separate migrations if possible.
- Forgetting about background jobs. If your application runs background workers, they may be using the old schema. A migration that changes a column type can break a running job. Coordinate with your team to pause or queue jobs during the migration.
Tips
- Use a migration linting tool. Tools like
strong_migrations(Rails) orsquawk(PostgreSQL) can automatically flag dangerous operations likeDROP COLUMNor non-concurrent index creation. Integrate them into your CI pipeline. - Make migrations reversible by design. Write an explicit
downor rollback script for every migration, even if your tool does not require it. It forces you to think about the inverse operation. - Keep migrations small and focused. A migration that does one thing is easier to audit and roll back. If a migration is doing too much, split it.
- Schedule risky migrations during low traffic. Even with online DDL, it is safer to run during a maintenance window. Use your monitoring to find the least busy hours.
- Automate the audit. Write a script that runs the migration on a fresh database, times it, and checks for common issues (e.g., NULLs in a NOT NULL column). Run it in CI on every pull request that touches migrations.
- Review migrations in the same PR as the code that uses them. This ensures the migration matches the application code that will run against it.
Troubleshooting
Migration fails on the test database but works locally. The most likely cause is a difference in data. Check if the test database has a row that violates a constraint, or if a column has a different type. Run the failing query manually to see the error. If the test database is not a true copy, make a fresh backup.
Migration takes much longer than expected. Check if the table is large and if the operation requires a full table rewrite. For PostgreSQL, you can check pg_stat_activity to see if the migration is waiting on a lock. If so, either wait or use a concurrent approach. For MySQL, check SHOW PROCESSLIST.
Migration succeeds but the application starts throwing errors. This usually means the migration changed something the code does not expect. Check the migration's changes against the application's queries. A common issue is a renamed column that is still referenced in a raw SQL query. Roll back the migration and fix the code first.
Rollback fails. If your migration tool cannot roll back, you may need to manually restore the previous schema. If you have a backup, restore it. If not, you may need to write a reverse migration by hand. This is why testing rollback before production is critical.
Lock wait timeout in production. This happens when a migration tries to take a lock that another transaction holds. In production, you can use lock_timeout to make the migration fail fast instead of hanging. Then retry during a quieter time or use an online migration tool.
Frequently Asked Questions
Q: Can I audit migrations without a production backup?
A: Yes, but it is risky. You can use a schema dump and generate synthetic data, but you will miss data-specific issues like NULLs or data that cannot be cast. A recent backup is strongly recommended.
Q: How do I know if a migration will lock my table?
A: In PostgreSQL, use pg_locks to see what locks are held. In MySQL, use SHOW OPEN TABLES. Generally, operations that rewrite a table (like changing a column type) take an exclusive lock. Adding an index without CONCURRENTLY also locks writes.
Q: Should I test migrations on a staging environment?
A: Yes, but staging is not a substitute for testing against a production data copy. Staging often has less data, so lock times will be shorter. Use both: staging for application compatibility, and a local copy for timing and data checks.
Q: What is the best way to add an index to a large table in production?
A: Use an online method: CREATE INDEX CONCURRENTLY in PostgreSQL, or ALTER TABLE ... ADD INDEX ... ALGORITHM=INLACE, LOCK=NONE in MySQL. These avoid blocking writes, but they take longer and cannot run inside a transaction. Test them on a copy first.
Q: Can I automate the entire audit?
A: You can automate most of it: linting, running on a test database, timing, and checking for NULLs. The final review of the migration's intent and rollback plan still needs a human. Automate the mechanical checks, and keep a human for the judgment calls.
Q: What should I do if a migration has already been applied in production and is bad?
A: Do not panic. If it is a schema change, you can often revert it with a reverse migration. If it is a data change, restore from a backup or write a corrective migration. The key is to have a rollback plan before you run any migration in production.