Agent Wranglers

DAT-23Required

Keep migrations from locking tables

Write migrations that never block a busy table for long. A long lock stops every request that touches it.

How to do it

Set a lock_timeout in PostgreSQL, such as 2 seconds, so a blocked migration fails fast instead of queueing traffic, and retry it later. Build indexes concurrently. Add foreign key and CHECK constraints as NOT VALID, then validate them in a separate transaction. To make a column NOT NULL, validate a CHECK (column IS NOT NULL) first, and PostgreSQL then skips the full scan. From PostgreSQL 18, add CONSTRAINT name NOT NULL column NOT VALID instead, and validate it in a separate step. In MySQL, ask for ALGORITHM=INSTANT or ALGORITHM=INPLACE, LOCK=NONE, so the statement fails instead of silently copying the table. Copy data in batches, not in one statement. A failed concurrent build leaves an invalid index behind, so drop it and retry. Measure the lock time first, as Test migrations on a copy of production data says.

Examples

SQL example

SET lock_timeout = '2s';
ALTER TABLE orders ADD CONSTRAINT orders_total_positive CHECK (total_cents >= 0) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_total_positive;
-- NOT NULL without a long lock: the validated check proves it, so no scan is needed
ALTER TABLE orders ADD CONSTRAINT orders_status_present CHECK (status IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_status_present;
ALTER TABLE orders ALTER COLUMN status SET NOT NULL;
ALTER TABLE orders DROP CONSTRAINT orders_status_present;
-- PostgreSQL: invalid indexes left by failed builds, expect no rows
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;

SQL example 2

-- MySQL: fails at once if the change would copy or lock the table
ALTER TABLE orders ADD COLUMN gift_note varchar(500) NULL, ALGORITHM=INSTANT;
CREATE INDEX orders_customer_created ON orders (customer_id, created_at) ALGORITHM=INPLACE LOCK=NONE;

How to check

Run the migration on a copy under simulated traffic. No request waits longer than the lock timeout, and the invalid index query returns no rows afterwards.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/migrations/lock-safe-migrations">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.