Filed underL03 · Cloud & DevOps
Published
Reading time23 min
Words5,392
Field notes · L03 Cloud & DevOps

Zero-downtime Postgres migrationsExpand/contract, lock timeouts and the ALTER TABLE that takes production down

How to change a live Postgres schema without downtime: the lock queue, lock_timeout, CREATE INDEX CONCURRENTLY, NOT VALID constraints, batched backfills.

The short answer

Most Postgres outages during migrations are not caused by slow DDL. They are caused by a fast DDL statement that waits for a lock, while every query that arrives after it queues up behind it. To migrate with zero downtime, run every migration with a short lock_timeout and retry. Use CREATE INDEX CONCURRENTLY, add constraints as NOT VALID and then VALIDATE them, backfill in small committed batches, and ship breaking changes as expand → migrate → contract across separate app deploys.

The rest of this post covers the mechanics, the SQL we actually run, and the places it still goes wrong. Everything here is checked against PostgreSQL 18 (current release 18.6), with notes where older versions behave differently. PostgreSQL 19 is in beta at the time of writing (Beta 4 announcement).

01Why a one-millisecond ALTER TABLE takes production down

Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock. That lock conflicts with every other lock mode, including the ACCESS SHARE lock a plain SELECT takes (explicit locking). Adding a nullable column only touches the catalogue, so once it has the lock it finishes in milliseconds.

The problem is getting the lock. Postgres hands out locks in roughly arrival order. A new request has to wait if it conflicts with a lock someone holds, or with a request already waiting in the queue. That second rule stops starvation. It also means one waiting ACCESS EXCLUSIVE request blocks every later SELECT on that table, even though none of those SELECTs conflict with each other.

Diagram
t=0s    analytics job:  BEGIN; SELECT ... FROM orders ...   (holds ACCESS SHARE, runs 90s)
t=5s    migration:      ALTER TABLE orders ADD COLUMN note text;
                        -> needs ACCESS EXCLUSIVE, conflicts with analytics job, WAITS
t=5.01s web request:    SELECT * FROM orders WHERE id = $1;
                        -> needs ACCESS SHARE, conflicts with the *waiting* ALTER, WAITS
t=5.02s ...every request touching orders now waits...
t=6s    connection pool exhausted; health checks fail; load balancer pulls instances
t=90s   analytics job commits -> ALTER runs in 2ms -> queue drains

The ALTER needed 2 ms. The outage lasted 85 seconds. GoCardless wrote this up after it cost them 15 seconds of API downtime, and Xata's write-up on the lock queue walks through the same thing. It is still the most common way we see schema changes hurt production.

Three things make it worse in practice:

  • Long transactions you didn't know about. An idle-in-transaction session from a debugging console. A BI tool holding a cursor open. A pg_dump running against the primary. Each one holds ACCESS SHARE until it ends.
  • Transactional DDL keeps locks until COMMIT. If your migration framework wraps five statements in one transaction, the ACCESS EXCLUSIVE from statement one is held until statement five finishes. A fast ALTER followed by a slow UPDATE in the same transaction means the table is locked for the whole UPDATE.
  • Replicas get hit too. ACCESS EXCLUSIVE locks are WAL-logged and replayed on hot standbys. A long read on a replica will either hold up replay (replication lag grows) or get cancelled once max_standby_streaming_delay runs out (hot standby conflicts).

02lock_timeout, statement_timeout and transaction_timeout: what each one is for

The fix for the lock queue is to put a limit on the wait. Postgres gives you three timeouts. They do different jobs (client connection defaults):

Setting What it limits Use it in migrations for
lock_timeout Time spent waiting for each lock. "The time limit applies separately to each lock acquisition attempt." Always. This is what stops the queue pile-up. Typically 1–5 s.
statement_timeout Total time per statement, waiting included Making sure a statement you think is metadata-only can't quietly turn into a table rewrite. Leave it unset (or very generous) for CREATE INDEX CONCURRENTLY and VALIDATE.
transaction_timeout (PG 17+) Total time per transaction A backstop against a migration transaction that holds locks far longer than planned.

