The Decisions You Cannot Cheaply Reverse

Migrations Without Downtime

The migration that takes your site down is the instant one, queued behind a long read while holding a lock everything else needs. The locks, the cheap forms, and the pattern that survives a rolling deploy.

A migration that takes twenty minutes is not the one that takes your site down. The one that takes your site down takes four milliseconds. Understanding why is most of the difference between people who have taken an outage and people who have not yet.

The lock, not the duration

ALTER TABLE in Postgres acquires an ACCESS EXCLUSIVE lock unless the documentation says otherwise, and that lock conflicts with everything, including plain reads. Combine subcommands and the strictest lock any of them needs is the one taken. Now the part people miss: a lock request that cannot be granted waits in a queue, and while it waits it blocks everything behind it. So your instant metadata change asks for ACCESS EXCLUSIVE, finds a long-running analytics SELECT holding a conflicting lock, and waits. Every query arriving after it, including ones that only wanted to read, queues behind your migration. Ten seconds later the pool is exhausted and the site is down. Nothing was slow. One statement was in the wrong place in a queue.

Expect the outage to come from a four millisecond change queued behind a long SELECT or a session left idle in transaction, with every subsequent query piling up behind it. Set lock_timeout to a few seconds on every migration and retry rather than wait. A migration that fails fast is an inconvenience. A migration that waits patiently is an outage.

What is actually cheap

Postgres has quietly made most routine changes free, and fearing the safe ones is how teams end up batching six risky changes into one window.

  • ADD COLUMN with a non-volatile default stores the default in the table metadata and does not rewrite the table. It is fast on a table of any size. This is the change people still schedule maintenance windows for.
  • The same statement does rewrite the whole table and every index on it when the default is volatile, for example clock_timestamp(), or when the column is a stored generated column, an identity column, or a domain type carrying constraints. A virtual generated column never rewrites.
  • SET NOT NULL normally scans the entire table, and the scan is skipped when a valid CHECK constraint already proves no NULL can exist. So the two-step is: add the CHECK as NOT VALID, VALIDATE it, then SET NOT NULL, which now has its proof and scans nothing.
  • ADD CONSTRAINT with NOT VALID commits immediately and scans nothing. The later VALIDATE CONSTRAINT takes only SHARE UPDATE EXCLUSIVE, because concurrent transactions are already enforcing the new rule and only pre-existing rows need checking. If the constraint is a foreign key, a ROW SHARE lock is also taken on the referenced table.
  • ADD FOREIGN KEY takes SHARE ROW EXCLUSIVE rather than ACCESS EXCLUSIVE, and attaching a partition takes only SHARE UPDATE EXCLUSIVE on the parent. The gentler locks are documented exceptions worth reading once.
  • CREATE INDEX CONCURRENTLY builds without blocking writes, at the cost of taking longer and not being allowed inside a transaction. If it fails it leaves an invalid index you must drop before retrying, so check afterwards rather than assume.

Expand and contract

The real constraint is not the database, it is that during a rolling deploy two versions of your code run at once against one schema, so the schema must be compatible with both at every instant. That rules out every change which renames, narrows or removes something in one step. The pattern that survives is parallel change, or expand and contract, spread across several deploys.

  1. Expandadd the new column, nullable, with no default that triggers a rewrite
  2. Write bothdeploy code that writes old and new, still reads old
  3. Backfillbatched by key range, resumable, idempotent, with a pause between batches
  4. Read newdeploy code that reads new while still writing both
  5. Contractstop writing old, prove nothing reads it, drop it in its own deploy

Every arrow is a deploy you are allowed to stop at. That is the entire value: rolling back the application never requires rolling back the database, because the schema always supports the previous version of the code. Renaming is not an exception. The rename is instant and breaks every process still running old code, so a rename is really add, write both, backfill, switch reads, drop.

Backfills are their own discipline

A single UPDATE across twenty million rows holds locks for its whole duration, generates an enormous volume of write-ahead log, bloats the table, and restarts from zero if it fails at ninety percent. Write backfills as a loop over a key range: a few thousand rows per batch, each batch its own transaction, a short sleep between them so autovacuum and your real traffic get air, and a record of where it reached so it can resume. Make it idempotent, because you will run it twice.

The step you cannot roll back

Deploy rollbacks do not restore data: reverting the code does not bring back a dropped column, and the backup you would restore from contains none of the other changes made since. So separate the destructive step in time: ship the code that stops using the column, wait until you can prove nothing reads it, then drop it in a deploy of its own. Proving it is the part people skip. Log the reads, or revoke select on that column in staging and watch what breaks, rather than trusting a search of a codebase that also contains a report nobody remembers writing.

The operational minimum

  • Migrations run in the deploy pipeline, never from a laptop. One applied by hand exists in production and not in the repository, so your schema and your source have silently diverged.
  • One migration per deploy, so that when something breaks the cause is unambiguous.
  • Test against production-sized data. A migration tested on a seed database of two hundred rows was tested for syntax, not behaviour.
  • Check for long-running transactions immediately before deploying, and write the rollback down before you run anything, even when the rollback is restore from backup and lose an hour.

Key takeaways

1ALTER TABLE takes ACCESS EXCLUSIVE unless documented otherwise, and a waiting lock blocks every query behind it, so an instant change behind a long read takes the site down.
2Know the cheap forms: non-volatile ADD COLUMN does not rewrite, NOT VALID then VALIDATE avoids the long scan, a CHECK lets SET NOT NULL skip its scan, CREATE INDEX CONCURRENTLY does not block writes.
3Rolling deploys run two code versions against one schema, so every change is expand and contract across several deploys, never a single rename or drop.
4Backfill in resumable, idempotent batches with a pause between them. One giant UPDATE bloats the table and restarts from zero.
5Drops are unrecoverable by rollback: ship the stop-using change, prove nothing reads it, then drop in a deploy of its own.

This is one lesson of 541.

The whole Foundation is free — 16 subjects, beginner to advanced. Sign in to track what you have read, take the end-of-module quizzes, and use the terminal.