Lock Timeout Guards DDL Acquire
Cap how long ALTER TABLE waits for its access-exclusive lock, so a queued migration fails fast instead of stalling every query behind it.
Code
-- ALTER TABLE 需要 ACCESS EXCLUSIVE 锁;若长事务已持有该表上的锁,
-- ALTER 会排队等待,并把排在它后面的所有查询一起堵住
-- lock_timeout 给拿锁等待设上限:拿不到就报错退出,而不是堵死业务
-- 超时报错原文:ERROR: canceling statement due to lock timeout
SET lock_timeout = '2s';
ALTER TABLE orders
ADD CONSTRAINT orders_total_nonnegative
CHECK (total_cents >= 0)
NOT VALID; -- 先快速拿锁登记约束,历史行暂不校验
-- VALIDATE 只拿 SHARE UPDATE EXCLUSIVE,允许并发读写,历史行在此校验
SET lock_timeout = '5s';
ALTER TABLE orders VALIDATE CONSTRAINT orders_total_nonnegative;
-- 会话级设置只影响当前会话:迁移脚本结束后恢复默认
RESET lock_timeout;The queue hazard
ALTER TABLE needs an ACCESS EXCLUSIVE lock. If a long transaction holds any lock on the table, the ALTER queues behind it and every query queued behind the ALTER also stalls — one idle transaction blocks the whole table.
Failing fast
SET lock_timeout = ‘2s’ caps the wait; when the lock cannot be acquired the statement errors out with canceling statement due to lock timeout instead of freezing the queue. The ADD CONSTRAINT … NOT VALID form keeps the lock window short because no existing rows are scanned.
Two-phase validation
VALIDATE CONSTRAINT runs later under lock_timeout = ‘5s’ taking only SHARE UPDATE EXCLUSIVE, which permits concurrent reads and writes while the historical rows are finally checked; RESET lock_timeout restores the session default afterwards.
Interactive Tools for This Topic
FAQ
- Why does NOT VALID matter for the lock window?
- The constraint is registered without scanning existing rows, so the ACCESS EXCLUSIVE phase stays metadata-short; VALIDATE later checks history under a weaker lock.
- What does lock_timeout protect against?
- Unbounded queuing: the ALTER errors out after 2s instead of holding a place in the lock queue that blocks every query behind it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.