The docs warn against setting any of these in postgresql.conf, because they would apply to every session. Set them in the migration session. One important caveat: if you run migrations through PgBouncer in transaction mode, a session-level SET can leak onto another client's server connection. Either run migrations over a direct connection to the primary (our default), or use SET LOCAL inside an explicit transaction. It is the same pooler trap that leaks tenant context in multi-tenant Postgres with row-level security.

How to pick lock_timeout: it is the longest stall you are willing to put on every query that touches the table. If your API's p99 budget is 500 ms, a 5 s lock timeout can still cause a visible blip. Start at 2 s for busy tables, and lower it rather than raising it. When it fires, the migration failed safely. Retry it. Don't make the timeout longer.

A retry wrapper for lock timeouts

A migration that hits lock_timeout rolls back cleanly, as long as it ran in a single transaction. So retry it with backoff and jitter:

bash
#!/usr/bin/env bash
# migrate-with-retry.sh: run one transactional migration file, retrying on lock timeout.
# Not for CREATE/DROP INDEX CONCURRENTLY files (those cannot run inside a transaction).
set -euo pipefail

file="$1"
max_attempts="${MAX_ATTEMPTS:-10}"

for attempt in $(seq 1 "$max_attempts"); do
  if out=$(PGOPTIONS="-c lock_timeout=2s -c statement_timeout=15s" \
           psql "$DATABASE_URL" -X -q -1 -v ON_ERROR_STOP=1 -f "$file" 2>&1); then
    printf '%s\n' "$out"
    exit 0
  fi
  if grep -q 'canceling statement due to lock timeout' <<<"$out"; then
    delay=$(( attempt * 2 + RANDOM % 3 ))
    echo "lock timeout on attempt ${attempt}/${max_attempts}; retrying in ${delay}s" >&2
    sleep "$delay"
    continue
  fi
  printf '%s\n' "$out" >&2   # any other error: stop and look
  exit 1
done
echo "gave up after ${max_attempts} lock timeouts; find the blocker" >&2
exit 1

-1 wraps the file in one transaction, so a retry always starts from a clean state. PGOPTIONS sets the timeouts for this connection only. If you use a framework, the same idea applies: strong_migrations for Rails exposes lock timeout retries as configuration, and most other ecosystems have an equivalent or can be wrapped like this.

Find the blocker before you migrate

Before any migration on a hot table, look for old transactions:

sql
SELECT pid,
       now() - xact_start AS xact_age,
       state,
       usename,
       application_name,
       left(query, 100)   AS query
FROM   pg_stat_activity
WHERE  xact_start < now() - interval '30 seconds'
AND    pid <> pg_backend_pid()
ORDER  BY xact_start;

And while a migration is waiting, ask what it is waiting on:

sql
SELECT a.pid, a.state, now() - a.xact_start AS xact_age,
       pg_blocking_pids(a.pid) AS blocked_by, left(a.query, 100) AS query
FROM   pg_stat_activity a
WHERE  cardinality(pg_blocking_pids(a.pid)) > 0;

Separately, set idle_in_transaction_session_timeout for application roles (for example ALTER ROLE app SET idle_in_transaction_session_timeout = '60s'). Forgotten transactions are the usual blocker, and this takes care of most of them.

03Which ALTER TABLE operations lock or rewrite the table

This is the table we keep open during migration review. "Brief" means the lock is held only for a catalogue update. With lock_timeout set, that is safe on a busy table. "Scan" means the table is read while the lock is held. "Rewrite" means the table, and usually every index on it, is rebuilt while the lock is held. Sources: ALTER TABLE, CREATE INDEX, explicit locking.

