Skip to content

Zero-downtime Postgres migrations: the lock queue, lock_timeout and NOT NULL done safely

Why a 4 ms ALTER TABLE can take a site down, and how to avoid it: lock_timeout with retries, cheap versus rewriting changes, NOT NULL in steps and safe indexes.

· 9 min read

  • Postgres
  • Migrations
  • Reliability

A schema migration that takes four milliseconds in staging can take a production site down for a minute. The work is not the problem. The lock is. Most forms of ALTER TABLE need an ACCESS EXCLUSIVE lock on the table, and while the statement waits for that lock, every query on the table waits behind it, including plain SELECTs.

This article covers how that happens, how to make migrations give up instead of blocking, and which changes are cheap, which scan the table and which rewrite it. Everything was run on PostgreSQL 16 against this table, filled with five million rows (around 300 MB before indexes), with a customers table alongside it:

CREATE TABLE orders (
  id          bigserial PRIMARY KEY,
  customer_id bigint NOT NULL,
  total_pence bigint NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now(),
  flags       int
);

We have not run PostgreSQL 18 yet. Where it changes the picture, the syntax below is taken from its manual and marked as such.

The lock queue

SELECT takes an ACCESS SHARE lock. The manual’s own summary is that only an ACCESS EXCLUSIVE lock blocks a SELECT. That is true, but a waiting ACCESS EXCLUSIVE request blocks them too, because lock requests on a table queue in order.

We held a transaction open in one session, the way a long report or an idle-in-transaction connection would:

BEGIN;
SELECT count(*) FROM orders WHERE id = 1;
-- stays open for 8 seconds

In a second session we ran a trivial migration:

ALTER TABLE orders ADD COLUMN note text;

It waited, as expected: the open transaction holds ACCESS SHARE, which conflicts with ACCESS EXCLUSIVE. Then a third session ran SELECT id FROM orders WHERE id = 42. It also hung. pg_locks showed why:

 pid  |        mode         | granted
------+---------------------+---------
  694 | AccessShareLock     | t         -- the open transaction
  700 | AccessExclusiveLock | f         -- the ALTER, waiting
  706 | AccessShareLock     | f         -- the SELECT, waiting behind the ALTER

pg_blocking_pids(706) returned {700}: the SELECT was blocked by the ALTER, not by the transaction that started it all. The ALTER completed after seven seconds and the SELECT after six. On a production table every request touching it stalls and the connection pool runs dry, for a migration that took milliseconds once it had the lock.

Give up quickly and retry

The fix is lock_timeout. It aborts a statement that waits longer than the limit to acquire a lock, and only while waiting; it does not limit the statement’s own work. We repeated the test with it set:

SET lock_timeout = '2s';
ALTER TABLE orders ADD COLUMN note text;
-- ERROR:  canceling statement due to lock timeout

The ALTER failed after two seconds, and the queued SELECT ran as soon as it did. Nothing was changed, so the migration can simply try again. Error code 55P03 (lock_not_available) identifies the timeout, which makes a retry loop easy. This one is Node.js with the pg driver. It opens a fresh connection per attempt, because SET is session-level and a pooled connection would carry the two-second limit back into the application. We ran it behind a seven-second transaction and it succeeded on the third attempt:

export async function ddl(config, sql, attempts = 10) {
  for (let attempt = 1; ; attempt++) {
    const client = new pg.Client(config);
    await client.connect();
    try {
      await client.query("SET lock_timeout = '2s'");
      await client.query("SET statement_timeout = 0");
      await client.query(sql);
      return;
    } catch (err) {
      if (err.code !== "55P03" || attempt >= attempts) throw err;
    } finally {
      await client.end();
    }
    const delay = Math.min(30_000, 500 * 2 ** (attempt - 1)) * (0.5 + Math.random());
    await new Promise((r) => setTimeout(r, delay));
  }
}

statement_timeout is set to zero because some steps below legitimately run for a long time, and a statement timeout would cancel them. The manual also notes that a statement_timeout at or below lock_timeout makes the lock timeout pointless, since the statement timeout fires first.

