Zero-Downtime Postgres SchemaMigrations Under Load
Zero-downtime Postgres schema migrations: how the ACCESS EXCLUSIVE lock queue stalls reads, why lock_timeout and retries fix it, when expand-contract pays.
The outage comes from the lock queue, not the statement
Almost every Postgres schema migration that takes a production system down is a fast statement that waited. Adding a nullable column is metadata work measured in milliseconds. It becomes an incident because of what happens while it sits in the lock queue, and because every other query on that table joins the queue behind it.
PostgreSQL's ALTER TABLE documentation is explicit about the lock involved: an ACCESS EXCLUSIVE lock is acquired unless explicitly noted, and when multiple subcommands are given, the lock acquired will be the strictest one required by any subcommand. ACCESS EXCLUSIVE is the strongest mode Postgres has and conflicts with every other mode, including the ACCESS SHARE that a plain SELECT takes. So a migration that bundles three subcommands takes the strongest lock any one of them needs, for the duration of all three.
The part that surprises teams is that a blocked DDL statement is not passive. Nikolay Samokhvalov's write-up on lock_timeout and retries at postgres.ai demonstrates it with three sessions: one sits idle in transaction after a SELECT, a second runs an ALTER TABLE and blocks, and then a third session's ordinary SELECT hangs too. His description is that the ALTER, while waiting to acquire the lock it needs, starts blocking others, and that it is blocking even read-only transactions that deal with the table. A one-millisecond ADD COLUMN queued behind a forty-second analytics query stalls reads on that table for forty seconds, and in practice your connection pool saturates before that window closes.
That reframes the problem. The question is not how long your DDL takes to execute, it is who holds a conflicting lock when you run it and how long they intend to hold it. Long SELECTs count, a pg_dump counts, and application code that opens a transaction and then makes an HTTP call counts, which is the most common culprit we find. Before any migration, the useful pre-check is a recursive query over pg_stat_activity joined through pg_blocking_pids to see the actual lock tree, plus select max(age(backend_xmin)) from pg_stat_activity to see how old the oldest snapshot on the system is.
lock_timeout and retries, instead of a maintenance window
The fix is small and almost nobody has it configured. Since Postgres 9.3, lock_timeout bounds only the time spent waiting to acquire a lock, which is the behaviour you want: statement_timeout would also kill the work after the lock is granted. Set it transaction-locally, with SET LOCAL lock_timeout = '50ms' immediately before the DDL, so a migration that cannot get its lock fails in 50 milliseconds instead of holding the queue open for everything else.
A failure that fast is only useful with a retry loop around it. The postgres.ai article's recommended shape is a low lock_timeout with retries and exponential backoff plus jitter: its worked example uses a lock_timeout of 50ms, up to 30 attempts, a base delay of 10ms and a cap of 60 seconds, catching the lock_not_available condition and sleeping a random interval inside that bound. In the author's own run the statement succeeded on the twelfth attempt. That is the right outcome. The migration eventually lands, and no single attempt was ever queued long enough for users to notice.
Two details matter if you implement this yourself. Retry the whole transaction rather than wrapping each attempt in a savepoint: the same article notes that subtransaction-based retries consume transaction IDs per attempt and can overflow the subtrans SLRU on standbys. And when one migration touches several tables, acquire the locks up front, explicitly, with LOCK TABLE ... IN ACCESS EXCLUSIVE MODE, so you are not escalating lock levels halfway through a transaction that already holds other locks.
Retries handle the normal case of many short queries. They do not help against a transaction that will run for ten minutes, because every attempt fails. For that, pre-check and refuse: if a transaction older than roughly a minute is touching the target table, postpone the migration or terminate that transaction deliberately. This logic belongs in the migration runner, not in a runbook step performed at 2am.
Know which statements rewrite the table and which only touch metadata
Once the lock behaviour is handled, the next question is how long you will hold that lock. The dividing line is whether the statement rewrites the table. ALTER TABLE ADD COLUMN is cheap even with a default, as long as the default is not volatile: the documentation states that when a non-volatile DEFAULT is specified, the default is evaluated at the time of the statement and the result stored in the table's metadata, and that in neither case, with or without a default, is a rewrite of the table required.
The volatile case is where teams get hurt. The same Notes section says that adding a column with a volatile DEFAULT, or changing the type of an existing column, will require the entire table and its indexes to be rewritten. DEFAULT now() and DEFAULT gen_random_uuid() are volatile, and both appear constantly in generated migrations. The safe sequence is to add the column with no default, backfill in batches, then set the default for new rows.
Constraints have a cheaper path that most ORMs do not take by default. Adding a CHECK or NOT NULL constraint requires scanning the table, but the docs are clear that it does not require a table rewrite, and with NOT VALID the ADD CONSTRAINT command does not scan the table and can be committed immediately, while still enforcing the constraint against new inserts and updates. You then run VALIDATE CONSTRAINT separately, which the documentation says acquires only a SHARE UPDATE EXCLUSIVE lock, so normal reads and writes continue. ADD FOREIGN KEY is also gentler than people expect: although most forms of ADD table_constraint require an ACCESS EXCLUSIVE lock, ADD FOREIGN KEY requires only a SHARE ROW EXCLUSIVE lock.
SET NOT NULL has its own shortcut worth memorising. Ordinarily the column is checked by scanning the entire table, but the docs say that if a valid CHECK constraint exists, and is not dropped in the same command, which proves no NULL can exist, then the table scan is skipped. So the recipe on older versions is to add a CHECK (col IS NOT NULL) as NOT VALID, validate it under the weaker lock, then flip SET NOT NULL for free. PostgreSQL 18 shortened this: its release announcement states that NOT NULL constraints support the NOT VALID and NO INHERIT clauses. On 18 and on 19, released 19 November 2026, you can declare the NOT NULL itself as NOT VALID and validate later, so check which major version your cluster runs before copying a recipe written for 13.
Type changes are the expensive ones and the exceptions are narrow: a rewrite is avoided only if the USING clause does not change the column contents and the old type is either binary coercible to the new type or an unconstrained domain over the new type. Indexes must always be rebuilt unless the system can verify logical equivalence, with the documented example that a column can be changed from text to varchar, or vice versa, without rebuilding the indexes because these data types sort identically. Note also that the USING expression is not applied to the column's default value, so a type change usually needs DROP DEFAULT and SET DEFAULT around it, and that a rewrite is not MVCC-safe: the docs warn that after a table rewrite, the table will appear empty to concurrent transactions. DROP COLUMN is the mirror image, since it does not physically remove the data and the space returns only on a later rewrite, which in PostgreSQL 19 is what the new REPACK command is for, replacing VACUUM FULL and CLUSTER.
CREATE INDEX CONCURRENTLY, and the mess a failed build leaves behind
Index creation is the other half of most migration incidents. The PostgreSQL 19 documentation states plainly that a standard index build locks out writes, but not reads, on the table until it's done. On a table of any size that is a write outage, so CONCURRENTLY is not an optimisation, it is the only acceptable form in production. The cost is real: with that option Postgres must perform two scans of the table, and in addition it must wait for all existing transactions that could potentially modify or use the index to terminate, before each scan.
Three constraints follow from that design, and each breaks a naive pipeline. A regular CREATE INDEX can be performed within a transaction block, but CREATE INDEX CONCURRENTLY cannot, so your framework's automatic transaction wrapper has to be disabled for that migration. Only one concurrent index build can occur on a table at a time, which rules out parallelising index additions on the same table. And schema modification of the table is not allowed while the index is being built.
The failure mode is the part to design for. If a problem arises while scanning, the command fails but leaves behind an invalid index, which the docs say will be ignored for querying purposes because it might be incomplete, however it will still consume update overhead. You are paying write amplification for an index no query can use, and nothing in your application will tell you. psql's backslash d reports it with the INVALID marker, and the recommended recovery is to drop the index and run CREATE INDEX CONCURRENTLY again, or rebuild it with REINDEX INDEX CONCURRENTLY.
Unique indexes deserve a specific warning. The uniqueness constraint is already being enforced against other transactions when the second table scan begins, and if a failure occurs in that second scan, the invalid index continues to enforce its uniqueness constraint afterwards. That is an index rejecting inserts while invisible to the planner, which makes for a genuinely confusing incident. The practical answer is a post-deploy check that queries pg_index for indisvalid being false and alerts. Two more limits: concurrent builds for indexes on partitioned tables are currently not supported, so you build per partition and attach, and only the first table scan is actually performed in parallel.
Expand and contract, because two versions of your code are always live
The database is only half the problem. During any rolling deploy, old and new application code run against the same schema at once, so every schema change has to be compatible with the code version about to be replaced. That constraint is what makes renames, type narrowing and column drops dangerous, and why the only pattern that reliably works is expand and contract: make additive changes, migrate data and traffic, then remove the old shape in a later release.
For a column rename the full sequence is six steps and three deploys. Add the new column, nullable, with no default. Deploy code that writes both columns and reads the old one. Backfill in batches. Add a CHECK ... NOT VALID for the invariant you want, then validate it. Deploy code that reads the new column. Drop the old column in a release after that, once you are confident nothing reads it. ALTER TABLE ... RENAME COLUMN never appears in this list, and that is the point.
Backfills are where the lock discipline from earlier gets undone. A single UPDATE across fifty million rows is one very long transaction: it holds a snapshot that prevents vacuum from cleaning up, it blocks the DDL you want to run next, and it generates enough dead tuples to leave the table bloated afterwards. Batch by primary key range, commit each batch in its own transaction, aim for batches that finish in well under a second, set a statement_timeout per batch, and pause between batches while watching replication lag on your standbys. The backfill belongs in a job runner with progress tracking, not in a migration file that the deploy waits on.
If you want that machinery rather than building it, pgroll from the Xata team is the most interesting option in this space. Its own description is that it offers safe and reversible schema migrations for PostgreSQL by serving multiple schema versions simultaneously, and it does this by creating virtual schemas using views on top of the physical tables, with clients selecting a version by setting the search_path to the new schema version name. The lifecycle is start, then complete once no clients use the old version, with rollback available throughout; for breaking column changes it adds a physical column, backfills it, and configures triggers so writes to either column propagate to the other for the duration of the migration. Its documented defaults put the backfill at 10,000 rows per batch, it works with Postgres 14.0 or later, and it is Apache 2.0 licensed.
Our honest read on it: pgroll is a strong fit when you cannot control when clients move to the new schema, for example a public API with external consumers or mobile clients in the wild. It is still a 0.x release, it puts a view layer between your application and your tables, and it brings its own migration format to learn. For a single service you deploy yourself, lock_timeout with retries, the cheap-statement catalogue above and expand-contract discipline in your existing tool will get the same uptime with less to explain to the next engineer. Either way, put a linter in CI: Squawk for raw SQL migrations and strong_migrations for Rails both catch the unsafe patterns before review does.
The five checks we put in a client's deployment pipeline
Check 1 is lock_timeout. Every migration transaction sets it locally, with a documented value and a retry policy around the statement, and a migration that cannot acquire its lock exits non-zero rather than waiting. If your tool has no hook for this, that is a reason to change tools.
Check 2 is a static linter in CI on the migration diff. The rules that pay for themselves immediately: no volatile default on ADD COLUMN, no ALTER COLUMN TYPE without an explicit plan, no CREATE INDEX without CONCURRENTLY, no RENAME, no constraint added without NOT VALID.
Check 3 is a post-deploy validity sweep. A query against pg_index for any index where indisvalid is false, run after every deploy and alerting if it finds one, because a failed concurrent build is otherwise silent and expensive.
Check 4 is separating backfills from migrations. Schema changes are fast, transactional and run during the deploy. Data changes are batched, resumable, rate limited and run outside it. Mixing them is how a deploy ends up holding a lock for twenty minutes.
Check 5 is a blocker pre-check with teeth. Before DDL, inspect pg_stat_activity for transactions older than a threshold against the target table, then abort or terminate them by a policy decided in advance rather than improvised mid-deploy.
Working with Darvi Labs
This is ordinary production engineering rather than anything clever, and it is usually the difference between a schema change nobody notices and a postmortem. Darvi Labs is a software engineering company based in Dhumbarahi, Kathmandu, working with product and engineering teams in the US, UK, EU, Australia and the Gulf. Scalable web application architecture and agentic AI engineering are what we do, and schema evolution on a live system is a recurring part of both.
If you have a migration coming up that you are not comfortable running, or a migration tool that gives you no way to set a lock timeout, that is a short and useful conversation to have before the deploy rather than after it. You can reach the team through the Contact page, read more engineering write-ups including pieces on PostgreSQL index tuning under production load and multi-tenant data isolation in PostgreSQL on the blogs page, and see recent work on the portfolio page.
Thinking through a similar decision?
Send us the constraint, the workflow, or the decision that keeps resurfacing. We can help clarify what should change first.
Start a conversation→Keep the decision trail moving.
Three more short reads from DarviLab work across product, systems, and operating constraints.
Nepal's Software Talent Pool: Size, Shape and Limits
Nepal's software talent pool, in figures: how big it really is, where the engineers are trained, what the employability gap means, and who keeps leaving.
Streaming LLM Responses: Proxies, Timeouts, Resumption
Streaming LLM responses breaks in the proxy layer, not the model: response buffering, the four idle-timeout clocks, and what resumption really costs you.
Outsourcing HIPAA and PCI Work to an Offshore Team
Outsourcing HIPAA and PCI work offshore: what the BAA chain must cover, how to keep your developers out of PCI scope, and what DORA adds for EU firms.