IICTPIICTP

Blog / Cloud & Architecture / System Design & Architecture

System Design & ArchitectureNovember 20, 20265 MIN READ

How do you change a database schema without downtime?

Split every breaking schema change into small steps that each work with both the old and the new version of the code. This is often called expand and contract, or parallel change: first add the new structure, then move code and data over, and only remove the old structure once nothing uses it.

In this post
  1. Why does a simple rename break things?
  2. What are the steps of expand and contract?
  3. How do you backfill a large table safely?
  4. Which operations are risky even when compatible?
  5. How do you keep this manageable?
  6. Sources and further reading

Why does a simple rename break things?

During a deployment, old and new versions of the application run at the same time, and a rollback brings the old version back. If you rename a column in one step, whichever version expects the other name fails. Every schema change has to be compatible with the code on both sides of it.

What are the steps of expand and contract?

Expand: add the new column or table, without removing anything. Migrate: deploy code that writes to both old and new, backfill existing rows, then switch reads to the new structure. Contract: once no running code uses the old structure, remove it in a later release. Each step can be deployed and rolled back on its own.

How do you backfill a large table safely?

In small batches, with a pause between them, so the database is not locked or overloaded and replicas keep up. Make the backfill restartable and idempotent, so it can stop and resume without duplicating work, and watch database load while it runs.

Which operations are risky even when compatible?

Some changes lock a table or rewrite it in full, depending on the database and version: adding a column with certain defaults, changing a column type, or building an index without the database’s concurrent option. Check your database’s documentation and test the migration on a copy with production-sized data.

How do you keep this manageable?

Run migrations through a tool that versions them alongside the code, separate schema migrations from application deploys, and keep each migration small. A checklist in code review, asking whether the change works with the previous release, catches most problems before they ship.

Sources and further reading

  1. Ambler, S. and Sadalage, P. Refactoring Databases: Evolutionary Database Design. Addison-Wesley, 2006.
  2. Sato, D. ParallelChange. martinfowler.com, 2014.

Go deeper: CTP™ credential · the TPBOK™ standard · Check your experience

IICTP is an independent technical credentialing body.

Keep reading

← All posts

Where do you stand?

Find the credential that fits the work you do.