Operation Lock Work under lock Verdict Safe alternative
ADD COLUMN (nullable, no default) ACCESS EXCLUSIVE Brief Safe with lock_timeout –
ADD COLUMN ... DEFAULT <non-volatile> (PG 11+) ACCESS EXCLUSIVE Brief (default stored in catalogue) Safe with lock_timeout –
ADD COLUMN ... DEFAULT <volatile> (clock_timestamp(), random(), gen_random_uuid()) ACCESS EXCLUSIVE Rewrite Unsafe Add nullable, set default, backfill in batches
ADD COLUMN ... GENERATED ALWAYS AS (...) STORED ACCESS EXCLUSIVE Rewrite Unsafe on large tables Virtual generated column (PG 18 default; "never requires a rewrite") or trigger + backfill
DROP COLUMN ACCESS EXCLUSIVE Brief (column hidden, space reclaimed later) Safe for the DB; unsafe for the app unless contracted properly See expand/contract
ALTER COLUMN TYPE (binary-coercible, e.g. varchar(50)→varchar(100), varchar→text) ACCESS EXCLUSIVE Brief Safe with lock_timeout –
ALTER COLUMN TYPE (e.g. int→bigint, text→jsonb) ACCESS EXCLUSIVE Rewrite + reindex Unsafe New column + trigger + backfill + swap
ALTER COLUMN SET NOT NULL ACCESS EXCLUSIVE Scan, unless a valid CHECK proves no NULLs Unsafe on large tables NOT VALID → VALIDATE (below)
ADD CONSTRAINT ... CHECK (...) ACCESS EXCLUSIVE Scan Unsafe on large tables NOT VALID then VALIDATE
ADD CONSTRAINT ... FOREIGN KEY SHARE ROW EXCLUSIVE on both tables (blocks writes) Scan Unsafe on large tables NOT VALID then VALIDATE
VALIDATE CONSTRAINT SHARE UPDATE EXCLUSIVE (+ ROW SHARE on referenced table for FKs) Scan, reads and writes continue Safe –
ADD CONSTRAINT ... UNIQUE / PRIMARY KEY ACCESS EXCLUSIVE Index build Unsafe CREATE UNIQUE INDEX CONCURRENTLY then ADD CONSTRAINT ... USING INDEX
CREATE INDEX SHARE (blocks writes) Index build Unsafe on busy tables CREATE INDEX CONCURRENTLY
CREATE INDEX CONCURRENTLY SHARE UPDATE EXCLUSIVE Two scans; reads and writes continue Safe, but can fail and leave an INVALID index –
DROP INDEX ACCESS EXCLUSIVE Brief Usually fine; queues like any ALTER DROP INDEX CONCURRENTLY
ALTER COLUMN SET DEFAULT / DROP DEFAULT ACCESS EXCLUSIVE Brief Safe with lock_timeout –
RENAME COLUMN / RENAME TO ACCESS EXCLUSIVE Brief Safe for the DB; breaks every running app instance Expand/contract
CREATE TRIGGER SHARE ROW EXCLUSIVE (blocks writes) Brief Safe with lock_timeout –
ATTACH PARTITION SHARE UPDATE EXCLUSIVE on parent; ACCESS EXCLUSIVE on the partition being attached Scan of attached partition unless a matching valid CHECK exists Safe with preparation Add a matching CHECK ... NOT VALID, validate, then attach
VACUUM FULL, CLUSTER ACCESS EXCLUSIVE Rewrite Unsafe pg_repack

Note on defaults: now() is STABLE, not volatile. ADD COLUMN created_at timestamptz DEFAULT now() evaluates once and stores that single value in the catalogue, so it doesn't rewrite. That is fine for performance, but every existing row then has the migration's timestamp. Decide whether that's what you actually want.

The cheapest way to confirm whether something rewrites: run it on a production-sized staging copy and compare pg_relation_filenode('orders') before and after. A new filenode means a rewrite.

04How to create an index without locking the table

sql
-- Must run outside a transaction block. No -1, no BEGIN, no framework transaction wrapper.
SET lock_timeout = '2s';      -- applies to the brief lock steps; the build itself doesn't hold a conflicting lock
SET statement_timeout = 0;    -- builds on large tables take as long as they take

CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_customer_id_idx
    ON orders (customer_id);

CONCURRENTLY scans the table twice and waits for existing transactions that could see the old state before each phase. Reads and writes keep going throughout. The trade-offs (docs):

  • It waits for old transactions. That long analytics query will make the build wait. It won't block other traffic, but the build can appear to hang. Watch progress in pg_stat_progress_create_index.
  • It can fail and leave an INVALID index behind. That happens on a deadlock, a uniqueness violation, or the session being killed. The invalid index is ignored by the planner but still costs write overhead. Your retry logic has to deal with this, and IF NOT EXISTS will happily skip over an invalid index with the same name. Check for invalid indexes after every concurrent build:
sql
SELECT c.relname AS index_name, t.relname AS table_name
FROM   pg_index i
JOIN   pg_class c ON c.oid = i.indexrelid
JOIN   pg_class t ON t.oid = i.indrelid
WHERE  NOT i.indisvalid;

Then drop it with DROP INDEX CONCURRENTLY and rebuild it, or use REINDEX INDEX CONCURRENTLY (PG 12+).

  • One concurrent build per table at a time. Queue them. Don't fire off five in parallel.
  • Partitioned tables are not supported directly. Create the index on the parent with ON ONLY (it starts invalid), build each partition's index concurrently, then attach each one:
sql
CREATE INDEX orders_customer_id_idx ON ONLY orders (customer_id);           -- parent, invalid, instant
CREATE INDEX CONCURRENTLY orders_2026_10_customer_id_idx
    ON orders_2026_10 (customer_id);                                          -- repeat per partition
ALTER INDEX orders_customer_id_idx
    ATTACH PARTITION orders_2026_10_customer_id_idx;                          -- parent becomes valid once all are attached

Adding a unique constraint or primary key without a long lock

sql
CREATE UNIQUE INDEX CONCURRENTLY orders_external_ref_key ON orders (external_ref);

-- then, in a short transaction with lock_timeout:
ALTER TABLE orders
    ADD CONSTRAINT orders_external_ref_key UNIQUE USING INDEX orders_external_ref_key;

For PRIMARY KEY USING INDEX, the columns have to be NOT NULL already. Otherwise Postgres sets NOT NULL for you, with a full scan under ACCESS EXCLUSIVE, which defeats the point. Do the NOT NULL step below first.

05How to add a NOT NULL constraint without downtime

ALTER COLUMN ... SET NOT NULL scans the whole table under ACCESS EXCLUSIVE. There are two safe routes, depending on version.

PostgreSQL 18 and later: NOT NULL ... NOT VALID

PG 18 stores NOT NULL constraints in pg_constraint and lets you add them as NOT VALID (release notes). New writes are enforced straight away. Existing rows are checked later under a lock that doesn't block traffic:

sql
-- 1. brief ACCESS EXCLUSIVE, no scan
ALTER TABLE orders
    ADD CONSTRAINT orders_currency_code_not_null NOT NULL currency_code NOT VALID;

-- 2. backfill any NULLs (batched, see below)

-- 3. scan under SHARE UPDATE EXCLUSIVE; reads and writes continue
ALTER TABLE orders VALIDATE CONSTRAINT orders_currency_code_not_null;

After step 3 the column is fully NOT NULL and there is no further step. In PG 18, pg_attribute.attnotnull is already true from step 1, because it now means the column has a "(possibly invalid) not-null constraint" (pg_attribute). So \d shows the column as not null straight away, and lists the constraint as NOT VALID under "Not-null constraints" until you validate it. Check pg_constraint.convalidated, not \d's column list, to know whether validation has run.

Be careful with step 3. The docs say that if a column has an invalid not-null constraint, SET NOT NULL validates it. That validation runs under ALTER TABLE's ACCESS EXCLUSIVE lock. Use VALIDATE CONSTRAINT, not SET NOT NULL, for the validation step.

