Database schema changes are inevitable. Applications evolve, requirements shift, and data models need to adapt. The challenge is making these changes while keeping your application running—no maintenance windows, no "we'll be back soon" pages, and no data loss.
This article covers practical strategies for database migrations that work in production environments with active traffic. We'll focus on the expand-contract pattern, backward-compatible changes, feature flags, and rollback plans that actually work when something goes wrong at 2 AM.
The expand-contract pattern
The expand-contract pattern (also called the parallel change pattern) is the foundation of zero-downtime database migrations. Instead of changing a schema in one risky deployment, you break it into three safe phases:
- Expand: Add new schema elements (columns, tables, indexes) alongside existing ones
- Migrate: Dual-write to both old and new schema while gradually reading from new
- Contract: Remove old schema elements once fully migrated
Each phase can be deployed independently, tested in production, and rolled back if needed. This is slower than a single migration script, but it's proven in systems that can't afford downtime.
Example: Renaming a column
Let's say you need to rename user_name to username in a users table with millions of rows.
Here's how to do it safely:
Phase 1: Expand (Deploy 1)
-- Add new column
ALTER TABLE users ADD COLUMN username VARCHAR(255);
-- Create index (if needed)
CREATE INDEX idx_users_username ON users(username);
-- Backfill existing data (run in batches to avoid locks)
UPDATE users SET username = user_name WHERE username IS NULL LIMIT 1000;
Phase 2: Migrate (Deploy 2)
Update application code to dual-write:
// Write to both columns
async function updateUser(userId, newUsername) {
await db.query(
'UPDATE users SET user_name = $1, username = $1 WHERE id = $2',
[newUsername, userId]
);
}
// Read from new column, fall back to old
async function getUser(userId) {
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
return {
...user,
username: user.username || user.user_name // Fallback during migration
};
}
Phase 3: Contract (Deploy 3)
Once all data is migrated and tested:
-- Remove old column
ALTER TABLE users DROP COLUMN user_name;
Each phase can be deployed days or weeks apart. If Phase 2 has issues, you roll back the code change without touching the database. If Phase 3 reveals problems, you still have the old column and can switch back.
Backward-compatible schema changes
Some schema changes are naturally backward-compatible and don't require expand-contract. These can be deployed directly before or after code changes:
Safe to deploy first (before code):
- Adding a new nullable column
- Adding a new table
- Adding an index
- Adding a check constraint that existing data satisfies
- Creating a new foreign key (if referential integrity already exists)
Safe to deploy last (after code):
- Dropping a column no longer referenced
- Dropping a table no longer used
- Dropping an index
- Relaxing a constraint
Requires expand-contract:
- Renaming columns or tables
- Changing column types
- Adding non-null columns
- Splitting or merging tables
- Changing foreign key relationships
Handling data backfills
Large data migrations can lock tables and block writes. Run backfills in small batches with delays between them:
-- Bad: Locks table for minutes
UPDATE users SET username = user_name WHERE username IS NULL;
-- Good: Processes in batches
DO $$
DECLARE
batch_size INT := 1000;
rows_updated INT;
BEGIN
LOOP
UPDATE users
SET username = user_name
WHERE id IN (
SELECT id FROM users
WHERE username IS NULL
LIMIT batch_size
);
GET DIAGNOSTICS rows_updated = ROW_COUNT;
EXIT WHEN rows_updated = 0;
-- Delay between batches to avoid overwhelming database
PERFORM pg_sleep(0.1);
END LOOP;
END $$;
For very large tables (billions of rows), consider online migration tools like pg_repack for PostgreSQL
or gh-ost for MySQL that can rebuild tables without blocking writes.
Using feature flags for migrations
Feature flags let you deploy migration code to production without activating it immediately. This separates deployment risk from migration risk:
async function getUser(userId) {
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
// Feature flag controls which column to use
if (await featureFlags.isEnabled('use-new-username-column')) {
return { ...user, username: user.username };
} else {
return { ...user, username: user.user_name };
}
}
Roll out the flag gradually: 1% of traffic, then 10%, then 50%, then 100%. If issues appear, disable the flag instantly without redeploying code. Once the flag is at 100% for a week, remove it and the old code path.
Testing migrations before production
Test migrations on production-like data and load:
- Staging environment: Clone a recent production database snapshot and run the full migration sequence
- Load testing: Apply production-level traffic during migration to catch locking issues
- Timing estimates: Measure how long each phase takes on production-sized data
- Rollback testing: Verify you can roll back each phase successfully
For critical migrations, run a "dark launch" where you dual-write and read from both schemas for a week, comparing results to verify consistency before switching reads to the new schema.
Rollback strategies that work
Every migration needs a rollback plan. Here's what works:
Code rollback
During the migrate phase, rolling back code should be safe because both old and new schemas exist. Test rollbacks in staging to verify.
Data rollback
If you've written new data to the new schema that the old code doesn't handle, you can't roll back code without data loss. Options:
- Keep old schema populated: Continue dual-writing to old schema until contract phase
- Reverse migration: Backfill from new schema to old schema if rollback is needed
- Feature flag: Switch back to old code path without redeploying
Rollback decision checklist
When issues appear during migration:
- Is production serving traffic correctly right now? (If yes, don't panic)
- Can you roll back code safely? (Check if old code can handle current data)
- Is this a code bug or a data consistency issue? (Code bugs rollback, data issues need fixes)
- Do you have backups? (Always verify backup before contract phase)
Common migration pitfalls
Forgetting to add indexes before querying
Add indexes in the expand phase, not when you switch reads to the new schema. Otherwise, your first production query will be a table scan.
Locking tables during peak hours
Run migrations during low-traffic hours, or use online migration tools. In PostgreSQL, avoid ALTER TABLE
operations that require ACCESS EXCLUSIVE locks during peak traffic.
Skipping the migrate phase
Don't go straight from expand to contract. The migrate phase is where you validate the new schema under production load while keeping the ability to roll back.
No migration monitoring
Add metrics for migration progress: percentage of rows migrated, error rates, query performance on new schema. Alert when error rates spike or queries slow down.
Key takeaways
- Use the expand-contract pattern for risky migrations: add new schema, migrate data and code, remove old schema
- Deploy each phase independently with time between them to validate in production before proceeding
- Feature flags let you deploy migration code without activating it, separating deployment risk from migration risk
- Test migrations on production-sized data and load—staging catches locking issues that unit tests miss
- Every migration needs a documented rollback plan tested before production deployment
Published by the DSSS Engineering Team. For corrections or topic requests, use the contact page.