Video in progress

Staff 🧪 Testing

In a zero-downtime deploy, how do you use tests to check that database schema changes (expand/contract) are safe?

I check every migration on the assumption that two versions run at the same time: I run the tests of the old code version against the new schema, and I measure the migration for locks and time on data close to the real volume. For breaking changes (dropping or renaming a column) I add linter rules.

📖 Answer

During a rolling deploy, for several minutes old and new pods write to the same database. The migration runs first, so the old code must be able to work with the new schema. If you rename a column in a single migration, the old pods crash immediately.

The expand/contract order: a new column is added (expand) → the code writes to both → the data is copied → the code reads only the new one → in the next release the old column is dropped (contract).

The tests:

  1. Old code + new schema. In CI: take the code at the previous release tag and run its integration tests against a database with the new migrations applied. If they fail, the migration isn't backward compatible. This is simple, but rarely done and very effective.

  2. A migration linter. Statically detect risky operations: DROP COLUMN / RENAME on columns in use, CREATE INDEX without CONCURRENTLY on a big table in PostgreSQL, adding NOT NULL with a default value (depending on the version it rewrites the table). Tools like Squawk, or your own rules.

  3. Volume and lock testing. Run the migration with synthetic data close to the prod volume and watch the time and pg_locks. An ALTER TABLE that took 1 ms on a 10-row test database can block a table for several minutes at 50 million rows. A lock_timeout setting protects a migration from waiting too long; have the test check that too.

  4. The rollback path. If a release is rolled back, can the old code work on the new schema? That's the same question as point 1, so no separate test is needed.

These tests are expensive, so not all of them run on every PR: the linter on every PR, the old-code test on PRs where a migration file changed, the volume test nightly or on a release candidate.