3.5 Hours

10. Schema Migration: Evolving Databases Without Downtime

Migration

Schema migration is the process of evolving your database schema over time. It's one of the hardest problems in software engineering. This module covers migration strategies, tools, and best practices for making schema changes safely.

Schemas change as applications evolve. New features require new tables, columns, and constraints. Changing a schema without downtime is challenging. This module covers strategies like zero-downtime migrations, rollback plans, and handling large tables.

Migration Strategies

The expand-and-contract pattern is the safest: 1) Add the new column with a default, 2) Backfill data, 3) Deploy code that uses the new column, 4) Remove the old column. This allows for rollback at any step.

StepActionSQLState
1. ExpandAdd new columnALTER TABLE users ADD COLUMN full_name TEXTname + full_name both exist
2. BackfillCopy dataUPDATE users SET full_name = namefull_name populated
3. SwitchDeploy new codeApplication uses full_nameOld code no longer used
4. ContractRemove old columnALTER TABLE users DROP COLUMN nameOnly full_name remains
SQL
-- Step 1: Add new column
ALTER TABLE users ADD COLUMN full_name TEXT;

-- Step 2: Backfill data
UPDATE users SET full_name = name;

-- Step 3: Deploy code that uses full_name

-- Step 4: Remove old column
ALTER TABLE users DROP COLUMN name;

Handling Large Tables

Large tables make migrations harder. Operations like adding columns, creating indexes, or altering data types can lock tables for hours. Use online DDL tools to avoid downtime.

  • Concurrent Index Creation: Create indexes without locking tables.
  • Online DDL Tools: Use tools like pt-online-schema-change or gh-ost.
  • Batch Operations: Break large updates into batches.
  • Low-Traffic Periods: Schedule migrations during off-peak hours.

Knowledge Check

Ready to test your understanding of 10. Schema Migration: Evolving Databases Without Downtime?

Back