Highlights

Contents

Part VI
06

Schema migrations

We change the shape of tables that are serving live traffic. Most migration outages come not from slow changes but from locks that make every other query wait. We will cover migration tools and how they run in a deploy, DDL locks and the lock queue, building indexes without blocking writes, and which changes are safe on a large PostgreSQL table.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Connections and pools2Queries from code3Inside an ORM4Transactions in code5Concurrency control6Schema migrations7Zero-downtime migrations8Scaling database access9The order write end toend

#Section 19Migration tools and how they run

The database schema changes as the product changes. Wren adds a tip column, an index for a new filter, a table for promotions. A migration is a small, versioned script that moves the schema from one state to the next, and a migration tool applies them in order and remembers which have run. Rails popularized the idea with Active Record migrations in 2005. Flyway, Liquibase, Alembic, Django migrations, golang-migrate and Prisma Migrate all work the same way.

Each migration is a file with a sortable version, such as 0044_add_kitchen_note.sql. The tool keeps a table in the database, often named schema_migrations, with one row per applied version. When it runs, it compares the files to the table and applies the missing ones in order, recording each as it succeeds. The same files run on a laptop, in CI, in staging and in production, so every environment reaches the same schema by the same path.

MIGRATIONS ARE NUMBERED FILES; A TABLE REMEMBERS WHICH RANMIGRATIONS ARE NUMBERED FILES; A TABLE REMEMBERS WHICH RAN0041_create_orders.sql0042_add_tip.sql0043_index_user.sql0044_add_kitchen_note.sql0045_backfill_note.sqlversionapplied_at00412026-09-01 10:0200422026-09-14 09:4000432026-09-30 11:150044pending0045pendingschema_migrationsmigrate: run 0044, then 0045each file runs once, in order, on every environment; never edit a file that already ran
Figure 6.34Files 0044 and 0045 have not run. The migrate step applies them in order and records each.

Three habits keep this reliable. Never edit a migration that has already run anywhere, because environments that applied the old version will never see the new one. Write a new migration instead. Keep each migration small, one logical change, so a failure is easy to understand and to retry. And make migrations safe to run while the old code is still serving traffic, which is the subject of the rest of this part and the next.

Wren runs migrations as a separate step in the deploy pipeline, after the new image is built and before the rollout. A single job runs them, protected by a PostgreSQL advisory lock, so two pipelines started at once cannot apply the same migration twice. Running migrations from every app instance at start-up is a common mistake that turns 20 instances into 20 migrators racing each other.

MIGRATE ONCE, THEN ROLL THE APP OUT INSTANCE BY INSTANCEMIGRATE ONCE, THEN ROLL THE APP OUT INSTANCE BY INSTANCEbuildimage v42migrateone job, one lockroll out4 instancesadvisory lock: only onemigrator at a timev41 → v42, one at a timefor a while old and new code run together against the new schema; both must work
Figure 6.35Build, migrate once under a lock, then roll the instances out one by one.

During the rollout, instances running v41 and v42 serve traffic side by side for several minutes. The migrated schema must therefore work for both versions, which rules out many changes that look harmless.

Down migrations, scripts that undo a change, exist in most tools. Wren writes them for development but rarely runs them in production. Rolling back a schema that has already accepted new data can destroy that data. The safer pattern is to roll forward with a new migration.

#Section 20DDL locks and the lock queue

Schema changes are DDL statements, data definition language, such as ALTER TABLE, CREATE INDEX and DROP COLUMN. Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock on the table, the strongest lock PostgreSQL has, which conflicts with every other lock, including the light ACCESS SHARE lock that a plain SELECT takes. Adding a nullable column only needs the lock for a millisecond to update the catalog. The danger is not how long it holds the lock. The danger is how long it waits to get it.

Picture Wren at peak. An analyst’s report has been running a SELECT on orders for 30 s, holding ACCESS SHARE. The deploy runs ALTER TABLE orders ADD COLUMN kitchen_note text. The ALTER needs ACCESS EXCLUSIVE, which conflicts with the analyst’s lock, so it waits. PostgreSQL’s lock queue is first come, first served, so every new query on orders, even a simple SELECT, must now wait behind the ALTER, since its lock would conflict with the ALTER’s pending request.

ONE ALTER TABLE WAITING AT THE DOOR BLOCKS EVERYONE BEHIND ITONE ALTER TABLE WAITING AT THE DOOR BLOCKS EVERYONE BEHIND ITorders tableanalytics SELECTrunning 30 sALTER TABLEwants exclusive0.2 s: all 40 pool connections stuck30 s: 6,000 queries queued, users see errorsthe lock queue is first come, first served; new readers line up behind the waiting ALTER
Figure 6.36The ALTER waits at the door behind one long query, and every later query queues behind the ALTER.

The arithmetic is brutal. Wren sends roughly 200 queries per second to orders at peak. All 40 pooled connections are stuck within 40 ÷ 200 = 0.2 s, and from then on requests fail with pool timeouts. If the report takes another 30 s, about 30 × 200 = 6,000 queries pile up or fail. A change that needs a millisecond of locking causes a 30-second outage.

The fix is lock_timeout. Wren’s migrations start with SET lock_timeout = '2s'. If the ALTER cannot get its lock within 2 s, it gives up, the queue behind it drains, and the migration tool retries after a pause. Each attempt causes at most a 2 s stall instead of an unbounded one, and the ALTER eventually lands in a quiet moment, holding its lock for 5 ms.

WITH lock_timeout = 2 S THE ALTER GIVES UP, AND THE QUEUE DRAINSWITH lock_timeout = 2 S THE ALTER GIVES UP, AND THE QUEUE DRAINSALTER attemptsuser queriessecondswait 2 sgive upwait 2 sgot it, 5 msstallnormalstallnormalbounded 2 s stalls instead of a 30 s outage; retry on a schedule until the table is quiet
Figure 6.37Two bounded stalls and one successful attempt, instead of one long outage.

Two more habits help. Run migrations away from peak traffic and long-running jobs, and set statement_timeout on reporting roles so no query holds a lock on a busy table for 30 s in the first place.

#Section 21Building indexes without blocking writes

A plain CREATE INDEX takes a SHARE lock on the table for the whole build. Reads continue, but every INSERT, UPDATE and DELETE waits. On Wren’s 5,000,000-row orders table, an illustrative build time of 40 s means 40 × 50 = 2,000 order writes blocked at peak, and most of those customers see errors. For a large, busy table that is unacceptable.

CREATE INDEX CONCURRENTLY, added in PostgreSQL 8.2 in 2006, builds the index without blocking writes. It works in phases. It registers the new index in the catalog as not yet valid, so new writes start maintaining it. It waits for every transaction that might not have seen that registration to finish. It scans the table and builds the index. It waits again, scans a second time to pick up rows written during the first scan, and finally marks the index valid. Writes flow throughout.

CREATE INDEX BLOCKS WRITES; CONCURRENTLY LETS THEM FLOWCREATE INDEX BLOCKS WRITES; CONCURRENTLY LETS THEM FLOWCREATE INDEX: 40 sbuild, writes blocked2,000 orderwrites waitingCREATE INDEX CONCURRENTLY: longer, but onlinescan 1wait for old txnsscan 2validwrites keep landing during the buildif it fails, it leaves an INVALID index; drop it and try again
Figure 6.38The plain build stops writes for 40 s. The concurrent build takes longer and lets them through.

The price is time and some fragility. A concurrent build reads the table twice and waits for older transactions, so it takes longer, and a long-running transaction anywhere in the database delays it. It cannot run inside a transaction block, which means migration tools that wrap every migration in a transaction need an explicit opt-out for that file. If it fails, for example because a unique index finds a duplicate, it leaves an invalid index behind. The index is maintained on every write but never used for reads, so it costs performance and helps nothing. Wren’s runbook checks for invalid indexes after any failed build, drops them with DROP INDEX CONCURRENTLY, and tries again.

The same idea, doing work in phases so locks are brief, runs through all safe schema changes. MySQL offers online DDL for many operations, and tools such as GitHub’s gh-ost (2016) and Percona’s pt-online-schema-change copy a table in the background and swap it in, for changes the database cannot do online itself.

#Section 22Safe and unsafe changes on a live table

Every proposed migration on a large table answers two questions. Does it rewrite or scan the table while holding a strong lock, and will the code currently running still work after it? Wren’s reviewers sort changes into three groups for PostgreSQL 11 and later.

Safe changes need only a brief catalog lock. Adding a nullable column is instant. Adding a column with a constant default has also been instant since PostgreSQL 11 (2018), which stores the default in the catalog instead of writing it into every row. CREATE INDEX CONCURRENTLY is safe, as the last section showed. Adding a check or foreign key constraint with NOT VALID is instant too, because it applies only to new writes. A later VALIDATE CONSTRAINT checks existing rows under a lighter lock that allows reads and writes.

SORTING SCHEMA CHANGES BY HOW MUCH THEY HURT A LIVE TABLE (POSTGRESQL 11+)SORTING SCHEMA CHANGES BY HOW MUCH THEY HURT A LIVE TABLE (POSTGRESQL 11+)safeadd a nullable columnadd a column with a constant defaultCREATE INDEX CONCURRENTLYadd constraint NOT VALID, then VALIDATEcarefulSET NOT NULL (full scan under lock)add a foreign key (validate separately)drop a column old code still readsrewrite or breakchange a column typeadd a column with a volatile defaultrename a column in use
Figure 6.39Green, amber and red. Most red changes become green when split into steps.

Careful changes are safe only with a technique. SET NOT NULL scans the whole table under ACCESS EXCLUSIVE, unless a validated CHECK (col IS NOT NULL) constraint already exists, in which case PostgreSQL 12 and later skip the scan. Adding a foreign key should use NOT VALID then VALIDATE. Dropping a column is instant for the database but breaks any running code that still selects it, so the code must stop using it first.

Rewrite or break changes need a different approach entirely. Changing a column’s type, say integer to bigint, rewrites the whole table under ACCESS EXCLUSIVE, minutes for 5,000,000 rows. Adding a column with a volatile default such as clock_timestamp() rewrites too. Renaming a column is instant for the database and instantly breaks every running instance that uses the old name.

Every item in the red group has a safe path, and it is always the same shape. Add the new thing beside the old one, move the data and the code across in small steps, and remove the old thing when nothing uses it. Part VII walks through it.