Table of Contents
When your database handles hundreds of transactions per second, running an innocent `ALTER TABLE ADD COLUMN` or renaming a foreign key can lock table metadata, block incoming queries, exhaust connection pools, and take your entire application down. Here is how we execute zero-downtime database upgrades on AWS PostgreSQL and MySQL.
1. The Perils of In-Place Schema Locks
In PostgreSQL, even lightweight schema commands require an `AccessExclusiveLock`. If a long-running analytics query or active transaction is executing on that table, the migration command queues up behind it—blocking every subsequent read and write query until timeouts bring down your web workers.
2. The Expand and Contract Pattern
We adhere strictly to the 4-phase Expand and Contract methodology:
- Phase 1 (Expand): Introduce the new column/table backwards-compatibly. The application still reads and writes to the legacy format.
- Phase 2 (Dual Write): Deploy application code that writes to both the legacy and the new columns simultaneously.
- Phase 3 (Backfill & Read Switch): Backfill historical data in chunked background batches, verify checksums, and switch reads to the new column.
- Phase 4 (Contract): Remove legacy code writes and safely drop the old column during a calm maintenance window.
3. Dual-Writing Architecture & Worker Queues
Rather than slowing down user-facing HTTP request cycles with synchronous double writes, our backend triggers asynchronous Celery/SQS event tasks to mirror writes to the secondary schema version.
4. Safe Batched Backfilling Without Lock Starvation
Never run a single `UPDATE table SET new_col = old_col;`. On tables with millions of rows, this creates massive write-ahead log (WAL) bloat. Instead, chunk updates into 5,000-row primary key windows with a 100ms sleep between iterations.
5. Verification, Cutover, and Cleanup
Automated verification scripts compare checksum hashes between old and new columns. Once 100% parity is verified, the feature flag flips read operations to the new schema with zero user impact or system downtime.
