Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

In PostgreSQL, ALTER TABLE orders ADD COLUMN note text; normally finishes in milliseconds, but during a deploy it hung and all queries on orders stopped for minutes. Explain why.

ALTER TABLE needs an ACCESS EXCLUSIVE lock, which conflicts even with the light lock a plain SELECT takes. If some old transaction already holds any lock on orders, the ALTER waits in the lock queue, and every query that arrives after it queues behind the ALTER, so the whole table looks frozen even though the ALTER itself would take milliseconds. We prevent it by running migrations with a short lock_timeout and a retry, and by checking for old transactions before deploying.

Why this question is asked

This is one of the most surprising PostgreSQL incidents because the statement is genuinely cheap. Adding a nullable column only changes the table's metadata, yet a deploy that runs it can stop all traffic on the table for minutes. Interviewers ask it to see whether we understand the lock queue, not just the lock modes, and whether we know how to make migrations safe. In this answer, we will recap the table lock modes, reproduce the hang with three sessions, see why everyone queues behind the ALTER, and then fix it with lock_timeout, retries and a pre-deploy check, including how to set this in Flyway and Liquibase.

1A Quick Recap of Table Locks

Besides row locks, PostgreSQL takes a lock on the whole table for every statement that touches it. These table locks come in eight modes, and most of them are weak and compatible with each other. A plain SELECT takes ACCESS SHARE, the weakest mode. INSERT, UPDATE and DELETE take ROW EXCLUSIVE. These coexist happily, which is why reads and writes run in parallel all day.

ALTER TABLE ... ADD COLUMN takes ACCESS EXCLUSIVE, the strongest mode. It conflicts with every other mode, including ACCESS SHARE. The reason is that it changes the table's definition, and no other statement may be reading the table while its shape changes. Another important detail: a table lock is held until the end of the transaction that took it, not until the statement finishes. A transaction that ran one SELECT on orders an hour ago and is still open still holds ACCESS SHARE on orders.

2Reproducing the Hang With Three Sessions

We can reproduce the incident with three psql sessions. Session A is a forgotten transaction or a long report. Session B is the deploy. Session C is the application.

SQL
-- Session A: a report that is still running, or an idle transaction
BEGIN;
SELECT count(*) FROM orders; -- holds ACCESS SHARE on orders until COMMIT
-- Session B: the deploy
ALTER TABLE orders ADD COLUMN note text; -- waits: ACCESS EXCLUSIVE conflicts with A's lock
-- Session C: ordinary application traffic
SELECT * FROM orders WHERE id = 7; -- waits too, even though A would allow it
-- Session D: what we see
SELECT pid, pg_blocking_pids(pid), left(query, 40) FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
-- pid | pg_blocking_pids | left
-- 202 | {101} | ALTER TABLE orders ADD COLUMN note text
-- 303 | {202} | SELECT * FROM orders WHERE id = 7

Notice the last line: session C is blocked by the ALTER, not by session A. Session C's ACCESS SHARE lock is compatible with A's lock, so if the ALTER were not there, C would run immediately. The ALTER has not done anything yet, and it is already blocking everyone.

3Why Everyone Queues Behind the Waiting ALTER

PostgreSQL grants conflicting lock requests in the order they arrive. When the ALTER asks for ACCESS EXCLUSIVE and has to wait, it takes its place in the queue for the orders table. A new request that conflicts with a queued request waits behind it, even if it is compatible with every lock that is actually held. The reason is fairness: without this rule, a steady stream of SELECTs could keep the table busy forever and the ALTER would never get its turn. This is called lock starvation, and the queue prevents it.

The cost of fairness is what we saw in the deploy. Every SELECT, INSERT and UPDATE on orders now queues behind the ALTER, which itself waits for the old transaction. Application requests time out, connection pools fill with waiting requests, and to everyone watching, the database has stopped. The moment session A ends, the ALTER gets its lock, finishes in milliseconds, releases it, and the whole queue drains at once.

Step throughThe lock queue during the deploy
Old transactionorders lock queueALTER TABLEApp queries
holds ACCESS SHARE (still open)
requests ACCESS EXCLUSIVE: conflicts, waits
request ACCESS SHARE: queue behind the ALTER
timeouts, pool fills up
COMMIT, lock released
lock granted, column added in ms
queue drains, traffic resumes

7 messages in order. Play them, or step through them one at a time.

The ALTER waited for minutes but worked for milliseconds; the queue behind it caused the outage.

4Why the ALTER Itself Is Fast

Once it gets the lock, adding a nullable column is a metadata-only change: PostgreSQL records the new column in its catalog and does not touch the existing rows, which simply read as NULL for that column. Since PostgreSQL 11, the same is true for a column with a non-volatile default such as DEFAULT 'none' or DEFAULT 0, because the default is stored once in the catalog and returned for old rows.

