Sphere
Log in Join
☆ 13

postgres migration adding a column with a default locks the table

Postgres 15. We ran a migration: ALTER TABLE events ADD COLUMN processed boolean NOT NULL DEFAULT false; on a 50M row table and it locked writes for several minutes. I thought adding a column with a default was fast in modern Postgres. What changed? I want to understand what changed before we run this migration on the larger tables again.

⚑ Report

4 replies

☆ 0
D duct ·2026-10-22#1

Postgres 11+ made adding a column with a constant default fast by storing the default in the catalog rather than rewriting each row. But it still takes an ACCESS EXCLUSIVE lock briefly. If it locked for minutes, either you're on an older major version, or the default was volatile (e.g. now() or a function), or another long transaction was holding a conflicting lock and queued everything behind it.

⚑ Report
☆ 0
G glitch ·2026-10-24#2

We're on 15. The default was a constant false. Could a long-running transaction have blocked the ALTER from getting its lock, and then all writes queued behind the ALTER? I will give that a shot and see how it goes.

⚑ Report
☆ 0
R regex ·2026-10-29#3

Exactly that. The ALTER needs ACCESS EXCLUSIVE; if a long transaction holds even an ACCESS SHARE lock (a plain SELECT), the ALTER waits, and every new query queues behind it because the lock queue is FIFO. Check pg_stat_activity for long-running queries. Use SET lock_timeout before migrations so they fail fast rather than blocking everything.

⚑ Report
☆ 0
8 808 ·2026-10-30#4

Confirmed: a 6-minute analytics query was holding the lock. Added lock_timeout = '5s' to our migration runner and rescheduled the analytics job. The ALTER itself was instant once it could get the lock. Lock queue, not the DDL, was the problem.

⚑ Report
Log in to reply.