---
title: "Run Schema Migrations Safely"
description: "Apply schema changes to a live Managed PostgreSQL service with lock timeouts, NOT VALID constraints, concurrent indexes and batched backfills."
url: https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/run-schema-migrations-safely/
product: "PostgreSQL"
section: product
last_updated: 2026-11-10
---
> For AI agents: the documentation index is at https://community.exoscale.com/llms.txt. Every page is available as markdown at `<page URL>index.md` or with `Accept: text/markdown`.

# Run Schema Migrations Safely

Apply schema changes to a live service without queueing its traffic behind your DDL, using lock timeouts, `NOT VALID` constraints, concurrent index builds and batched backfills.

## Why DDL Under Load Stalls Traffic

Most forms of `ALTER TABLE` need an `ACCESS EXCLUSIVE` lock on the table. The change itself often
takes milliseconds; the problem is the queue. The `ALTER TABLE` first waits for every transaction
that holds any lock on the table, including a transaction that only read from it and stayed open.
While it waits, every new statement on the table, plain `SELECT`s included, queues behind it.

A schema change that needs a few milliseconds of exclusive access can therefore block all traffic
on the table for as long as the oldest open transaction lasts. While a migration waits, the lock
queue looks like this:

```sql
SELECT pid, granted, mode, left(query, 50) AS query
FROM pg_locks
JOIN pg_stat_activity USING (pid)
WHERE relation = 'orders'::regclass
ORDER BY granted DESC;
```

```text
 pid  | granted |        mode         |                       query
------+---------+---------------------+----------------------------------------------------
 1884 | t       | AccessShareLock     | SELECT count(*) FROM orders;
 1903 | f       | AccessExclusiveLock | ALTER TABLE orders ADD COLUMN discount numeric(10,
 1919 | f       | AccessShareLock     | SELECT count(*) FROM orders WHERE id < 10;
```

Session 1884 finished its `SELECT` but kept its transaction open, session 1903 is the migration,
and session 1919, an ordinary read, waits behind the migration. Who waits for whom:

```sql
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, left(query, 50) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
```

