The Migration That Locked the Table
The migration ran in 400 ms on staging. Why did production stop taking orders for 11 minutes?
此挑战尚未翻译为简体中文,你正在阅读英文版本。
任务: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;