Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Migration Locks: Why Tables Block & Safe Patterns

· 7 min read · Home Tech

In this article
  1. Background: How PostgreSQL Locking Works
  2. Why Migrations Block Tables: The Lock Queue
  3. Safer Patterns: Lock Timeouts and Retry Logic
  4. Online Migrations: Minimal Lock DDL
  5. Common Problems and Misconceptions
  6. Comparing Migration Tools and Strategies
  7. Costs and Trade-offs
  8. Frequently Asked Questions

PostgreSQL migration locks block tables because DDL statements like ALTER TABLE take an ACCESS EXCLUSIVE lock, which conflicts with nearly every other operation, including plain SELECT queries. The safe pattern is to avoid long-running transactions around DDL, use LOCK TABLE with a timeout, and prefer online migration tools that minimize lock duration.

Background: How PostgreSQL Locking Works

PostgreSQL uses a multi-granularity locking model where each statement acquires locks at different levels of strength. The key lock modes relevant to migrations are:

  • ACCESS SHARE – taken by SELECT; conflicts only with ACCESS EXCLUSIVE.
  • ROW EXCLUSIVE – taken by INSERT, UPDATE, DELETE; conflicts with SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE.
  • SHARE – taken by CREATE INDEX (non-concurrently); conflicts with ROW EXCLUSIVE and higher.
  • ACCESS EXCLUSIVE – taken by ALTER TABLE, DROP TABLE, TRUNCATE, and VACUUM FULL; conflicts with all other lock modes.

When a migration runs ALTER TABLE, it requests an ACCESS EXCLUSIVE lock. If any transaction is holding a conflicting lock (even a read-only transaction that has started but not finished), the migration waits. Worse, once the migration is waiting, it blocks all subsequent queries on that table, creating a queue that can cascade into a full application outage.

Why Migrations Block Tables: The Lock Queue

Consider a simple migration that adds a column:

BEGIN;
ALTER TABLE users ADD COLUMN age INT;
COMMIT;

If a long-running SELECT is already executing on users, the ALTER will wait for it to finish. While waiting, the ALTER holds a pending ACCESS EXCLUSIVE lock request. New SELECT queries that arrive after the ALTER are queued behind it, even though they would normally not conflict with each other. This is because PostgreSQL’s lock manager processes requests in arrival order, and a waiting exclusive lock blocks all later requests, regardless of compatibility.

The result is a “lock pile-up”: one slow query causes the migration to wait, and the migration’s wait causes every subsequent query to hang. This is the classic reason why migrations “block the table” even when the DDL itself is fast.

Safer Patterns: Lock Timeouts and Retry Logic

The most immediate safeguard is to set a lock timeout before running a migration. This prevents the migration from waiting indefinitely:

SET lock_timeout = '5s';
ALTER TABLE users ADD COLUMN age INT;

If the lock cannot be acquired within 5 seconds, the statement fails with an error. Your migration tool can then retry later, or you can investigate what’s holding the lock. This pattern converts a silent hang into a fast failure, which is much easier to handle in automated deployments.

For interactive sessions, you can also check what’s blocking you with:

SELECT pid, state, wait_event_type, wait_event, query
FROM pg_stat_activity
WHERE datname = current_database();

Look for rows with wait_event_type = 'Lock' and the corresponding pid to identify the blocker.

Online Migrations: Minimal Lock DDL

PostgreSQL provides several DDL operations that avoid ACCESS EXCLUSIVE locks:

  • Adding a column with a default – In PostgreSQL 11 and later, adding a column with a constant default (e.g., ALTER TABLE users ADD COLUMN age INT DEFAULT 0) is a metadata-only operation that takes only a brief ACCESS EXCLUSIVE lock, not a full table rewrite.
  • Creating an index with CONCURRENTLY – CREATE INDEX CONCURRENTLY builds the index without blocking writes, but it still requires a short SHARE UPDATE EXCLUSIVE lock at the start and end.
  • Adding a constraint with NOT VALID – ALTER TABLE ... ADD CONSTRAINT ... NOT VALID adds a check constraint without scanning the table; you can then validate it separately with VALIDATE CONSTRAINT which takes only a SHARE UPDATE EXCLUSIVE lock.