To find and end the session at the root of the chain, see
[Manage long-running queries](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-long-running-queries/index.md#find-what-is-blocking-what).

## Set a Lock Timeout in Every Migration

`lock_timeout` limits how long a statement waits for a lock, and so how long a queue can build up
behind it. Keep it short in migrations: failing and retrying later costs little. Set
`statement_timeout` to `0` at the same time, so that a long step such as `VALIDATE CONSTRAINT` is
not cancelled by a timeout inherited from the role or the database.

Inside a transaction, `SET LOCAL` limits the settings to that transaction:

```sql
BEGIN;
SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '0';
ALTER TABLE orders ADD COLUMN status text NOT NULL DEFAULT 'pending';
COMMIT;
```

When the lock cannot be obtained in time, the statement fails, nothing changes, and the queue
behind it clears:

```text
ERROR:  canceling statement due to lock timeout
```

Retry once the blocking transaction is gone. Without a `lock_timeout`, the `ALTER TABLE` waits as
long as the blocking transaction stays open, and the table's traffic waits with it.

Run migrations on a direct connection to the service. Through a connection pool in transaction
mode, a plain `SET` can stay on a server connection that other clients reuse. See
[Manage connection pools](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-connection-pools/index.md).

## Add Columns Without Rewriting the Table

`ADD COLUMN` without a default, or with a non-volatile default such as a constant, only changes the
catalog: PostgreSQL stores the default once and returns it for existing rows. It takes
milliseconds whatever the size of the table:

```sql
ALTER TABLE orders ADD COLUMN status text NOT NULL DEFAULT 'pending';
```

A volatile default, such as `gen_random_uuid()` or `clock_timestamp()`, needs a different value
per row, so the same statement rewrites the whole table while holding `ACCESS EXCLUSIVE`. The time
grows with the table; on a table of a few million rows, it is several seconds of blocked traffic.

To check whether a statement rewrote the table, compare the table's file number before and after.
It changes on a rewrite:

```sql
SELECT pg_relation_filenode('orders');
```

To get a volatile default without the rewrite, add the column without default, then set the
default, which only applies to new rows. Both are catalog changes:

```sql
ALTER TABLE orders ADD COLUMN external_ref uuid;
ALTER TABLE orders ALTER COLUMN external_ref SET DEFAULT gen_random_uuid();
```

Existing rows keep `NULL` until you backfill them.

## Backfill in Batches

One `UPDATE` over millions of rows locks every row until it commits, produces all its dead rows at
once, and conflicts with concurrent writes. Update bounded batches instead, each in its own
transaction:

```sql
WITH batch AS (
    SELECT id
    FROM orders
    WHERE external_ref IS NULL
    ORDER BY id
    LIMIT 50000
)
UPDATE orders o
SET    external_ref = gen_random_uuid()
FROM   batch
WHERE  o.id = batch.id;
```

Repeat until it returns `UPDATE 0`. Size the batch so that one iteration stays short, and pause
between iterations on a busy service so that autovacuum keeps up with the dead rows.

## Add NOT NULL Without a Long Lock

`ALTER COLUMN ... SET NOT NULL` scans the whole table under `ACCESS EXCLUSIVE`, unless a validated
constraint already proves that the column has no `NULL`. Split the change into a quick catalog step
and a scan that does not block traffic.

On PostgreSQL 18, the default version for new services, a not-null constraint can be added as
`NOT VALID`, then validated:

```sql
ALTER TABLE orders ADD CONSTRAINT orders_external_ref_not_null NOT NULL external_ref NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_external_ref_not_null;
```

The first statement returns immediately and enforces the constraint for new writes: an insert of a
`NULL` fails with `null value in column "external_ref" ... violates not-null constraint`. The
`VALIDATE CONSTRAINT` scans the table under a `SHARE UPDATE EXCLUSIVE` lock, which does not block
reads or writes.

On PostgreSQL 15 to 17, use a check constraint:

```sql
ALTER TABLE orders ADD CONSTRAINT orders_external_ref_check CHECK (external_ref IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_external_ref_check;
ALTER TABLE orders ALTER COLUMN external_ref SET NOT NULL;
ALTER TABLE orders DROP CONSTRAINT orders_external_ref_check;
```

`SET NOT NULL` still takes `ACCESS EXCLUSIVE`, but the validated check constraint lets PostgreSQL
skip the scan, so the lock is held only briefly.

Constraints not validated yet:

```sql
SELECT conname, contype, convalidated
FROM pg_constraint
WHERE conrelid = 'orders'::regclass AND NOT convalidated;
```

## Add Foreign Keys in Two Steps

Adding a foreign key normally checks every existing row while blocking writes on both tables. Split
it the same way:

```sql
ALTER TABLE orders
    ADD CONSTRAINT orders_customer_id_fkey
    FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_id_fkey;
```

The `NOT VALID` step is a short catalog change that enforces the key for new writes. The
validation takes `SHARE UPDATE EXCLUSIVE` on `orders` and `ROW SHARE` on `customers`, so normal
reads and writes continue. If existing rows violate the key, it fails and names one:

```text
ERROR:  insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL:  Key (customer_id)=(50001) is not present in table "customers".
```

Fix the rows and run `VALIDATE CONSTRAINT` again.

## Build Indexes Concurrently

A plain `CREATE INDEX` blocks writes to the table until it finishes. Build indexes on live tables
concurrently:

```sql
CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);
```

`CREATE INDEX CONCURRENTLY` cannot run in a transaction block:

```text
ERROR:  CREATE INDEX CONCURRENTLY cannot run inside a transaction block
```

Most migration tools wrap each migration in a transaction; use their option to disable it for
this migration.

A concurrent build that fails, for example a unique index on a column with duplicates, leaves an
invalid index behind:

```text
ERROR:  could not create unique index "orders_customer_uniq"
DETAIL:  Key (customer_id)=(33779) is duplicated.
```

Find invalid indexes and drop them before you retry:

```sql
SELECT c.relname AS index_name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
WHERE NOT i.indisvalid;

DROP INDEX CONCURRENTLY orders_customer_uniq;
```

For rebuilding existing indexes, see
[Repair and rebuild indexes](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/repair-indexes/index.md).

## Use a Dedicated Migration Role

A migration role gives you one place for safe timeouts, a recognizable name in the logs, and
objects owned by a group role rather than by the last person who deployed. `avnadmin` has
`CREATEROLE` and can set it up (see
[Manage users and databases](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-users-and-databases/index.md)):

```sql
CREATE ROLE app_owner NOLOGIN;
CREATE ROLE migrator LOGIN PASSWORD 'REPLACE_WITH_A_STRONG_PASSWORD' IN ROLE app_owner;
ALTER ROLE migrator SET lock_timeout = '2s';
ALTER ROLE migrator SET statement_timeout = '0';
ALTER ROLE migrator SET idle_in_transaction_session_timeout = '2min';
GRANT CONNECT ON DATABASE DATABASE_NAME TO app_owner;
GRANT USAGE, CREATE ON SCHEMA public TO app_owner;
```

Parameters:

- `DATABASE_NAME`: the database the migrations run in, for example `defaultdb`.

`ALTER TABLE` requires ownership, so hand the tables to the group role:

```sql
ALTER TABLE orders OWNER TO app_owner;
ALTER TABLE customers OWNER TO app_owner;
```

`avnadmin` can do this because a role it creates is granted to it automatically. Every session
that `migrator` opens starts with the three timeouts in place; a statement can still override them
with `SET LOCAL` when a step needs it. The settings apply at login, not after `SET ROLE migrator`.

## Mind idle_in_transaction_session_timeout

The blocking session in the example above, a transaction left open after a read, is what
`idle_in_transaction_session_timeout` ends. Check your value:

```sql
SHOW idle_in_transaction_session_timeout;
```

A new service returns `1d`: a migration session left open in a terminal, or a tool that crashed
between two statements, can hold its locks for a day. The `2min` on the `migrator` role above
avoids that. When the timeout fires, the session is closed and its transaction rolled back:

```text
FATAL:  terminating connection due to idle-in-transaction timeout
```

The timeout only counts time spent idle between statements. A long `VALIDATE CONSTRAINT` or index
build is running, not idle, and is not affected. To change the value for the whole service, see
[Manage long-running queries](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-long-running-queries/index.md#set-idle_in_transaction_session_timeout-for-the-service).

## Rehearse on a Fork

How long each step takes, and which locks it waits for, depends on your data. Run the migration on a
fork of the service first, measure each step, then run the same script on production. A fork is a
separate service built from backups, so the rehearsal does not touch the source. See
[Fork a service and recover to a point in time](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/fork-a-service/index.md).

## Related Pages

- [Manage long-running queries](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-long-running-queries/index.md)
- [Repair and rebuild indexes](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/repair-indexes/index.md)
- [Manage users and databases](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-users-and-databases/index.md)
- [Fork a service and recover to a point in time](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/fork-a-service/index.md)
- [ALTER TABLE in the PostgreSQL documentation](https://www.postgresql.org/docs/18/sql-altertable.html) ↗