A two-second lock_timeout is still up to a two-second stall for users: the ALTER blocks queries while it waits. The limit bounds the worst case, and it applies to each lock acquisition separately, so a statement that locks a table, its indexes and its TOAST table can wait up to the limit more than once. Keep it short, retry with backoff, and run migrations when traffic is low. Set it per migration session rather than in postgresql.conf, where it would apply to everyone. idle_in_transaction_session_timeout is worth setting too, so a forgotten BEGIN cannot hold a lock for ever.

Which changes are cheap

Once the lock is acquired, how long it is held depends on the form of ALTER TABLE. Some changes touch only the catalog, some rewrite the table, and some scan it (the next section covers those). Times are from our five-million-row table, with a code column added for the type tests. The rewrites were confirmed by pg_class.relfilenode changing, which it did not for the others.

Change Time What happens
ADD COLUMN status text NOT NULL DEFAULT 'new' 4 ms Metadata only. Since PostgreSQL 11, a non-volatile default is stored in the catalog and returned for existing rows.
ADD COLUMN imported_at timestamptz NOT NULL DEFAULT now() 2 ms Also metadata only. now() is stable, so it is evaluated once and every existing row gets the same value.
ADD COLUMN seen_at timestamptz NOT NULL DEFAULT clock_timestamp() 6.8 s Volatile default: the whole table and its indexes are rewritten.
ALTER COLUMN code TYPE varchar(40) on a varchar(20), then TYPE text 2 ms each No rewrite: the old type is binary coercible to the new one and nothing needs checking.
ALTER COLUMN code TYPE varchar(40) on a text column 2.7 s Rewrite. Every value has to be checked against the limit.
ALTER COLUMN flags TYPE bigint on an int 7.8 s Rewrite.
ALTER COLUMN status SET DEFAULT 'pending' 2 ms Metadata only.
DROP COLUMN 2 ms Metadata only; the column is hidden, not removed.

A rewrite holds ACCESS EXCLUSIVE for its whole duration, so an int to bigint change on a large table is not a migration, it is an outage. The usual answer is a new column, a backfill in batches, a trigger to keep the two in step, and a swap; that deserves its own article.

The first row is the one to remember. Adding a NOT NULL column with a constant default costs nothing, so when a new column has a sensible fixed default, use it and skip the backfill entirely.

Adding NOT NULL to an existing column

The naive form scans the table while holding ACCESS EXCLUSIVE:

ALTER TABLE orders ALTER COLUMN flags SET NOT NULL;

That took 0.6 s on our table, which was cached. It grows with the table, and unlike the lock-queue problem, every query waits for the whole scan. Since PostgreSQL 12 there is a way to do the scan without blocking anyone. The manual states that if a valid CHECK constraint proves no NULL can exist, the table scan is skipped. So prove it first:

-- 1. Instant: no scan, enforced for new rows from now on
ALTER TABLE orders ADD CONSTRAINT orders_flags_not_null
  CHECK (flags IS NOT NULL) NOT VALID;

-- 2. Scans the table under SHARE UPDATE EXCLUSIVE, which does not block reads or writes
ALTER TABLE orders VALIDATE CONSTRAINT orders_flags_not_null;

-- 3. Instant: the scan is skipped because the CHECK proves it
ALTER TABLE orders ALTER COLUMN flags SET NOT NULL;
ALTER TABLE orders DROP CONSTRAINT orders_flags_not_null;

Step 1 took 3 ms and step 3 took 2 ms. Step 2 took 0.66 s, and while it ran we inserted and updated rows from another session; both finished in about 50 ms. pg_locks showed the validation holding only SHARE UPDATE EXCLUSIVE. Run the statements as separate transactions. If a migration tool wraps them in one, the ACCESS EXCLUSIVE lock from step 1 is held until the transaction commits, including through the scan, and you are back where you started.

If the validation finds a NULL, it fails with check constraint ... is violated by some row and the constraint stays NOT VALID. New rows are still checked, so you can fix the old data and validate again.

PostgreSQL 18 makes this shorter. NOT NULL constraints are now full entries in pg_constraint, and the manual lists not-null constraints among those that can be added NOT VALID and then validated:

ALTER TABLE orders ADD CONSTRAINT orders_flags_not_null NOT NULL flags NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_flags_not_null;

No CHECK to drop afterwards. On 16 the first statement is a syntax error.

Backfills

Before you can make a column NOT NULL, every row needs a value. One UPDATE orders SET flags = 0 took 49 s. It did not block readers, or writers to rows it had not reached yet, but every row it had changed stayed locked until commit, and a 49-second transaction stops vacuum removing anything that died during it, the same problem as the long-transaction design in a Postgres job queue.

Batching did not make it faster: fifty thousand rows per transaction took 49 s in total too. What it changed is the shape. No row is locked for more than a fraction of a second, a failure part-way loses one batch rather than everything, and vacuum can keep up.

UPDATE orders SET flags = 0
WHERE id > $1 AND id <= $2 AND flags IS NULL;

The flags IS NULL condition makes the loop safe to rerun from the start. Walk the primary key in ranges rather than using OFFSET; the reasons are the ones in keyset pagination in Postgres. Either way the table roughly doubled in size, because every updated row leaves a dead one behind. Vacuum makes that space reusable but does not give it back to the filesystem.

Indexes

Plain CREATE INDEX takes a SHARE lock. Reads continue, writes wait. On our table it took 2.2 s, a SELECT during it returned in 34 ms, and an UPDATE waited 1.7 s for it to finish. CREATE INDEX CONCURRENTLY took 3.1 s and the same UPDATE ran in 26 ms. The concurrent form is slower and has three catches.

It cannot run inside a transaction block. If your migration tool wraps each migration in a transaction, as most do, you need its escape hatch for this one.

It waits. Before each of its two scans it waits for every transaction that has written to the table, and at the end for every transaction in the database whose snapshot is older than its second scan. Behind a six-second transaction that had updated one row, our build took 6.3 s instead of 3.1 s. A long report running elsewhere can stall it for as long as the report runs.

If it fails, it leaves an INVALID index behind. We forced a failure by building a unique index over duplicate rows:

Indexes:
    "orders_pkey" PRIMARY KEY, btree (id)
    "orders_cust_total" UNIQUE, btree (customer_id, total_pence) INVALID

Queries ignore an invalid index. Whether writes still maintain it, and whether a unique one already rejects duplicates, depends on how far the build got before it failed: ours failed in the first scan, pg_index.indisready was false, and a duplicate insert went straight through. The same leftover appeared when a lock_timeout cancelled a concurrent build that was waiting for a writer. So a retry loop around CREATE INDEX CONCURRENTLY must drop the invalid index before trying again, and IF NOT EXISTS does not help: it saw the invalid index and skipped. Check indisvalid first, and remove it with DROP INDEX CONCURRENTLY, which avoids the exclusive lock but, like the build, cannot run in a transaction block.

Foreign keys

ADD FOREIGN KEY takes SHARE ROW EXCLUSIVE on both tables, which blocks writes to each while it checks every row. Split it the same way as the CHECK. Adding orders.customer_id referencing customers as NOT VALID took 3 ms, then VALIDATE CONSTRAINT took 1.4 s under SHARE UPDATE EXCLUSIVE on orders and ROW SHARE on customers. Writes to both continued.

None of this is exotic: a short lock_timeout with retries, constant defaults, NOT VALID then VALIDATE, CONCURRENTLY for indexes, one step per transaction. The difference between a migration nobody notices and one that pages the on-call engineer is usually whether someone checked which lock each statement takes first.

If you’re planning schema changes on a live system, or an API and database that have to stay up while they evolve, see our backend development service.

Have something you'd like built?

Tell us what you're building. We'll reply within two working days with questions, an approach and next steps.

Start a project
Esc

↑ ↓ to move · Enter to open