PostgreSQL Advisory Lock Critical Section
Serialize critical sections across application instances with advisory locks, scoping by key and releasing on session end.
Code
-- PostgreSQL 会话级咨询锁:try 锁拿不到立即返回假
SELECT pg_try_advisory_lock(4271);
-- 若返回 true,此会话独占编号 4271 的锁
-- 其他实例的尝试会得到 false:
SELECT pg_try_advisory_lock(4271); -- false:已被占用
-- 临界区:只有一个实例在执行对账
BEGIN;
SELECT pg_advisory_xact_lock(4271); -- 事务级:提交或回滚自动释放
UPDATE reconciliation_runs
SET started_at = now(), status = 'running'
WHERE id = 'nightly-2026-10-21';
-- ... 对账主体 ...
UPDATE reconciliation_runs
SET finished_at = now(), status = 'done'
WHERE id = 'nightly-2026-10-21';
COMMIT; -- 锁随事务结束自动归还
-- 会话级锁的显式释放路径
SELECT pg_advisory_unlock(4271);
-- 双键形式:类目 ID 加实体 ID 组合编号
SELECT pg_try_advisory_lock(4271, 42);
-- 锁状态观测
SELECT pg_locks.locktype, pg_locks.objid, pg_locks.granted
FROM pg_locks
WHERE locktype = 'advisory';How the snippet works
The file runs SELECT / UPDATE statements, touching reconciliation_runs and pg_locks.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects.
Applying it
Run the statement against the reconciliation_runs table.
Statements that matter
SELECT pg_advisory_xact_lock(4271); -- 事务级:提交或回滚自动释放
UPDATE reconciliation_runs
SET started_at = now(), status = 'running'
WHERE id = 'nightly-2026-10-21';
SELECT pg_locks.locktype, pg_locks.objid, pg_locks.granted
FROM pg_locks
WHERE locktype = 'advisory';
UPDATE reconciliation_runs
SET finished_at = now(), status = 'done'
WHERE id = 'nightly-2026-10-21';
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Which tables appear in this script?
- `reconciliation_runs`, `pg_locks`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.