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

Managing Schema Changes and Locks in PostgreSQL

When you change a table, column, constraint, or index in PostgreSQL, the database acquires locks before it applies the change. Those locks control which other queries and writes can run at the same time. If your migration session waits for a lock, or holds one while PostgreSQL does heavy work, application reads and writes can stall.

Before you run a schema change, check which lock PostgreSQL needs and how much work the server will do. Even when PostgreSQL avoids rewriting a large table, your session can still wait behind another transaction, which is a group of SQL statements that PostgreSQL commits or rolls back together. If you build an index concurrently, PostgreSQL lets ordinary writes continue, though the server spends extra time and resources to finish the job. Understanding these trade-offs helps you plan the change, cap how long a session waits for a lock, and spot blocked queries when something goes wrong.

Check which operations conflict with a schema change

PostgreSQL has eight table-level lock modes. When two modes conflict, PostgreSQL cannot grant both locks on the same table at once. An ordinary SELECT takes an ACCESS SHARE lock, while INSERT, UPDATE, DELETE, and MERGE take a ROW EXCLUSIVE lock. Despite its name, ROW EXCLUSIVE is a table-level lock. The PostgreSQL lock reference lists which modes conflict with each other.

Operation Lock behavior
Ordinary SELECT Takes ACCESS SHARE; conflicts only with ACCESS EXCLUSIVE
INSERT, UPDATE, DELETE, MERGE Take ROW EXCLUSIVE
CREATE INDEX Takes SHARE; blocks writes to the table while the index is built
CREATE INDEX CONCURRENTLY Takes SHARE UPDATE EXCLUSIVE; allows ordinary writes but conflicts with some maintenance and schema changes
Many ALTER TABLE forms Take ACCESS EXCLUSIVE, unless the specific form documents a weaker lock

ACCESS EXCLUSIVE conflicts with every other table-level lock, including the one ordinary reads use. PostgreSQL does not require that mode for every ALTER TABLE action, because the lock depends on the specific subcommand. If you combine multiple actions in one ALTER TABLE statement, PostgreSQL takes the strictest lock required by any of them. Check the lock requirements for each ALTER TABLE form before you combine changes.

A session waiting for a lock can also delay sessions that arrive later. If your migration session requests an ACCESS EXCLUSIVE lock and waits behind a long transaction, PostgreSQL queues new conflicting requests behind yours. A small schema change can therefore cause a pileup of blocked queries. Keep each migration focused and avoid bundling unrelated changes into one statement.

Keep the lock-holding transaction short

PostgreSQL normally holds a lock until its transaction ends. Even after PostgreSQL finishes a DDL statement quickly, your session keeps holding the lock while later statements run or while the transaction waits to commit. An idle transaction holds its locks too.

Run your schema change in a short transaction and commit right away. Avoid running unrelated queries or application work between the DDL statement and COMMIT. For a broader look at transaction lifetimes and concurrency, see managing PostgreSQL transactions.

You can set lock_timeout so your migration session stops waiting instead of hanging indefinitely for a lock. PostgreSQL applies that timeout separately to each lock-acquisition attempt. statement_timeout limits the total runtime of a statement, so it controls a different kind of wait or workload. Choose values that match how long your service can tolerate blocked requests, and apply them only to the migration session or transaction. Both settings are covered in the client connection settings.

Distinguish metadata changes from table rewrites

For some schema changes, PostgreSQL only updates metadata; for others, it scans or rewrites the entire table. That difference affects how long the work takes and how many resources the server uses, though PostgreSQL still has to acquire the required lock either way.

In PostgreSQL 19, when you add a column with a non-volatile default, PostgreSQL records the default in metadata and avoids rewriting every existing row. If you use a volatile default such as clock_timestamp(), PostgreSQL may need to rewrite the table and its indexes. Adding a stored generated column or an identity column can also force a rewrite. When you change a column's type, PostgreSQL normally rewrites the table and its indexes as well, with a few documented exceptions in the PostgreSQL ALTER TABLE reference.