PostgreSQL 12–17: the CHECK constraint trick

Since PG 12, SET NOT NULL skips the scan if a valid CHECK constraint already proves there are no NULLs:

sql
ALTER TABLE orders
    ADD CONSTRAINT orders_currency_code_nn CHECK (currency_code IS NOT NULL) NOT VALID;  -- brief
ALTER TABLE orders VALIDATE CONSTRAINT orders_currency_code_nn;                          -- non-blocking scan
ALTER TABLE orders ALTER COLUMN currency_code SET NOT NULL;                              -- brief, scan skipped
ALTER TABLE orders DROP CONSTRAINT orders_currency_code_nn;                              -- brief

Run the last two in one short transaction with lock_timeout set. The docs note the scan is only skipped if the CHECK is "not dropped in the same command". Separate statements in the same transaction are fine.

06How to add a foreign key without blocking writes

A plain ADD FOREIGN KEY takes SHARE ROW EXCLUSIVE on both tables and scans the referencing table. Writes to both tables stop for the whole scan. Split it:

sql
-- 0. index the referencing column first, or deletes/updates on customers will seq-scan orders forever after
CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_customer_id_idx ON orders (customer_id);

-- 1. brief lock on both tables, no scan; new writes are checked from here on
ALTER TABLE orders
    ADD CONSTRAINT orders_customer_id_fkey
    FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;

-- 2. scan under SHARE UPDATE EXCLUSIVE on orders + ROW SHARE on customers
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_id_fkey;

If VALIDATE fails, you have orphaned rows. Find them with an anti-join, fix them, and validate again. The constraint stays in place and keeps enforcing new writes the whole time, which is usually what you want.

PG 18 also allows NOT VALID foreign keys on partitioned tables, and adds NOT ENFORCED constraints. Don't confuse the two. NOT ENFORCED never checks anything. It is documentation, not a migration step.

07How to backfill a large table without killing the database

A single UPDATE orders SET currency_code = currency on 200 million rows is a migration failure waiting to happen. It's one huge transaction holding row locks on everything it touches. It produces a burst of WAL that replicas and logical replication consumers have to absorb. It leaves dead tuples that autovacuum can't remove until it commits. And if it fails at 95%, all of the work is thrown away.

Backfill in small batches. Commit each one. Pace them. Watch replication lag.

python
# backfill.py — psycopg 3. Each statement commits on its own (autocommit).
import os, time
import psycopg

DSN          = os.environ["DATABASE_URL"]
BATCH        = 5_000              # rows per transaction; tune so each batch takes ~50–200 ms
PAUSE_S      = 0.05               # breathing room for autovacuum and replicas
MAX_LAG_B    = 256 * 1024 * 1024  # pause if any replica is >256 MB of WAL behind

LAG_SQL = """
SELECT coalesce(max(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)), 0)
FROM   pg_stat_replication
"""

with psycopg.connect(DSN, autocommit=True) as conn:
    conn.execute("SET statement_timeout = '10s'")
    conn.execute("SET lock_timeout = '1s'")
    lo, hi = conn.execute("SELECT min(id), max(id) FROM orders").fetchone()
    cursor = lo
    while cursor is not None and cursor <= hi:
        conn.execute(
            """
            UPDATE orders
               SET currency_code = currency
             WHERE id >= %s AND id < %s
               AND currency_code IS NULL
            """,
            (cursor, cursor + BATCH),
        )
        cursor += BATCH
        while conn.execute(LAG_SQL).fetchone()[0] > MAX_LAG_B:
            time.sleep(1)
        time.sleep(PAUSE_S)

