DB Migration Took Production Down — How to Prevent It
A single ALTER TABLE locked production for 20 minutes, costing $100k. Learn proven strategies to safely execute DB migrations with zero downtime.
Twenty Minutes of Silence From a Single ALTER TABLE
A production database goes offline. The support chat fills up. Revenue stops. The cause? A single schema migration that seemed perfectly harmless in staging.
This scenario plays out across the industry with alarming regularity. As the team at Toolshelf puts it, "most migration horror stories start the same way: a seemingly innocent schema change that locks a table for way longer than expected." A straightforward command like ALTER TABLE users ADD COLUMN email_verified BOOLEAN DEFAULT FALSE; on a table with 10 million rows might take 20 minutes and lock the entire table the whole time.
According to industry data cited by Mactores, unplanned downtime costs enterprises more than $5,000 per minute. For a 20-minute outage, that is $100,000 gone — not counting the trust deficit with users who just watched the app go dark.
Put simply: database migrations are the single most dangerous routine operation in any deployment pipeline. Unlike application code, which can be rolled back in seconds, structural database changes often cannot be easily reversed.
Why Migrations Break Production
The problem is rarely the SQL itself. It is everything around it — the deployment strategy, the rollback plan, the performance implications, and the edge cases nobody considered.
Four specific technical causes create most outages:
Table Locks During Schema Changes
When a migration runs an ALTER TABLE on a large table, the database engine may acquire an exclusive lock. As explained in a detailed analysis by Pavan Rangani, for a table with 50 million rows, adding a column with a default value in older PostgreSQL versions rewrites every row while holding an ACCESS EXCLUSIVE lock the entire time. No queries can execute — not even SELECT statements. If that table handles 5,000 queries per second, that means 5,000 failed requests per second for the duration of the migration.
Long-Running Data Transformations
Backfilling data across millions of rows in a single transaction is a recipe for trouble. The database must hold the transaction open, consuming memory, blocking other writes, and risking timeout failures.
Application Incompatibility With New Schema
Deploying application code that expects a new column before that column exists — or removing a column the running application still references — creates instant errors. The window between "migration applied" and "new code deployed" is where things break.
No Rollback Plan
As noted by Teamplify's engineering blog, if a migration fails due to a timeout on a long heavy SQL operation, retrying it again and again automatically only compounds the problem. The deployment should be rolled back immediately after the first failure — but many teams have no rollback path defined.
The Expand-Contract Pattern: The Industry Standard Fix
The most reliable approach for preventing migration downtime is the expand-contract pattern (sometimes called expand-migrate-contract). Multiple authoritative sources — from DeployHQ to C# Corner — identify it as the gold standard for complex schema changes.
The pattern works in three phases:
Phase 1: Expand
Add new schema elements alongside existing ones. Both old and new structures coexist. The running application continues using the old structure without any changes.
For example, instead of renaming user_name to username directly (which DeployHQ calls the "Wrong Way"), add a new username column while keeping user_name intact. This operation is typically non-blocking.
Phase 2: Migrate
Update application code to write to both old and new columns. Backfill existing data from the old column to the new one. The backfill runs in small batches — not as one massive query.
Real numbers: instead of updating 50 million rows in one shot, process them in batches of 100,000. Each batch completes in seconds, releases its locks, and lets normal traffic flow between batches. As recommended by C# Corner: run UPDATE users SET status='active' LIMIT 1000; in loops instead of one big query.
Phase 3: Contract
Once all application instances read from the new column and data is fully migrated, remove the old column in a subsequent deployment. This final cleanup happens days or even weeks later, after confirming everything works.
Honest take: this approach requires discipline. Every schema change needs to be planned across multiple deployments. It is slower. It is more work. But it is the difference between a smooth Tuesday afternoon and a 20-minute outage that makes the whole team sweat.
Five Concrete Rules That Prevent Migration Downtime
In our experience with 30+ projects involving production databases, these five rules catch the vast majority of issues before they reach production.
Rule 1: Every Migration Must Be Backward Compatible
This is the golden rule, as DeployHQ states clearly: every migration must be backward compatible with the currently running application code. If the current app version would break after the migration runs, the migration is not safe.
What this means for your project: before writing any migration, ask one question — "Can the current production code still work after this migration runs?" If the answer is no, break it into smaller steps.
Rule 2: Never Run Migrations as Part of Application Startup
The Teamplify engineering team explicitly warns against patterns like <run-db-migrations> && <launch-the-app>. The migration script must handle parallel executions correctly, detect if another migration is already in progress, and avoid automatic retries on failure.
Here is what we recommend: run migrations as a separate, explicit step in the deployment pipeline. One execution. If it fails, roll back the deployment — do not retry blindly.
Rule 3: Use Non-Blocking DDL Operations
PostgreSQL's CREATE INDEX CONCURRENTLY builds indexes without locking the table for writes. But as Toolshelf notes, it is not foolproof — it can fail midway through, leaving an invalid index that requires manual cleanup. Always check for invalid indexes after a concurrent build.
For MySQL, tools like pt-online-schema-change and gh-ost perform schema changes by creating a shadow table and swapping it in, avoiding long locks on the original table.
Rule 4: Batch All Data Migrations
Any migration that touches existing rows — backfills, data transformations, type conversions — must run in batches. A single UPDATE on millions of rows holds a transaction open for the entire duration, blocking other operations and risking timeouts.
Real numbers: a batch size of 1,000 to 10,000 rows with a short sleep between batches (50–100ms) keeps the database responsive. The total migration takes longer, but the application stays available throughout.
Rule 5: Test Migrations Against Production-Size Data
A migration that completes in 200ms on a dev database with 500 rows can take 20 minutes on a production table with 10 million rows. Always test against a dataset that matches production in both size and shape.
High-Risk Migrations and How to Handle Each
Not all migrations carry equal risk. Here is a breakdown of the most dangerous operations and the safe alternative for each.
Dropping Columns or Tables
Dangerous approach: Drop the column in the same deployment that removes it from the application code. If the deployment rolls back, the app expects a column that no longer exists.
Safe approach: First deploy application code that no longer reads from the column. Wait for all instances to update. Then drop the column in a separate migration days later.
Renaming Columns
Dangerous approach: ALTER TABLE users RENAME COLUMN user_name TO username; — instantly breaks every query referencing the old name.
Safe approach: Add the new column, set up a sync trigger or dual-write in the application, backfill existing data in batches, switch reads to the new column, then drop the old column.
Changing Data Types
Dangerous approach: ALTER TABLE orders ALTER COLUMN amount TYPE NUMERIC(10,2); — rewrites the entire table with an exclusive lock.
Safe approach: Add a new column with the target type, backfill in batches, switch the application to the new column, drop the old one.
Adding Indexes on Large Tables
Dangerous approach: CREATE INDEX idx_users_email ON users(email); — locks the table for the entire build duration.
Safe approach: CREATE INDEX CONCURRENTLY idx_users_email ON users(email); — builds the index without blocking writes. Monitor for completion and check for invalid indexes afterward.
Advanced Strategies for Large-Scale Migrations
For teams running databases with hundreds of millions of rows or handling thousands of queries per second, the expand-contract pattern alone may not be enough.
Change Data Capture (CDC)
As described by Mactores, Change Data Capture uses the database's write-ahead log to replicate data incrementally in near-real-time. This keeps source and target in sync until the team is ready for a final cutover measured in minutes rather than hours.
The Beefed.ai analysis notes that log-based CDC captures row-level changes with minimal CPU overhead and supports deletes and updates. The typical downtime target with CDC plus logical replication is near-zero — measured in seconds.
Blue-Green Database Deployments
The concept mirrors blue-green application deployments: prepare a replica database, apply migrations to the replica, synchronize data in real-time, then switch traffic. As outlined by Dev.to, the steps are: prepare the green database as a replica, apply migrations to it, implement real-time data synchronization, and finally update connection strings to point to the green database.
This approach adds infrastructure complexity but provides a clean rollback path — if anything goes wrong, switch back to the original database.
Key takeaway for business: blue-green database setups roughly double infrastructure cost during migration windows. For most small-to-mid projects, the expand-contract pattern delivers zero downtime without the extra infrastructure spend.
A Migration Checklist for Every Deployment
Before any migration reaches production:
- Is it backward compatible? Can the current running code survive this change?
- Is it non-blocking? Does it avoid exclusive locks on high-traffic tables?
- Is data migration batched? No single transaction touching more than 10,000 rows.
- Has it been tested on production-size data? Measure actual execution time.
- Is there a rollback plan? What happens if this migration fails halfway?
- Is the application deploy decoupled? Migration runs separately from code deployment.
- Is monitoring in place? Alerts for lock wait times, query latency, error rates during the migration window.
Key Takeaway for Business
Database migrations do not have to be scary. The 20-minute production outage is entirely preventable with three disciplines:
First, adopt the expand-contract pattern. It requires more deployments per feature, but each deployment is safe and reversible. The extra planning cost is a fraction of what a single outage costs in revenue and trust.
Second, decouple migrations from application deployments. Run them as a separate, monitored step. Never retry automatically on failure.
Third, batch everything. No single migration should lock a table long enough for users to notice. If a migration takes more than a few seconds, break it into smaller pieces.
Honest take: zero-downtime migrations are not technically difficult. They are organizationally difficult. They require every developer on the team to think about backward compatibility before writing the first line of migration SQL. That discipline — more than any tool or framework — is what separates teams that deploy confidently from teams that deploy with crossed fingers.
Frequently Asked Questions
How do you prevent downtime when adding a new column to a production database?
Add the column without a default value first (this is typically instant in modern PostgreSQL). Then backfill the default in batches using UPDATE ... WHERE id BETWEEN X AND Y. Finally, set the column default for future rows. This avoids the full table rewrite that causes locks.
How do you safely remove a column from production without causing downtime?
Deploy application code that no longer references the column first. Wait until all application instances are running the new code. Then drop the column in a separate migration. This two-step approach ensures no running code ever references a missing column.
What is the expand-contract pattern and why does it prevent downtime?
It splits every breaking schema change into three safe steps: expand (add new structures alongside old), migrate (copy data and switch application code), and contract (remove old structures). At every step, both old and new application versions can work with the database, so there is no moment where the schema and code are incompatible.
How should you coordinate application deployments with database schema changes?
Run the database migration as a separate step before deploying new application code. The migration must be backward compatible — meaning the currently running application version continues to work after the migration. Only after the migration succeeds should the new application code be deployed.
How do you maintain data consistency during a zero-downtime migration?
Use dual writes or database triggers to keep old and new columns in sync during the transition period. Backfill existing data in batches. Verify row counts and data integrity before switching reads to the new structure. Only remove the old structure after confirming full consistency.
This article is based on publicly available sources and may contain inaccuracies.


