Currently Available: Need a skilled Software Developer for your next project?
Categories
Databases PostgreSQL

Best Practices for Safe PostgreSQL Schema Migrations

When you change a PostgreSQL schema in production, the database has to keep serving queries while you roll out new application versions and PostgreSQL updates existing rows. You can run a migration cleanly in a test database and still stall production if PostgreSQL waits for a lock, scans or rewrites a large table, or leaves older application code unable to work with the new schema.

Plan each migration around both the database changes and the application rollout. Check which locks and data changes your SQL requires. Keep transactions that alter the schema short, and run large backfills separately. A backfill is a job that updates existing rows over time. Following these practices reduces disruption, though you cannot prevent every impact. The examples below follow PostgreSQL 18 documentation, so check the behavior for the version you run.

Check locks, scans, and rewrites before deploying

You can disrupt production with a single short SQL command. Before you run a migration, find out which lock the command needs, whether PostgreSQL will scan existing rows, and whether it will rewrite the table or its indexes. PostgreSQL generally takes an ACCESS EXCLUSIVE lock for ALTER TABLE unless the specific operation documents a different lock. That lock conflicts even with the ACCESS SHARE lock that ordinary SELECT queries use, so when PostgreSQL waits to acquire it, other requests can back up in a queue behind it. Check PostgreSQL’s lock behavior and the ALTER TABLE reference for the exact command you plan to run.

Keep schema changes in short transactions. PostgreSQL holds a lock until the transaction ends, so if you put a long-running backfill in the same transaction, PostgreSQL keeps the schema lock in place far longer than the schema change itself needs. Check whether your migration runner, the tool that applies migrations, wraps each migration in a transaction. This matters especially when a command has special transaction requirements. For more on the operational trade-off, see why short transactions matter.

In a migration session, you can set lock_timeout to limit how long a statement waits to acquire a lock and statement_timeout to cap how long it runs. These two settings solve different problems. PostgreSQL advises against setting lock_timeout to the same duration as, or longer than, a nonzero statement_timeout. Set them only for migration sessions rather than imposing migration-specific limits on all database users. The values below are examples, not universal defaults:

BEGIN;
SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '15min';

ALTER TABLE orders ADD COLUMN source text;

COMMIT;

Choose limits based on your latency goals, table activity, and expected migration runtime. If PostgreSQL aborts a statement because it exceeded lock_timeout, investigate the blocking queries and retry in a safer window instead of extending the wait. PostgreSQL documents both settings in its client connection defaults.

Avoid unexpected table rewrites

A small-looking schema change can force PostgreSQL to do a lot of work. In PostgreSQL 18, when you add a column with a non-volatile default, such as a fixed text value, PostgreSQL does not need to rewrite every existing row. When you use a volatile default, such as clock_timestamp(), which can return a different value each time PostgreSQL calls it, PostgreSQL may have to rewrite the table and its indexes. When you change an existing column’s type, PostgreSQL normally rewrites the table and its indexes, subject to documented exceptions. Check the PostgreSQL table-modification behavior for the exact type and command.

If historical rows need different values, add the column without a default and populate it separately. You keep the schema change separate from the data work, though your application must also supply values for new rows during the transition. Test version-specific behavior on the PostgreSQL release you deploy; do not assume PostgreSQL 18’s documented behavior applies unchanged to older releases or to every command.

Build indexes without blocking writes

When a production table needs a new index, consider CREATE INDEX CONCURRENTLY. If you run a regular CREATE INDEX, PostgreSQL blocks writes while it builds the index. If you run CREATE INDEX CONCURRENTLY, PostgreSQL lets inserts, updates, and deletes continue, though it takes longer, scans the table twice, and waits for certain existing transactions to finish. PostgreSQL permits only one concurrent index build on a table at a time, and you cannot run the command inside a transaction block. The CREATE INDEX documentation covers these limits.

Make sure your migration runner does not wrap the command in a transaction. If CREATE INDEX CONCURRENTLY fails, PostgreSQL can leave an invalid index behind, so inspect the database before you retry and drop or rebuild the invalid index as appropriate. If a concurrent unique-index build fails, take extra care: PostgreSQL can start enforcing uniqueness before the index becomes fully available, and an invalid index left behind can still enforce uniqueness.