Design notes:

  • Batch by primary-key range, not OFFSET. Range predicates use the index, and each batch costs the same however far in you are. Sparse IDs just mean some batches update fewer rows.
  • Make it idempotent. The AND currency_code IS NULL predicate means you can kill the script and rerun it from the start, or from a saved cursor.
  • New rows are someone else's job. Rows inserted after you read max(id) must already be handled by the application or a trigger (see expand/contract). That is why the dual-write step comes before the backfill.
  • Logical replication counts too. If you run CDC (Debezium, a managed replication slot into a warehouse), also watch pg_replication_slots and confirmed_flush_lsn. A slot that falls behind keeps WAL on the primary's disk.
  • Don't drive it from a stored procedure with COMMIT in a loop unless you've checked how your timeouts and connection pooler treat a single long CALL. An external script is easier to pause, observe and kill.

How long will it take? A worked example, not a benchmark. Assume 200,000,000 rows, 5,000 rows per batch, 80 ms per batch and a 50 ms pause:

Text
batches    = 200,000,000 / 5,000         = 40,000
per batch  = 80 ms + 50 ms               = 130 ms
total      = 40,000 × 0.13 s             = 5,200 s ≈ 87 minutes (plus any lag pauses)

Measure your real per-batch time on the first few hundred batches and redo the sum. If 87 minutes is too slow, raise the batch size before you cut the pause. The pause is what keeps replicas and autovacuum healthy.

08Expand/contract: coordinating schema changes with application deploys

Everything above makes individual statements safe. Expand/contract makes the sequence safe. During a rolling deploy, version N and version N+1 of your application run against the same database at the same time. So every schema state you pass through has to work with both of them.

The pattern, using a column rename (orders.currency → orders.currency_code) as the example:

Diagram
          schema                    app deploy               both N and N+1 work?
          ──────                    ──────────               ────────────────────
Phase 1   EXPAND                    —                        yes: new column unused
          add currency_code (nullable)
          add sync trigger
Phase 2   MIGRATE                   —                        yes
          batched backfill
          add NOT NULL (NOT VALID → VALIDATE)
Phase 3   —                         deploy A: read/write     yes: trigger keeps both in sync
                                    currency_code
Phase 4   —                         deploy B: stop           yes
                                    referencing currency
                                    (ORM ignore list)
Phase 5   CONTRACT                  —                        yes: nothing reads the old column
          drop trigger, drop currency

Phase 1, the sync trigger. It handles writes from either app version:

sql
CREATE OR REPLACE FUNCTION orders_sync_currency() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    NEW.currency_code := coalesce(NEW.currency_code, NEW.currency);
    NEW.currency      := coalesce(NEW.currency, NEW.currency_code);
  ELSIF NEW.currency_code IS DISTINCT FROM OLD.currency_code THEN
    NEW.currency := NEW.currency_code;
  ELSIF NEW.currency IS DISTINCT FROM OLD.currency THEN
    NEW.currency_code := NEW.currency;
  END IF;
  RETURN NEW;
END $$;

SET lock_timeout = '2s';
ALTER TABLE orders ADD COLUMN currency_code text;
CREATE TRIGGER orders_sync_currency
  BEFORE INSERT OR UPDATE ON orders
  FOR EACH ROW EXECUTE FUNCTION orders_sync_currency();

The rules that make this work:

  1. One deploy per incompatible step. A rename takes at least two app deploys and three migrations. That isn't bureaucracy. It's the minimum number of states in which old and new code can coexist.
  2. Migrations run before the deploy that needs them, never in the same step as one that breaks the old code. Expand migrations go before the app deploy. Contract migrations go after the last app version that used the old shape has drained. That includes background workers, cron jobs and the one-off script someone left running.
  3. Tell the ORM before you drop the column. Many ORMs cache column lists or generate SELECT * style statements. Rails needs ignored_columns deployed before the drop. Elsewhere, a dropped column under a cached prepared statement can produce cached plan must not change result type errors until connections recycle.
  4. Contract is optional but has a deadline. Leaving the old column for a week is fine. Leaving it for a year means someone new reads from it. Put the contract migration in the same ticket as the expand.

