Database & DevOpsJuly 26, 20267 min read

Zero-Downtime Database Migrations: The Expand and Contract Pattern in Production

Nguyen Dai Long

Nguyen Dai Long

Backend Lead & Software Engineer

In continuous deployment environments, taking down the entire website for scheduled maintenance during database migrations is unacceptable. However, naive schema migrations (like dropping columns or adding non-null columns without defaults) lock tables and cause immediate 500 errors. The Expand and Contract pattern solves this by ensuring backwards compatibility across rolling deployments.

1. The 5 Phases of Expand and Contract

Phase 1 (Expand): Add the new column as nullable. Phase 2 (Dual-Write): Update code to write to both old and new columns while reading from the old. Phase 3 (Backfill): Run an async background migration to populate historic rows. Phase 4 (Switch): Update code to read and write exclusively to the new column. Phase 5 (Contract): Safely drop the old column.

Key Implementation Takeaways:

  • Never rename a column in a single migration step in production.
  • Always add new columns as NULLable or with safe default values.
  • Backfill massive datasets in bounded batches using primary key ranges to avoid lock contention.

Summary & Final Thoughts

Following the Expand and Contract pattern guarantees zero downtime and smooth rollbacks across continuous integration deployments.

Engineering Feedback0 likes

Was this technical breakdown helpful for your production workflow?

Nguyen Dai Long

Written by Nguyen Dai Long

Backend Engineer & Backend Lead with 4+ years of hands-on experience building production systems, RESTful APIs, and cloud infrastructure using Python (Django), Laravel, PostgreSQL, and Google Cloud Platform.

Technical Discussion0

Ask questions, challenge architectures, or share your own production insights.

Join the Technical Community Discussion

Sign in via GitHub or Google in 5 seconds to comment, exchange architecture insights, and build your engineering presence.

Loading discussion...
NDL Ecosystem

Explore Free Web Tools & Games

View All Tools & Apps