# Zero-Downtime Database Migrations in Practice

Schema changes under live traffic need expand-and-contract delivery: add compatible shapes first, migrate data and behavior, shift reads with evidence, then contract old paths. Staff engineers treat backfills as restartable operations, assume overlapping app versions, and keep rollback as a traffic switch—not a destructive undo script run at 2 a.m.

Published: 2024-06-05

## Assume deployments and clients overlap

A migration rarely runs in isolation. Old and new application instances serve traffic together, workers replay delayed jobs, mobile clients stay on prior builds for weeks, and edge functions may cache connection settings. Safe migrations design every intermediate state so both code paths remain valid until telemetry proves the old path is cold.

Zero downtime is not zero risk—it is a delivery shape that makes risk observable. Each phase should have a clear success metric, a halt condition, and an owner who can stop the train without guessing which deploy introduced drift.

For Supabase-backed MVPs, Postgres is often the system of record while Expo clients and Cloudflare Workers both talk to the same project. Coordinate migration steps with mobile release cadence and worker deploys so a schema expand does not land before any client can ignore the new column.

Document minimum application versions required for each phase. Support and on-call should read that matrix during incidents instead of inferring compatibility from git history.

Run a short tabletop before the first production expand: list every service that reads or writes the table, every cron that assumes column names, and every analytics export that denormalizes the old shape. Missing one consumer is how migrations succeed in staging yet fail under real traffic because a nightly job still selects the deprecated column.

When multiple teams share one database, publish a migration calendar and freeze unrelated DDL during backfill weeks. Concurrent schema changes multiply lock contention and make attribution harder when p95 latency spikes.

## Expand without changing meaning

Add nullable columns, parallel tables, indexes, or API fields that existing code can ignore. Avoid NOT NULL defaults on large tables without measuring rewrite cost, lock duration, and replication lag on managed Postgres. Build indexes concurrently when the engine supports it and monitor progress instead of assuming instant completion.

Deploy application code that can write both representations—or populate the new model for newly created rows only—before you depend on the new shape for reads. Dual writes introduce consistency risk; bound the window, instrument divergence counts, and prefer a single transaction when both records live in one database.

| Phase | Schema | Application | User impact |
| --- | --- | --- | --- |
| Expand | Add nullable column / table | Old code ignores | None if nullable |
| Dual write | Same | New code writes both | Slight write latency |
| Backfill | Same | Job fills historical rows | Throttled load |
| Read switch | Same | Reads new column | Watch error rate |
| Contract | Drop old column | Old code gone | Irreversible |

Measure table size and lock behavior in staging that mirrors production storage, not empty dev databases. Migration commands should be idempotent and safe to retry after partial failure.

Renaming columns or changing types without an expand path is a common foot-gun: ORMs and raw SQL in workers may cache prepared statements or assume stable names. Prefer additive renames—new column, backfill, read switch, then drop the old name—rather than in-place ALTER that blocks writers.

For foreign keys and check constraints added during expand, validate that backfill order respects dependency graphs. Circular references may require nullable intermediate states or deferred constraint checks that you document explicitly in the runbook.

## Treat backfill as a production operation

A backfill is a workload with checkpoints, not a one-off script on a laptop. Process deterministic batches keyed by primary key or monotonic cursor, persist progress, limit concurrency, and expose metrics: rows processed, lag behind live writes, error rate, and estimated completion. Operators must be able to pause under load without corrupting data.

Validate continuously during the backfill. Compare row counts, checksum samples, and domain invariants rather than waiting for a final banner. If the migration transforms meaning, encode the mapping in executable checks reviewed by domain owners.

Schedule backfills away from peak unless business constraints forbid it. Throttle when replication lag or p95 query latency crosses SLO. Supabase and other managed Postgres tiers still punish heavy updates with IO credit burn.

Never run unbounded updates from CI or local shells against production without the same guardrails you would require for a deploy. The backfill job belongs in your runbook with on-call ownership.

Idempotency keys on backfill batches prevent double-application when a worker retries after a timeout. Store the last successful primary-key cursor in a small control table or object store so restarts continue forward instead of reprocessing hot ranges that already match the target shape.

## Move reads deliberately behind flags

When new writes and historical data are ready, shift reads behind a feature flag, cohort percentage, or internal-only path first. Shadow reads compare old and new query results without changing the user-visible response; log mismatches with enough context to debug schema or code bugs without logging sensitive fields.

Segment errors and latency by read path so the decision to advance is evidence-based. A green staging test does not prove Monday traffic matches your shadow sample—watch production for at least one full business cycle when the column is user-visible.

Rollback during read-switch should usually mean flipping traffic back to the old path, not running destructive DDL. Dropping columns under panic turns a recoverable deployment into a restore-from-backup event. Keep expanded schema until overlapping application versions and queued jobs have drained.

Mobile clients complicate read switches: cached responses and offline stores may serve stale shapes. Version API responses or enforce minimum client builds when read semantics change materially.

## Contract only after evidence

Stop writing the old representation, confirm through metrics that nothing reads the deprecated column or table, then remove unused application code in a separate deploy from the DDL drop. Dropping schema in the same release as code removal removes your safety net if rollback is needed.

Wait for overlapping worker and mobile versions to clear—or accept that old clients will error and document that as a forced upgrade. Telemetry should show near-zero reads of deprecated fields for a defined window before contract.

Contract phases belong on the calendar like feature work. Teams that skip contract accumulate ghost columns and temporary dual-write paths that become permanent complexity.

For multi-tenant SaaS on Postgres row-level security, verify policies still reference correct columns after contract. A policy that silently fails open or closed is worse than a hard migration error.

## Supabase and managed Postgres constraints

Managed Postgres simplifies operations but does not remove migration physics. Use migration files in git, review lock-prone statements in PR, and prefer online-friendly patterns: concurrent indexes, additive changes first, and avoid long transactions that block autovacuum.

Supabase connection poolers and edge functions may hold connections differently from long-lived app servers. Test migrations against the same pool mode you use in production.

Edge functions and Cloudflare Workers should not embed migration logic; they consume schema the migration pipeline already promoted. Keep DDL out of request paths so a hot code path never becomes accidental schema admin.

When using Supabase Auth alongside app tables, coordinate foreign key and RLS changes with auth triggers. Identity migrations are user-visible failures even when the database migration succeeded on paper.

Local supabase db reset flows are fine for developers, but production promotion should always replay the same ordered migration files CI applied. Drift between environments is a leading cause of works-in-preview-locks-in-prod surprises when row counts differ by orders of magnitude.

## Observability and rollback that match reality

Instrument each migration phase: dual-write mismatch rate, backfill lag, read-path error ratio, and replication lag. Dashboards should link to the migration ticket and the engineer on call for the job—not only generic database CPU graphs.

Rollback artifacts are traffic switches and feature flags, plus documented SQL to pause backfills. Full restore from snapshot remains the last resort; practice time-to-restore so leadership knows the cost of skipping expand-and-contract discipline.

Run game days for bad deploy during backfill: pause job, revert read flag, verify old path still serves. Postmortems should cite which phase was active and whether contract happened too early.

Pair migration work with API versioning when mobile clients consume affected tables through HTTP. Epoch headers and additive JSON fields give clients time to catch up before contract removes server-side fallbacks.

Treat long-running migration jobs like deploys: announce start and end in the team channel, link dashboards, and define who may pause or resume the backfill. Ambiguous ownership during a lag spike is how teams either over-throttle and miss deadlines or under-throttle and hurt production SLOs.

## Operational checklist for zero-downtime migrations

Before expand: size tables, estimate lock time, define success metrics, assign on-call for the backfill job, and confirm staging used production-like volume. Before dual-write: add divergence metrics and alert thresholds. Before read switch: enable shadow reads and review mismatch samples with domain owners.

Before contract: prove near-zero reads of deprecated fields, confirm no workers enqueue old shapes, update RLS policies and documentation, and schedule DDL in a low-traffic window with rollback plan that does not require DROP.

After contract: remove feature flags, delete dead code paths, archive migration runbooks, and note total calendar time—expand-and-contract often takes longer than big-bang but fails less catastrophically.

Freelance MVPs benefit from writing this checklist into the handoff doc: which phases remain, which flags control reads, where checkpoints live, and who owns the next phase gate.

Link migration plans to data retention posts when backfills touch personally identifiable fields—legal basis and deletion paths must stay coherent across schema versions.

Capture lessons in a short postmortem template: phases executed, wall-clock duration, unexpected consumers, and whether contract waited long enough. That history becomes the estimate for the next migration and prevents the team from repeating a rushed read switch under deadline pressure.