A volatile default is different. DEFAULT clock_timestamp() or DEFAULT gen_random_uuid() must produce a different value for each existing row, so PostgreSQL rewrites the entire table while holding ACCESS EXCLUSIVE. On a large table that is minutes of real blocking, a separate problem from the queueing we saw here, and one that migration linters should catch.

5The Fix: A Short lock_timeout and a Retry

Since the ALTER itself is fast, we only need to stop it from waiting long in the queue. lock_timeout tells PostgreSQL to give up on a statement that cannot acquire its lock within the limit. If the ALTER gives up after three seconds, the queue behind it disappears after three seconds, and the application sees a brief pause instead of an outage. Then we retry after a short pause, because the old transaction may have finished.

SQL
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN note text;
-- If something holds a lock on orders:
-- ERROR: canceling statement due to lock timeout
-- The queue behind it is released; the migration tool retries after a pause.
-- Before deploying, look for old transactions that would block us
SELECT pid, state, now() - xact_start AS age, left(query, 50)
FROM pg_stat_activity
WHERE xact_start < now() - interval '1 minute'
ORDER BY xact_start;

The timeout should be short compared with what the application tolerates; if its own timeouts are lower than three seconds, choose one second. The pre-deploy query finds a forgotten session or long report before we start.

6Setting lock_timeout in Flyway and Liquibase

The simplest place is the migration itself: a first line of SET lock_timeout = '3s'; in the SQL script applies to the rest of that script, because Flyway and Liquibase run a script on one connection. To apply it to every migration without relying on authors, we set it on the connection. Flyway runs initSql on each connection it opens, and Spring Boot exposes it as spring.flyway.init-sqls. For Liquibase, or any tool, the PostgreSQL JDBC driver accepts server settings in the URL through the options parameter. A third option is a dedicated migration role with the setting attached by ALTER ROLE.

Java
# Spring Boot with Flyway
spring.flyway.init-sqls: SET lock_timeout = '3s'
# Any tool, through the PostgreSQL JDBC driver
spring.liquibase.url: jdbc:postgresql://db:5432/shop?options=-c%20lock_timeout=3s
-- Or once, on the role that runs migrations
ALTER ROLE migrator SET lock_timeout = '3s';

Retries are the other half: the deploy pipeline reruns the migration step a few times with a pause, which is safe because a failed ALTER changed nothing.

7Follow-up questions

How would Flyway or Liquibase be configured to set lock_timeout?

Put SET lock_timeout at the top of the script for a single migration. For all migrations, use Flyway's initSql (spring.flyway.init-sqls in Spring Boot), the PostgreSQL JDBC options parameter in the migration URL, which works for Liquibase too, or ALTER ROLE on the migration user. Then let the pipeline retry the migration step a few times.

Would adding the column with a default have been slower?

Since PostgreSQL 11, a constant or other non-volatile default is stored in the catalog, so it is just as fast. A volatile default such as clock_timestamp() forces a full table rewrite under ACCESS EXCLUSIVE, which is slow on a large table and should be done in steps instead.

8Conclusion

In this answer, we saw that ALTER TABLE takes an ACCESS EXCLUSIVE lock that conflicts even with SELECT. When an old transaction holds any lock on the table, the ALTER waits in the lock queue, and because PostgreSQL grants conflicting requests in order, every later query waits behind it, so the table appears frozen. The column itself is added in milliseconds once the lock is granted. Running migrations with a short lock_timeout, retrying, and checking for old transactions before deploying turns a potential outage into a short pause.

What to say in the interviewAbout 80 seconds aloud

Open with

The ALTER itself is fast, the problem is the lock queue. ADD COLUMN needs an ACCESS EXCLUSIVE lock, which conflicts with everything, even the ACCESS SHARE lock of a plain SELECT, and table locks are held until the transaction ends.

Then, if they want more

So if any session had an open transaction that touched orders, for example a long report or someone idle in transaction, the ALTER had to wait. PostgreSQL grants conflicting lock requests in arrival order to avoid starvation, so every query that arrived after the ALTER queued behind it, even reads that were compatible with the old lock.

That made the table look completely blocked for minutes. As soon as the old transaction ended, the ALTER got its lock, finished in milliseconds because adding a nullable column is metadata only, and the queue drained.

To prevent it, I run every migration with a short lock_timeout, say three seconds, so the ALTER gives up quickly and the queue disappears, and the pipeline retries. With Flyway I would set it through spring.flyway.init-sqls or on the migration role, and with Liquibase through the JDBC options parameter. Before deploying, I check pg_stat_activity for transactions older than a minute.

I would also watch for volatile defaults, which do rewrite the table and need a different approach.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 11
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In PostgreSQL, ALTER TABLE orders ADD COLUMN note text; normally finishes in...": https://scrivio-interview-library.netlify.app/databases/database-locking/cae0e2f5a5/