Most database migration failures happen because we try to move too fast.
A developer needs to change a schema, update the application code, and backfill existing rows. To save time, they bundle everything into a single deployment step: the migration alters the column, the new app code deploys immediately after, and an update script runs against the live database.
In production environments running rolling updates, Kubernetes pods, or serverless instances, this single-step approach breaks. While the deployment rolls out, version 1 of your application (which expects the old schema) and version 2 (which expects the new schema) run at the same time. If version 2 immediately renames or drops a column, version 1 crashes. If the data backfill locks a massive table, the entire API hangs.
The result is usually a 2 AM emergency rollback and a corrupted or half-migrated database.
To achieve zero downtime, database migrations must be decoupled from code deployments using a structured design pattern.
The Solution: Expand and Contract
The Expand-and-Contract pattern (also known as Parallel Change) breaks schema changes into incremental, backward-compatible steps. The fundamental rule is simple: old and new versions of your application must always be able to run simultaneously without error.
Instead of executing a schema change in one deployment, you break it into three distinct phases.
1. The Expand Phase
First, modify the database schema by adding new columns or tables alongside the old ones. Do not delete, rename, or add NOT NULL constraints without default values to existing fields yet.
-- Step 1: Expand
-- Add the new column, keeping it nullable so old application writes don't fail.
ALTER TABLE users ADD COLUMN full_name VARCHAR(255);
At this stage, existing application instances continue writing to and reading from first_name and last_name. The database update is completely invisible to live traffic.
2. Dual-Writing and Data Backfilling
Next, deploy application code that writes to both the old and new columns whenever a record is updated or created.
Once dual-writing is live, backfill historical records. Never run a single massive UPDATE statement on a large table in production, as this causes heavy lock contention. Instead, process data in small background batches.
# Step 2: Batch Backfill Script
import time
def backfill_full_name(batch_size=1000):
while True:
# Update records in small chunks to avoid locking the database table
query = """
WITH target_rows AS (
SELECT id FROM users
WHERE full_name IS NULL
LIMIT :batch_size
)
UPDATE users
SET full_name = CONCAT(first_name, ' ', last_name)
FROM target_rows
WHERE users.id = target_rows.id;
"""
result = db.execute(query, {"batch_size": batch_size})
# Stop when no remaining rows need backfilling
if result.rowcount == 0:
break
time.sleep(0.1) # Throttle backfill to keep I/O low
3. The Switch and Contract Phase
Once all historical data is backfilled and both fields remain in sync:
- Deploy a new version of the application that reads directly from the new
full_namecolumn while continuing to write to both (or just the new column). - Verify that old instances of the application are fully decommissioned.
- Remove references to the old columns from the application codebase entirely.
- Execute the final cleanup migration to drop the old fields.
-- Step 3: Contract
-- Safe to execute only after no active code touches these columns.
ALTER TABLE users DROP COLUMN first_name;
ALTER TABLE users DROP COLUMN last_name;
Separate Migrations from Application Startup
Another common operational mistake is executing database migrations directly inside the application startup command (e.g., inside a Docker container's ENTRYPOINT or CMD).
When scaling services horizontally across multiple containers or instances, every container booting at the same time attempts to execute schema changes simultaneously. This leads to race conditions, deadlocks, and failed container boots.
Instead, execute migrations as a dedicated, single-execution pipeline step in your CI/CD process before deploying new application containers. This ensures schema adjustments occur sequentially in a controlled environment.
By combining the expand-and-contract pattern with isolated CI/CD deployment steps, schema changes transform from high-risk production events into routine background updates.
About Me
Tanmay builds AI agents and automation for businesses and is open to freelance projects. Feel free to connect with Tanmay on LinkedIn.
Top comments (0)