The same shape covers changing a column's type (for example int → bigint primary keys): add the new column, sync it with a trigger, backfill, build a unique index concurrently, then swap in one short ACCESS EXCLUSIVE transaction (drop the old PK, ADD PRIMARY KEY USING INDEX, move sequence ownership and the default, rename). If other tables reference that key, their foreign key columns need the same treatment first. That's the part people underestimate, and it is often the bulk of the work.

Do you need pgroll or another expand/contract tool?

pgroll automates expand/contract by serving the old and new schema versions side by side through views, with the backfill and triggers generated for you. It's good engineering. You probably don't need it if you have one main application, a migration linter, and the discipline to split deploys. It starts to pay off when many services share a database, deploy on their own schedules, and can't easily coordinate, as often happens partway through a strangler fig migration off a monolith. Then a tool that enforces the two-version contract is worth the extra moving part.

What we'd put in nearly every pipeline instead is a linter. Squawk flags exactly the operations in the table above, including require-lock-timeout and require-statement-timeout rules, and runs in CI against the raw SQL your framework generates.

09The migration review checklist and session preamble

This is the asset. Copy it into your repository's PR template or migration README.

Session preamble for every transactional migration

sql
-- Paste at the top of every migration that runs in a transaction.
SET LOCAL lock_timeout      = '2s';    -- max stall imposed on other queries; lower for very hot tables
SET LOCAL statement_timeout = '15s';   -- anything slower here is not metadata-only; stop and rethink
-- PG 17+: backstop for the whole transaction
SET LOCAL transaction_timeout = '30s';  -- armed when this line runs, not at BEGIN
SET LOCAL application_name  = 'migration:20261006_add_currency_code';  -- visible in pg_stat_activity

SET LOCAL transaction_timeout inside an open transaction starts the timer at that point (assign_transaction_timeout), so the 30 seconds count from the preamble, not from BEGIN.

For non-transactional files (CONCURRENTLY operations), use SET instead of SET LOCAL on a dedicated direct connection. Keep lock_timeout, and set statement_timeout = 0.

Pre-merge review (author and reviewer)

# Check Pass if
1 Every statement is in the "safe" column of the lock table, or uses its safe alternative No bare CREATE INDEX, SET NOT NULL, ADD CONSTRAINT without NOT VALID, volatile DEFAULT, or type change that rewrites
2 Preamble present with lock_timeout Linter (require-lock-timeout) passes
3 Only one ACCESS EXCLUSIVE statement per transaction, or several that are all brief No slow statement after a lock-taking one in the same transaction
4 CONCURRENTLY operations are in their own non-transactional migration Framework transaction wrapper disabled for that file only
5 Backfills are not in the migration Backfill is a separate, resumable, batched job
6 Schema state is compatible with the currently deployed app and the next version Reviewer can name which deploy each phase belongs to
7 Drops and renames have a prior deploy that stopped using the column Link to the merged PR that added the ORM ignore or removed the reads
8 New FK columns have an index CREATE INDEX CONCURRENTLY precedes ADD FOREIGN KEY ... NOT VALID
9 Tested against production-sized data Timing recorded; pg_relation_filenode unchanged for "brief" operations

At run time (operator)

  1. Check for long transactions (the pg_stat_activity query above). Kill or wait out anything older than your lock_timeout budget on the target table.
  2. Check replication lag and logical slot lag are at baseline.
  3. Avoid peak traffic and scheduled batch windows (nightly ETL, reporting jobs, pg_dump).
  4. Run with the retry wrapper. Treat repeated lock timeouts as a signal to find the blocker, not a reason to raise the timeout.
  5. After any CONCURRENTLY operation, run the invalid-index query.
  6. After VALIDATE, confirm pg_constraint.convalidated = true.
  7. Record the actual duration against the estimate. Next time's estimate gets better.

Rollback stance

Write the down-migration for expand steps. They're cheap to reverse. Don't pretend contract steps are reversible: once a column is dropped, the data is gone. The rollback for a contract is a restore. Make sure the backup you'd restore from has actually been tested, because your backups don't exist until you've restored them. A contract is also the kind of change worth writing up in an architecture decision record that notes its reversal cost.

