QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Database structure

How do you change a schema without downtime: expand/contract, CONCURRENTLY and NOT NULL?

A schema is changed without downtime in small compatible steps. An ALTER takes a strong lock and queues others behind it, so the migration sets lock_timeout. An index is built with CREATE INDEX CONCURRENTLY outside a transaction and invalid ones are checked. NOT NULL is introduced through CHECK ... NOT VALID, VALIDATE and SET NOT NULL, and a rename is done as expand/contract over several releases.

SQL · Database structure

A migration "only adds a column" and the service does not answer for a minute. What happened?

A migration adds one column to the orders table and in CI it runs in an instant. On the live environment it stands in a queue, and ordinary SELECTs and INSERTs to that table queue behind it: the application is silent until the migration ends. The command itself is fast, the lock is to blame. This lesson is about how to change a schema so that users do not notice: the order of steps, long operations and NOT NULL constraints.

How it works and why. In PostgreSQL most forms of ALTER TABLE take an ACCESS EXCLUSIVE lock unless the documentation says otherwise. It conflicts with any other access to the table, even a read. If some transaction already holds the table (a long report, a forgotten open session), the ALTER waits and new queries line up behind it, although they do not conflict with that transaction themselves. So the downtime comes not from the migration runtime but from the lock wait. Reproduced with three sessions (figure 1).

The queue behind ALTER

Session A: open transactionholds the table after a SELECTB waits for ASession B: ALTER TABLEasks for ACCESS EXCLUSIVE and waitsC waits for BSession C: a plain SELECTno conflict with A, yet queued behind ALTERdowntime = the lock wait
Figure 1. One long reader stops the migration and everyone who arrived after it.

A query to pg_stat_activity with pg_blocking_pids(pid) showed two rows: the ALTER and the ordinary SELECT, both waiting on a Lock event. After a ROLLBACK in session A the ALTER ran first, then the SELECT. The defence: limit the wait in the migration session and retry later.

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

The documentation advises against setting lock_timeout in postgresql.conf because it would affect all sessions: it is set in the migration session. A failed attempt changed nothing and is safe to run again.

An index without blocking writes. A plain CREATE INDEX blocks writes to the table for the whole build. CREATE INDEX CONCURRENTLY builds the index without locks that prevent INSERT, UPDATE and DELETE, but it makes two passes over the table and waits for transactions that could have modified it, so it takes longer. It cannot run inside a transaction: PostgreSQL answers CREATE INDEX CONCURRENTLY cannot run inside a transaction block, and many migration tools wrap every migration in a transaction by default, so the wrapper is switched off for this step. After a failure (for example a uniqueness violation) an invalid index is left behind: queries ignore it, while table updates still maintain it. In a test with a duplicate email pg_index.indisvalid showed false for such an index. It is dropped and built again, or rebuilt with REINDEX INDEX CONCURRENTLY.

-- outside a transaction block
CREATE INDEX CONCURRENTLY idx_orders_user
  ON orders (user_id);

-- after a failure: find leftovers
SELECT indexrelid::regclass
FROM pg_index
WHERE NOT indisvalid;

NOT NULL on a large table. SET NOT NULL checks the whole table under a strong lock. The documentation describes a way around it: if a valid CHECK constraint exists that proves no NULL can exist, the full scan is skipped. The constraint is added as NOT VALID (new rows are already checked, old ones are not), then VALIDATE CONSTRAINT takes only SHARE UPDATE EXCLUSIVE and does not stop writes. Skipping the scan appeared in PostgreSQL 12. Since PostgreSQL 18 a NOT NULL constraint itself can be added as NOT VALID and then validated with VALIDATE CONSTRAINT, without the intermediate CHECK.

ALTER TABLE orders
  ADD CONSTRAINT status_nn
  CHECK (status IS NOT NULL) NOT VALID;
-- backfill old rows first, then:
ALTER TABLE orders VALIDATE CONSTRAINT status_nn;
ALTER TABLE orders ALTER COLUMN status SET NOT NULL;
ALTER TABLE orders DROP CONSTRAINT status_nn;

In a test the NOT VALID constraint rejected a new row with NULL at once, while VALIDATE failed as long as old NULLs remained: the error check constraint ... is violated by some row. So old rows are backfilled first, in batches.

Expand/contract for a rename. A direct RENAME COLUMN is instant, but the old application version fails at once: in a test SELECT email after the rename gave column "email" does not exist. During a deployment old and new code run together, so the change is split into compatible steps, each in its own release:

  1. Expand: add the new column, nullable, with no default. The old version does not notice it.
  2. The new version writes to both columns, and old rows are copied in batches (UPDATE ... WHERE id BETWEEN ...) so no long transaction is held.
  3. The new version reads from the new column. The old column is kept: it is the way back.
  4. Contract: when no old version runs any more, the old column is dropped in a following release.

Limits and alternatives. Adding a column with a constant DEFAULT is fast and does not rewrite the table, while a volatile one (for example gen_random_uuid()) rewrites all of it. MySQL (InnoDB) describes similar operations as online DDL: creating a secondary index permits concurrent changes and does not rebuild the table, renaming a column without changing its type runs with ALGORITHM=INSTANT, and switching to NOT NULL rebuilds the table in place and fails if the column holds NULLs. If the requested ALGORITHM or LOCK is impossible, MySQL returns an error instead of silently taking a stronger lock or a slower algorithm. Expand/contract is slower than one ALTER, but it can be stopped at any step.

Common mistakes.

  • Measuring a migration by its runtime on an empty database: downtime comes from the lock wait when long transactions exist.
  • Running CONCURRENTLY inside the migration tool transaction and getting an error only at this step.
  • Not checking for invalid indexes after a failure: they stay and slow down writes.
  • Renaming and dropping a column in one release: the old application version fails before the deployment ends.

Check yourself

An ADD COLUMN migration runs in milliseconds in CI, but on the live environment even reads stand still. What do you check first?

Answer

Whether a long open transaction holds this table: the ALTER waits for it and other queries line up behind it. Look at pg_stat_activity and pg_blocking_pids, set lock_timeout in the migration and retry.

Why does a developer add CHECK ... NOT VALID instead of SET NOT NULL straight away, and what must happen before VALIDATE?

Answer

SET NOT NULL scans the whole table under a strong lock, while VALIDATE takes a weaker one and does not stop writes. Old rows with NULL must be backfilled before VALIDATE, or it fails.

In an interview. Junior: A schema change locks the table. To avoid downtime it is done in steps: first add, then move the data, then remove the old. Middle/Senior: Downtime comes from the queue behind the ALTER, so I set lock_timeout and look for long transactions. I build indexes with CONCURRENTLY outside a transaction and check for invalid ones, I introduce NOT NULL through CHECK NOT VALID and VALIDATE, and I do a rename as expand/contract over several releases.

More articles in this chapter