Back to articles
Database Migrations in Production: Zero-Downtime Schema Changes
How-ToDevOps

Database Migrations in Production: Zero-Downtime Schema Changes

via Dev.to DevOpsYoung Gao

Database Migrations in Production: Zero-Downtime Schema Changes You deploy a migration that adds a NOT NULL column. The old code is still running. Every INSERT fails. Your API returns 500s for 3 minutes until the new code deploys. The Expand-Contract Pattern Never make breaking schema changes in one step. Instead: Expand : Add the new column as NULLABLE (or with a default) Migrate code : Deploy code that writes to both old and new columns Backfill : Populate existing rows in batches Contract : Remove old column, add NOT NULL constraint Safe Migration Examples Adding a Column ALTER TABLE users ADD COLUMN phone TEXT ; UPDATE users SET phone = legacy_phone WHERE phone IS NULL AND id BETWEEN 1 AND 10000 ; ALTER TABLE users ALTER COLUMN phone SET NOT NULL ; Renaming a Column Never rename directly. Instead: add new column, dual-write, backfill, switch reads, drop old column. Four deploys, zero downtime. Dangerous Operations These lock tables and block queries on large tables: Adding index wi

Continue reading on Dev.to DevOps

Opens in a new tab

Read Full Article
6 views

Related Articles