10Where this crosses the other layers

A schema migration looks like a database task. In practice it's a coordination problem across layers. The deploy pipeline (Cloud & DevOps) decides the order of migrations and releases, and whether a contract runs before the old workers have drained. Feature flags and progressive delivery decide when the new code path actually takes traffic. The ORM and application code (Software) decide whether a dropped column causes errors. CDC pipelines and warehouses (Data) often break harder than the app does when a column changes type or disappears, because a downstream connector somewhere has a schema it hasn't been told about. And the role that runs migrations (Security) usually has far more privilege than the application role. It should be a separate, audited identity, not the app's own credentials with CREATE granted "for now". If migrations run from CI, hardening GitHub Actions with OIDC to AWS keeps that identity's credentials short-lived. When we review migration practice, most of the incidents we find started in the gaps between these owners, not in the SQL.

11If you meant moving Postgres to a new server or major version

"Zero-downtime Postgres migration" also gets used for moving a database: a new host, a new major version, or into or out of a managed service. That's a different problem. In short: use logical replication to keep a new cluster in sync, then cut over with a brief write pause. Or use a managed equivalent such as Amazon RDS Blue/Green Deployments. Logical replication doesn't replicate DDL or sequence values, so freeze schema changes during the move and set the sequences before cutover. pg_upgrade is faster but needs a downtime window. Note that PostgreSQL 14 reaches end of life on 12 November 2026 (versioning policy), so many teams will be doing exactly this soon.

12FAQ

What lock_timeout should I use for Postgres migrations?

Use the longest stall you'd accept on every query against that table. That's usually 1–3 seconds for busy OLTP tables and up to 5–10 seconds for quiet ones. When it fires, retry with backoff. Repeated timeouts mean a long transaction is in the way. Find and deal with it rather than raising the timeout.

Is ADD COLUMN with a DEFAULT safe in Postgres?

Since PostgreSQL 11, yes, provided the default is non-volatile (a constant, or a stable function such as now()). Postgres stores the value in the catalogue and doesn't rewrite the table. A volatile default such as gen_random_uuid() or clock_timestamp() rewrites the whole table under ACCESS EXCLUSIVE. Add the column without a default, set the default for new rows, and backfill existing rows in batches.

Should Postgres migrations run inside a transaction?

Yes for brief DDL. Transactional DDL means a failed migration leaves nothing half-applied, and a lock timeout can be retried cleanly. The catch is that every lock is held until COMMIT, so never put a slow statement after a lock-taking one in the same transaction. CREATE INDEX CONCURRENTLY, DROP INDEX CONCURRENTLY and REINDEX CONCURRENTLY can't run inside a transaction at all. Give them their own migration file.

How do I tell if an ALTER TABLE will rewrite the table?

Check the lock table above, then confirm on a production-sized copy. Note SELECT pg_relation_filenode('your_table') before and after. If the filenode changes, the table was rewritten. As a rule of thumb: volatile defaults, stored generated columns, and type changes that aren't binary-coercible rewrite. Most other ALTER TABLE forms either scan the table or only touch the catalogue.

Do these rules apply to RDS, Aurora, Cloud SQL, Neon or Supabase?

Yes. Managed Postgres services run the same lock manager, so the lock queue, lock_timeout and CONCURRENTLY behave the same way. What changes is the operational detail: how you see replica lag, whether there is a pooler in front that turns session SETs into a problem, and which extensions (such as pg_repack) you're allowed to install. Check those before your first migration on a new platform.

Can a CREATE INDEX CONCURRENTLY still cause downtime?

Not by blocking reads or writes. It takes SHARE UPDATE EXCLUSIVE, which allows both. It can still hurt in other ways. It adds I/O and CPU load during the build. It waits behind long transactions. If it fails, it leaves an invalid index that slows every write until you drop it. Schedule it off-peak on large tables, and always check for invalid indexes afterwards.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →