The Real Fullstack

The Migration That Locked the Table

The migration ran in 400 ms on staging. Why did production stop taking orders for 11 minutes?

Ingénieur senior10 minSimulateur de chronologieDéfi de code
postgresqlflywaysqlkubernetes

Ce défi n'est pas encore traduit en Français. Vous lisez la version anglaise.

Mission:Order the expand / migrate / contract steps so that every running version of the code works at every moment and no step holds a long exclusive lock.Contexte · Objectifs d'apprentissage ▾

Larkspur is replacing orders.customer_id with customer_ref. The first plan dropped the old column, added a NOT NULL constraint and built an index in one release, while pods running the old code were still serving traffic. On a 90-million-row table, writes queued behind the locks.

Mission: Order the expand / migrate / contract steps so that every running version of the code works at every moment and no step holds a long exclusive lock.

Objectifs d'apprentissage

  • Plan schema changes as expand → migrate → contract.
  • Avoid long locks: concurrent index builds, NOT VALID constraints, batched backfills.
  • Coordinate migrations with rolling deployments.
SimulationSimulé
release
11. dropOld ✕ contract last, never drop what running code reads
22. addNullable
33. validateNotNull ✕ constrain once every writer fills it
44. backfill ✕ backfill after new rows are dual-written
55. indexConcurrently
66. deployDualWrite
77. deployReadNew
Lancer la simulation
-- V87 expand (instant: no table rewrite, short lock)ALTER TABLE orders ADD COLUMN customer_ref uuid;-- app v2 writes both customer_id and customer_ref-- V88 backfill in batches (no long transaction)UPDATE orders SET customer_ref = c.ref FROM customers c WHERE orders.customer_id = c.id AND orders.customer_ref IS NULL AND orders.id BETWEEN :from AND :to;-- V89 (no transaction): build without blocking writesCREATE INDEX CONCURRENTLY orders_customer_ref_idx ON orders (customer_ref);-- app v3 reads customer_ref-- V90 constrain without a long exclusive lockALTER TABLE orders ADD CONSTRAINT customer_ref_nn CHECK (customer_ref IS NOT NULL) NOT VALID;ALTER TABLE orders VALIDATE CONSTRAINT customer_ref_nn;-- V91 contractALTER TABLE orders DROP COLUMN customer_id;

Simplification

Seven steps with precedence rules. Lock behaviour differs between databases and versions; always check the documentation for yours. Modèle pédagogique — les chiffres illustrent un comportement, ce ne sont pas des benchmarks.

Concepts

Défis liés

Références