Course contentsShow
← Databases & SQL
Lesson 1746 of 1,95316. Distributed Data ArchitecturesFree lesson

Handling Schema Drift

Version schema changes to support multiple application code versions during rolling deployments.

In this lesson, you will learn how to manage schema transitions during rolling deployments to ensure your database remains compatible with both old and new application code simultaneously.

The Challenge of Rolling Deployments

When you update a distributed system, you rarely flip a switch to update every node at once. Instead, you perform a rolling deployment, where some instances run v1 of your code while others have already been upgraded to v2. If v2 introduces a database schema change—like renaming a column or splitting a table—the v1 instances will immediately crash if they attempt to write to the new schema.

Handling schema drift requires an Expand-Contract (or Parallel Change) pattern, where you treat the database migration as a multi-step process that spans multiple deployment cycles.

The Expand-Contract Strategy

To avoid downtime or errors during a rolling update, never execute a destructive change (like dropping a column) in a single step. Follow this progression:

  1. Expand: Modify the schema to be additive. If you want to rename user_name to full_name, add a new column full_name while keeping user_name.
  2. Dual Write: Update your application code so that v2 writes to both columns, but still reads from user_name (or uses a fallback).
  3. Migrate: Run a background process to backfill the full_name column for existing records.
  4. Cutover: Update the application to read exclusively from full_name.
  5. Contract: Once all instances are running v2 and the user_name column is confirmed to be unused, remove the old column.

By keeping the schema backwards-compatible, your v1 code continues to function while v2 is being phased in.

-- Step 1: Add the new column (Safe for v1 and v2)
ALTER TABLE users ADD COLUMN full_name VARCHAR(255);

-- Step 2: Application v2 writes to both columns
-- UPDATE users SET user_name = 'Alice', full_name = 'Alice' WHERE id = 1;

-- Step 3: Once v2 is fully deployed, remove the legacy column
ALTER TABLE users DROP COLUMN user_name;

This incremental approach prevents "schema drift" from causing outages by ensuring that your database state is always a superset of what your various application versions require.

Key Takeaway: Never execute breaking schema changes in one step; use an Expand-Contract pattern to keep the database backwards-compatible while rolling out code updates.