For operations that cannot be done online (e.g., changing a column’s type), you often need to use a tool like pg_repack or londiste that creates a new table, copies data, and swaps it with minimal downtime. These tools are outside the core PostgreSQL distribution but are widely used in production.

Common Problems and Misconceptions

A frequent misconception is that VACUUM or ANALYZE blocks writes. In fact, VACUUM (full) and ANALYZE take SHARE UPDATE EXCLUSIVE locks, which conflict only with ACCESS EXCLUSIVE and other SHARE UPDATE EXCLUSIVE operations. They do not block normal SELECT, INSERT, UPDATE, or DELETE.

Another common issue is running migrations inside a transaction that also performs slow data changes. For example:

BEGIN;
UPDATE users SET name = lower(name); -- takes a long time
ALTER TABLE users ADD COLUMN age INT;
COMMIT;

Here, the UPDATE holds ROW EXCLUSIVE locks on rows, and the ALTER will wait for the entire transaction to finish, blocking all other queries for the duration. Always separate DDL from long-running DML.

Also, beware of ALTER TABLE ... SET DEFAULT or ALTER TABLE ... ALTER COLUMN TYPE – these often rewrite the table and take a long exclusive lock. For large tables, they can cause minutes of downtime.

Comparing Migration Tools and Strategies

Different migration frameworks handle locking differently:

  • Raw SQL migrations (e.g., Flyway, Liquibase) – they execute your SQL as-is; you are responsible for lock timeouts and online patterns.
  • ORM auto-migrations (e.g., Django, Rails) – they generate DDL automatically, but you still need to review the SQL for lock implications.
  • Online schema change tools (e.g., pg_repack, gh-ost for MySQL, but for Postgres there is also pgroll from Xata) – these are designed to minimize downtime by copying data in the background.

For most applications, the best strategy is to combine lock timeouts with explicit online DDL where possible, and to schedule migrations during low-traffic windows. For very large tables, consider using a dedicated tool.

Costs and Trade-offs

The cost of a migration is not just the time it takes, but the impact on availability. An ACCESS EXCLUSIVE lock that blocks all reads and writes for 10 seconds on a busy table can cause thousands of failed requests and trigger cascading failures in dependent services. The cost of using CREATE INDEX CONCURRENTLY is that it takes longer to run and consumes more I/O, but it avoids blocking writes entirely.

Similarly, adding a column with a default in PostgreSQL 11+ is nearly free, but changing a column type can require a full table rewrite, which is both time-consuming and lock-heavy. Understanding these trade-offs helps you choose the right approach for each migration.

Frequently Asked Questions

Why does my ALTER TABLE hang even though the table is idle?

If the table appears idle, check for open transactions that have not committed or rolled back. A transaction that has executed a SELECT and then gone idle in transaction still holds its locks until it commits or aborts. Use pg_stat_activity to find sessions with state = 'idle in transaction' and terminate them if appropriate.

Does adding a column with a default lock the table?

In PostgreSQL 11 and later, adding a column with a constant default is metadata-only and takes a very brief ACCESS EXCLUSIVE lock. The lock is held only for the duration of the catalog change, not for a full table rewrite. However, if you add a column with a volatile default (e.g., now()), it will rewrite the table and lock it for the duration.

What is the difference between ACCESS EXCLUSIVE and SHARE UPDATE EXCLUSIVE?

ACCESS EXCLUSIVE conflicts with all other lock modes, including SELECT. SHARE UPDATE EXCLUSIVE conflicts only with itself, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE. Operations like CREATE INDEX CONCURRENTLY and VACUUM use SHARE UPDATE EXCLUSIVE, so they do not block reads or writes.

Can I use a lock timeout with CREATE INDEX CONCURRENTLY?

Yes, you can set lock_timeout before running CREATE INDEX CONCURRENTLY. However, note that CREATE INDEX CONCURRENTLY can leave an invalid index if it fails, so you need to clean up after a failure.

How do I avoid blocking when changing a column type?

Changing a column type usually requires a table rewrite. To avoid blocking, you can create a new column with the desired type, update it in batches, then drop the old column and rename the new one. This is essentially what online schema change tools do automatically.

Is it safe to run migrations during off-peak hours?

Off-peak hours reduce the chance of conflicting queries, but they do not eliminate them. A single long-running transaction from an application that stays open can still block the migration. Always use lock timeouts and monitor the lock queue, even during off-peak times.