When PostgreSQL rewrites a large table, the work can take a long time and the server may temporarily need as much as double the table's disk space. Even when PostgreSQL skips the rewrite, your session still acquires its required lock and holds it until the transaction ends. Before you alter a large table, check which lock PostgreSQL takes and whether it will scan or rewrite existing rows.

When you drop a column, PostgreSQL hides it from SQL queries, though it does not immediately reclaim the physical space it occupied. PostgreSQL frees that space gradually as you update rows, unless a table rewrite happens first. The documentation also warns that some table-rewriting commands are not MVCC-safe for transactions using snapshots taken before the rewrite. Check the exact command and your PostgreSQL version before scheduling a rewrite.

Use concurrent index creation when writes must continue

When you run a regular CREATE INDEX, PostgreSQL lets reads continue, while its SHARE lock blocks writes. When you run CREATE INDEX CONCURRENTLY, PostgreSQL uses a weaker lock so ordinary inserts, updates, and deletes can keep running. That concurrency costs extra work, because PostgreSQL scans the table twice and waits for certain existing transactions to finish. Because the server uses extra CPU and I/O during the build, it can slow down other database activity. See the index creation documentation for the command's restrictions and failure behavior.

PostgreSQL still takes locks during a concurrent build. It allows only one concurrent index build on a table at a time and blocks schema changes to that table until the build finishes. You also cannot run the command inside a transaction block. If the build fails, PostgreSQL can leave an invalid index behind. PostgreSQL ignores invalid indexes when planning queries, yet it still updates them when you modify the table, which adds overhead. If a concurrent build of a unique index fails, PostgreSQL can still enforce uniqueness in some failure cases.

Use CONCURRENTLY to avoid blocking ordinary writes, while keeping in mind that it still affects performance. Plan how you will spot and clean up a failed build, and check what your PostgreSQL major version supports. For example, PostgreSQL 19 does not let you build a partitioned index concurrently in one step. Instead, you build indexes concurrently on each individual partition and then create the partitioned index in a metadata-only step.

Add constraints in stages for large tables

On a large table, you can add a foreign key, which links values to rows in another table, or a check constraint, which requires rows to meet a rule, as NOT VALID. That way PostgreSQL skips scanning all existing rows during the initial command, while still enforcing the constraint on new writes. After you fix any existing violations, you run VALIDATE CONSTRAINT so PostgreSQL checks the older rows.

For example:

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;

PostgreSQL still acquires locks in the first step. In PostgreSQL 19, when you add a foreign key, PostgreSQL takes SHARE ROW EXCLUSIVE locks on both the table receiving the constraint and the referenced table. When you validate the constraint, PostgreSQL takes a SHARE UPDATE EXCLUSIVE lock on the altered table, which allows concurrent updates while it checks existing rows, and a ROW SHARE lock on the referenced table. Other constraint forms use different locks, so check the relevant ALTER TABLE subcommand. NOT VALID postpones the table scan, though PostgreSQL still acquires locks in both steps.

Find blocked sessions and index-build progress

Query pg_stat_activity to find sessions waiting for locks or sitting idle inside a transaction. Its wait-event fields show whether a session is waiting for a lock or actively running a query. Query pg_locks to see outstanding locks, including locks that PostgreSQL has not granted yet. Because PostgreSQL normally stores row-level lock information on disk, a session waiting for a row lock often appears to be waiting for the holder's transaction ID instead. See the documentation for activity and wait events and viewing locks.

A first check for lock waits and idle transactions is:

SELECT pid, state, wait_event_type, wait_event, xact_start, query
FROM pg_stat_activity
WHERE wait_event_type = 'Lock'
   OR state LIKE 'idle in transaction%';

While an index build is running, you can check pg_stat_progress_create_index to see its current phase and progress. The cited progress reference covers PostgreSQL 15, so check the documentation for your deployed major version before relying on version-specific details.

PostgreSQL detects deadlocks, which happen when transactions wait on locks held by each other, and aborts one transaction so another can proceed. The server does not guarantee which transaction it will abort. When your migration touches several tables, acquire locks in a consistent order to reduce the chance of deadlocks.

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 *