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?

Senior Engineer10 Min.Zeitachsen-SimulatorCode-Aufgabe
postgresqlflywaysqlkubernetes

Diese Aufgabe ist noch nicht auf Deutsch übersetzt. Du liest die englische Version.

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.Kontext · Lernziele ▾

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.

Lernziele

  • Plan schema changes as expand → migrate → contract.
  • Avoid long locks: concurrent index builds, NOT VALID constraints, batched backfills.
  • Coordinate migrations with rolling deployments.
SimulationSimuliert
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
Simulation starten
-- 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;

Vereinfachung

Seven steps with precedence rules. Lock behaviour differs between databases and versions; always check the documentation for yours. Lernmodell – die Zahlen veranschaulichen Verhalten und sind keine Benchmarks.

Konzepte

Verwandte Aufgaben

Referenzen