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?

シニアエンジニア10 分タイムラインシミュレーターコード課題
postgresqlflywaysqlkubernetes

この課題はまだ日本語に翻訳されていません。英語版を表示しています。

ミッション: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.背景 · 学習目標 ▾

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.

ミッション: 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.

学習目標

  • Plan schema changes as expand → migrate → contract.
  • Avoid long locks: concurrent index builds, NOT VALID constraints, batched backfills.
  • Coordinate migrations with rolling deployments.
シミュレーションシミュレーション値
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
シミュレーションを実行
-- 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;

簡略化

Seven steps with precedence rules. Lock behaviour differs between databases and versions; always check the documentation for yours. 教育用モデルです。数値は挙動を示すためのもので、ベンチマークではありません。

コンセプト

関連する課題

参考資料