Zero-Downtime Database Migrations: A Safe Release Pattern
A practical expand-and-contract guide to database changes that stay compatible across app versions, backfills, deployments, and rollbacks.
A database change can be correct and still break production. A new application version may expect a column that has not been added yet; an older instance may keep writing a field that a migration has already removed. When application servers and database changes are deployed separately, the dangerous period is often the transition between versions—not the final schema.
Why database deployments become dangerous
Many migration scripts are written as if the application changes everywhere at once. Real deployments usually involve rolling releases, background workers, delayed jobs, replicas, and rollback procedures. For some time, more than one application version may be running against the same database.
- A new application version reads a column before the migration has created it.
- A migration renames or removes a field while an older application instance still uses it.
- A large backfill holds locks or consumes enough database capacity to affect normal traffic.
- A rollback restores the previous application but cannot restore data already changed by an incompatible migration.
The practical goal is not to make every database operation instant. It is to make each release step compatible with the application versions that might still be running, and to keep each step observable and recoverable.
The expand-and-contract pattern
Expand-and-contract breaks a risky schema change into smaller steps. First, expand the schema so old and new application versions can use it. Then move application behavior and data gradually. Only after the old version and old data path are no longer needed do you contract the schema by removing the obsolete structure.
| Stage | Schema | Application behavior | Safe to proceed when |
|---|---|---|---|
| Expand | Add the new structure; retain the old one. | The application still works with the old structure. | The schema change is available and does not break existing versions. |
| Bridge | Keep both structures. | Deploy code that can work during the transition and keeps required data in sync. | All writers that only know the old structure have been retired. |
| Migrate | Keep both structures. | Backfill existing records and move reads to the new structure. | New reads and writes are verified against the expected data. |
| Contract | Remove the old structure. | Stop using the old field or table. | No deployed code, job, report, or recovery procedure still depends on it. |
Before changing the schema
- Identify every reader and writer: web servers, workers, scheduled jobs, admin tools, reports, data exports, and external consumers.
- Check how releases overlap in your environment, including whether old workers can continue processing queued jobs after a deployment.
- Decide how data will move, how long the backfill may run, and how you will pause or resume it.
- Define what success looks like: for example, the number of records migrated, mismatch rates, error rates, and database load.
- Confirm whether each environment has one database or a fleet of tenant-specific databases. For the latter, plan rollout and verification per database; the multi-tenant isolation guide explains why those isolation choices affect operations.
Phase 1: Expand the schema
Make the smallest additive change first: add a nullable column, a new table, or another structure that existing application code can ignore. Avoid combining this step with a destructive rename or drop. A rename may look like one operation in a migration, but old code still asks for the old name.
An additive change is not automatically risk-free. Adding a constraint, changing a column type, or creating an index can still take substantial time or contend with production traffic, depending on the database and operation. Check the behavior of your actual database version, use its supported low-impact options where appropriate, and test the operation on representative data.
Phase 2: Deploy a bridge version
Deploy application code that can operate while both schema versions exist. For a field replacement, a bridge version might continue reading the old field while writing the old and new fields together. If both writes target the same database transaction, keep them atomic where possible. If they cross systems or transactions, treat partial failure as a real possibility and add a repair or reconciliation strategy.
Do not start a one-time backfill while old-only writers are still active unless you have another mechanism to keep the new field current. An older server could update the old value immediately after that record has been copied. Wait until old-only instances and workers have drained, or use a deliberate synchronization mechanism that covers them.
Phase 3: Backfill existing data
Treat a backfill as a production workload, not as a harmless follow-up script. Process bounded batches, use a stable cursor such as a primary key, make retries safe, and record progress. Limit the rate if the job competes with normal queries. If the transformation is expensive or changes over time, record which transformation version produced each result.
type SourceRow = { id: string; oldValue: string | null };
interface BackfillStore {
fetchBatch(afterId: string | null, limit: number): Promise<SourceRow[]>;
setNewValueIfAbsent(id: string, value: string | null): Promise<void>;
saveCheckpoint(id: string): Promise<void>;
}
function normalize(value: string | null): string | null {
return value === null ? null : value.trim();
}
async function backfill(
store: BackfillStore,
checkpoint: string | null,
batchSize = 500,
): Promise<string | null> {
let cursor = checkpoint;
while (true) {
const rows = await store.fetchBatch(cursor, batchSize);
if (rows.length === 0) return cursor;
for (const row of rows) {
await store.setNewValueIfAbsent(row.id, normalize(row.oldValue));
cursor = row.id;
}
if (cursor !== null) await store.saveCheckpoint(cursor);
}
}This example assumes the store makes setting a missing value safe to repeat. If a live application write has already populated the new field, the backfill should not overwrite it with an older snapshot. In a real implementation, make the conditional write atomic, store the checkpoint durably, and ensure the cursor ordering is stable. If a process stops partway through a batch, rerunning that batch should not corrupt data.
Phase 4: Verify, then switch reads
A completed job does not prove the new data is correct. Compare old and new values where the transformation allows it, inspect nulls and unexpected formats, and check representative records. For a large dataset, use sampled checks alongside aggregate counts or other checks that do not require an expensive full-table comparison.
Move reads to the new structure only after the backfill and ongoing writes have kept it sufficiently current. If practical, use a short period of shadow reads: serve the response from the established source while comparing the new source in the background. Record mismatches, but avoid logging sensitive values. Once verification passes, switch reads gradually or behind a reversible release control.
Phase 5: Stop depending on the old structure
After reads use the new structure, stop writing the old one in a separate application release. Keep the old schema in place while you verify that no deployed code, delayed job, report, or operational script still needs it. This pause between changing application behavior and dropping the old field is what makes many rollbacks possible.
Phase 6: Contract the schema
Remove the old column, table, or index only after the dependency search and production observation show that it is unused. The final cleanup may be scheduled much later than the initial feature release. That delay is often safer than coupling a destructive schema change to the same deployment that first introduces the replacement.
Plan rollback around data, not just code
Rolling back application code does not necessarily undo a data migration. Before switching reads or removing a field, decide what rollback means at each stage. Early in the process, returning to code that reads the old field may be straightforward. After new writes diverge or the old field is dropped, restoring the earlier behavior may require a reverse backfill, a forward fix, or a restore from backup.
| Situation | Potential response | Important limitation |
|---|---|---|
| Bridge release has a code defect. | Roll back to the prior version while the old structure remains. | The prior version must still be compatible with the expanded schema. |
| Backfill is too costly or produces errors. | Pause it, inspect progress, fix the cause, and resume from a safe checkpoint. | Resume is safe only if the operation can be repeated without harmful side effects. |
| New reads reveal incorrect values. | Switch reads back if the old data is still authoritative and current. | Rollback may not help if old and new values have already diverged. |
| Old structure has been dropped. | Use a forward repair or restore data and reconcile changes. | A code rollback alone cannot recreate deleted data. |
Operational safeguards
- Track migration progress, throughput, errors, retries, and database load; alert on sustained degradation rather than only job failure.
- Make the backfill pausable and resumable, with a clear owner and a documented way to stop it safely.
- Set batch sizes and concurrency conservatively, then adjust based on observed impact rather than assuming the largest batch is fastest overall.
- Keep migration operations separate from application startup when they may take a long time or need controlled pacing.
- Test both mixed-version operation and recovery paths, not only the final schema on a clean database.
Common failure modes
- Renaming or dropping a field in the same release that introduces its replacement.
- Backfilling before old application instances and workers can no longer write only the old field.
- Running one large update that creates long locks, heavy replication lag, or a burst of database load.
- Assuming a migration is reversible because the migration framework has a down operation; the reverse operation may not restore changed or deleted data.
- Dropping the old structure as soon as the new screen appears to work, without checking less visible consumers such as exports and scheduled jobs.
When this pattern is unnecessary
Not every change needs a multi-release migration. A small application with a genuinely coordinated outage, a disposable development database, or a change that is fully backward-compatible may use a simpler approach. The key is to make the deployment assumption explicit. If old and new application versions can overlap, or the data change is costly to reverse, separating expansion, migration, and cleanup is usually the safer choice.
A practical release checklist
Before shipping, confirm that the schema change is compatible with currently deployed code; all old-only writers have drained before the backfill; the backfill is bounded, repeatable, and observable; the new data has been checked before reads switch; rollback accounts for data changes; and the old structure will remain until every consumer has stopped using it. For complex applications with multiple services, workers, or data paths, WebMriya’s complex application development capability can help teams plan and deliver these compatibility steps.
Frequently asked questions
Does expand-and-contract require zero downtime?
No. It is a way to make schema and application changes compatible during a rolling release. Whether the service itself has zero downtime also depends on deployment infrastructure and application behavior.
Can I backfill while the application is receiving writes?
Usually, yes, but only after old-only writers have been retired or another synchronization mechanism keeps the new data current. Make the backfill safe to repeat and protect newer live writes from being overwritten.
How long should I wait before dropping the old column?
Wait until no deployed version, worker, report, export, or operational tool depends on it, and you have verified the new path in production. The right interval depends on release cadence and how long delayed work can remain in the system.