PostgreSQL reports progress for index creation in its progress reporting views. Watch those views alongside your query and lock monitoring; running the build concurrently reduces a specific kind of blocking, but PostgreSQL still spends time and database resources on the work. For more detail on how this works internally, see how PostgreSQL handles concurrent index creation.

Add constraints in stages

When you add a constraint directly, PostgreSQL may have to check every existing row, which slows the change down on a large table and restricts other updates until it finishes. For a foreign key, which links a value in one table to a row in another, or a check constraint, which requires table values to meet a rule, you can add NOT VALID to skip the initial check of historical rows while PostgreSQL still enforces the rule on later inserts and updates. You can then validate existing rows separately with VALIDATE CONSTRAINT, which lets PostgreSQL use a less restrictive lock. When PostgreSQL validates a foreign key, it also takes a lock on the referenced table.

ALTER TABLE orders
    ADD CONSTRAINT orders_customer_fk
    FOREIGN KEY (customer_id) REFERENCES customers (id)
    NOT VALID;

ALTER TABLE orders
    VALIDATE CONSTRAINT orders_customer_fk;

NOT VALID means PostgreSQL has not checked old rows yet; it does not exempt new or updated rows. Confirm that existing data satisfies the rule before you validate it, and account for the referenced table when you plan foreign-key validation.

To make a column required, let new writes supply a value while you update old rows. Add the column as nullable, deploy code that provides a value, and add a CHECK (column IS NOT NULL) NOT VALID constraint so PostgreSQL rejects new nulls. Then update existing rows that have nulls, validate the check, and set the column to NOT NULL. Once the check confirms that no nulls remain, PostgreSQL can skip the table scan that SET NOT NULL would otherwise require. Finish the backfill before you validate the check. Once the check is in place, updates to old rows that still contain nulls can fail. Verify this sequence for your PostgreSQL version and table.

Backfill large tables separately

Update large sets of existing rows in batches with a limit on how many rows each batch handles, and commit after each batch. If your worker saves a stable key or cursor, a marker of how far it has progressed, it can resume after a failure without scanning the whole table again. Assign someone to own the job, track its progress and failures, and build in a way to pause or retry it. Watch how the job affects production traffic.

Even when you run a backfill asynchronously, it still consumes database resources and still needs a clear completion condition. No universal batch size or row-count threshold makes a backfill safe, so choose and adjust the batch size based on your workload and the impact you observe. GitLab’s batched background migration guidance shows one way to run long data changes separately from schema migrations, though its framework-specific approach is not a PostgreSQL requirement.

Keep old and new application versions compatible

Application instances switch to a new release at different times. For a rename, type conversion, or other change that could break code using the old structure, keep both forms available while you roll out the new release:

  1. Add the new column or structure while retaining the old one.
  2. Deploy code that can work with both forms and writes the new value.
  3. Backfill historical rows.
  4. Switch reads to the new form and verify the results.
  5. Remove the old form in a later migration after deployed code and delayed jobs no longer use it.

When you add the new structure before removing the old one, you have to maintain temporary schema and code, but application instances can switch at different times. Treat cleanup as a separate deployment decision: dropping a column removes its data, so confirm that nothing needs the old value anymore and that your rollback plan does not depend on it. GitLab’s migration style guidance also separates schema changes from long-running data work.

Monitor the migration and inspect failures

Test the migration on data that reflects your production data, and confirm that the tool applying it handles transactions the way the PostgreSQL command requires. While the migration runs, inspect active queries and lock waits through pg_stat_activity. PostgreSQL provides progress reporting for some operations, including index creation, though not every migration has a built-in progress indicator.

If a migration fails, check the database instead of assuming PostgreSQL rolled back every change. If CREATE INDEX CONCURRENTLY fails, PostgreSQL can leave an invalid index behind, and other migrations may have already completed earlier steps before an error stopped later work. Record what the database contains before you retry so your next attempt does not duplicate work or overlook an incomplete change.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *