Sub topic 13
Advisory locks
This chapter assumes you know how row-level and table-level locks behave, how a lock waits in the queue, and how to read pg_locks. You also need two psql sessions to try the examples.
What an advisory lock is
An advisory lock is a lock that PostgreSQL stores and arbitrates but never attaches to any data. Table locks protect tables and row locks protect rows. An advisory lock protects a number that your application chooses, and what that number means is up to you. Examples are "the nightly invoice run", "customer 7's import" or "the schema migration".
PostgreSQL only guarantees this: two sessions cannot hold conflicting advisory locks on the same key at the same time. It does not check that the key relates to anything, and it does not stop code that never asks for the lock. That is why the locks are called advisory.
Use them when you need mutual exclusion that does not map cleanly onto rows:
- Only one copy of a scheduled job runs at a time.
- Work on one customer is serialized, even though it touches many tables.
- One process at a time runs a migration or a cache rebuild.
- A resource lives outside the database, such as a file or an API quota, and you want the database to arbitrate access.
Advisory locks have two advantages over a lock on a dummy row. They do not create row versions, so they cause no table bloat. They also do not conflict with VACUUM or with ordinary queries on any table.
Keys
A key is either one bigint or two integer values. These are separate key spaces: pg_advisory_lock(1, 2) never conflicts with pg_advisory_lock(8589934594).
The two-integer form fits a namespace plus an identifier. The first integer says what kind of work it is, and the second says which instance.
-- Namespace 1001 = "customer import", 7 = customer id
SELECT pg_advisory_xact_lock(1001, 7);To lock on a string, hash it to a bigint. hashtextextended(text, seed) is available in PostgreSQL 11 and later.
SELECT pg_advisory_xact_lock(hashtextextended('invoice-run:2026-11', 0));Keys are global to the database. Every application connected to the same database shares one key space. If two unrelated services both use pg_advisory_lock(1), they block each other. Agree on a namespace convention, such as a fixed first integer per feature.
Hash collisions are possible with 64-bit hashes, though rare. A collision causes unnecessary waiting but no incorrect behavior.
Transaction-level and session-level locks
Each function comes in two forms with different lifetimes.
| Form | Example | Released |
|---|---|---|
| Transaction-level | `pg_advisory_xact_lock(key)` | Automatically at `COMMIT` or `ROLLBACK`. There is no unlock function. |
| Session-level | `pg_advisory_lock(key)` | By `pg_advisory_unlock(key)`, `pg_advisory_unlock_all()`, or when the session ends. Transaction boundaries do not affect it. |
Each form also has variants:
- Blocking:
pg_advisory_lockwaits until the lock is free. - Non-blocking:
pg_try_advisory_lockreturnstrueorfalseimmediately. - Shared: the
_sharedvariants, such aspg_advisory_lock_shared, conflict with exclusive locks on the same key but not with other shared locks. This works likeFOR SHAREversusFOR UPDATE.
Prefer the transaction-level form when you can. It cannot leak, because a rollback or a dropped connection always releases it. The session-level form needs a matching unlock on every code path, including error paths.
The try-lock pattern
The non-blocking form suits jobs where "someone else is already doing it" is an acceptable answer.
BEGIN;
SELECT pg_try_advisory_xact_lock(42) AS got_lock;
-- if got_lock is true, run the exclusive work
COMMIT; -- the advisory lock is released automaticallyIf got_lock is false, the application skips the work and ends the transaction. Skipping avoids a pile of workers all queued behind the first one.
Session-level locks stack
The same session can take the same session-level lock more than once without blocking itself. PostgreSQL counts the requests, and the lock is released only after the same number of unlocks.
SELECT pg_advisory_lock(42);
SELECT pg_advisory_lock(42);
SELECT pg_advisory_unlock(42); -- true, but the lock is still held once
SELECT pg_advisory_unlock(42); -- true, now released
SELECT pg_advisory_unlock(42); -- false, with a warning: you don't own a lockSession-level locks ignore transactions entirely. A rolled-back transaction does not release them, and neither does a savepoint rollback. This is the usual source of "the lock is still held" surprises.
BEGIN;
SELECT pg_advisory_lock(42);
ROLLBACK;
-- The lock on 42 is still held by this session.Transaction-level locks behave differently under savepoints. A lock taken after a savepoint and then rolled back with ROLLBACK TO is released, like other locks taken in the aborted subtransaction.
Advisory locks and connection poolers
Session-level locks belong to a server connection, not to your application's logical session. A pooler in transaction mode, such as PgBouncer, hands a server connection to a different client after each transaction. This causes two failures:
- Your
pg_advisory_unlockmay run on a different server connection from the one that took the lock, so it fails and the lock stays held. - Another client may get the connection that still holds your lock. That client then owns a lock it did not ask for, and it can unlock it by accident.
With transaction pooling, use only pg_advisory_xact_lock and its variants. They live and die inside one transaction, which stays on one server connection.
Seeing advisory locks
Advisory locks appear in pg_locks with locktype = 'advisory'.
SELECT pid, classid, objid, objsubid, mode, granted
FROM pg_locks
WHERE locktype = 'advisory';The key is split across columns:
- For a single
bigintkey,objsubidis1.classidholds the high 32 bits andobjidthe low 32 bits. - For a two-integer key,
objsubidis2.classidis the first integer andobjidis the second.
Waiting sessions show granted = false, so the blocked-session query from the earlier chapter on finding blockers works unchanged. pg_blocking_pids() reports advisory-lock blockers like any others. A waiting session has wait_event_type = 'Lock' and wait_event = 'advisory' in pg_stat_activity.
Limits and timeouts
Advisory locks use the same shared-memory lock table as table locks. The table has room for roughly max_locks_per_transaction * (max_connections + max_prepared_transactions) entries. A job that takes a million advisory locks can exhaust it and fail with "out of shared memory". Take locks per unit of work, not per row of a large batch.
The blocking forms obey lock_timeout, so a wait can be bounded the same way as a table lock wait.
BEGIN;
SET LOCAL lock_timeout = '3s';
SELECT pg_advisory_xact_lock(42); -- fails with SQLSTATE 55P03 after 3 seconds
COMMIT;Advisory locks can also deadlock. Two sessions that take keys 1 and 2 in opposite order form a cycle, and the deadlock detector aborts one of them after deadlock_timeout, exactly as for row locks. The remedy is the same: always take advisory locks in a fixed order. The detector cannot see waits that happen outside the database, so a cycle that passes through an external resource still hangs.
Pitfalls
Calling a lock function in a WHERE clause
It is tempting to claim work with a single query:
SELECT id
FROM jobs
WHERE status = 'pending' AND pg_try_advisory_lock(id)
LIMIT 1;This is unsafe. The planner decides when the function runs. It may call it for rows that LIMIT later discards, and those rows stay locked at session level with no one holding the result. Use FOR UPDATE SKIP LOCKED for job queues instead, as shown in the NOWAIT and SKIP LOCKED chapter. If you need advisory locks, fetch the candidate id first, then lock it in a separate statement.
Forgetting that nothing enforces the lock
A code path that skips the lock call is not blocked. Put the locking step in one shared function or helper, and do not scatter raw pg_advisory_lock calls through the code.
Relying on an advisory lock for data integrity
If a rule must always hold, such as "only one active subscription per user", use a constraint or a row lock. Advisory locks suit coordination between cooperating processes, not enforcement against every possible writer.
Leaked session-level locks
A long-lived worker that crashes without cleanup is not a problem, because the lock disappears with the connection. A long-lived worker that stays up but forgets to unlock holds the key indefinitely. When you must use session-level locks, release them in a finally block or its equivalent, and call pg_advisory_unlock_all() before returning a connection to a pool.
Choosing a lock type
| Need | Use |
|---|---|
| Serialize work around a few rows | Row locks (`FOR UPDATE`) |
| Serialize work across many tables or an external resource | Advisory lock |
| Run a job only if nobody else is running it | `pg_try_advisory_xact_lock` |
| Hold a lock across several transactions | Session-level advisory lock, with a direct (non-pooled) connection |
| Claim distinct queue items | `FOR UPDATE SKIP LOCKED` |
Exercise
A scheduled report job runs every minute, and a run can take several minutes. You want a second run to exit immediately if one is already running. Your application connects through PgBouncer in transaction pooling mode. Which advisory lock call do you use, and why not pg_advisory_lock?
Show answer
Use pg_try_advisory_xact_lock(key) inside a transaction that spans the job, and exit if it returns false. With transaction pooling, the session-level pg_advisory_lock stays on whichever server connection took it, and the matching pg_advisory_unlock may run on a different connection. The lock then leaks or is released by the wrong client. The transaction-level form is released at commit or rollback on the same connection. The non-blocking variant also lets the second run exit at once instead of queueing.
Exercise
Session A runs SELECT pg_advisory_lock(5); twice and then SELECT pg_advisory_unlock(5); once. Session B then runs SELECT pg_try_advisory_lock(5);. What does B get, and what changes the result?
Show answer
B gets false. Session-level locks stack, so A still holds the lock once after one unlock. B gets true only after A runs a second pg_advisory_unlock(5), calls pg_advisory_unlock_all(), or disconnects.
Exercise
How do you find which sessions hold advisory locks, and how do you tell a lock taken with one bigint key from one taken with two integers?
Show answer
Query pg_locks where locktype = 'advisory'. A one-bigint key has objsubid = 1, with the key split across classid (high 32 bits) and objid (low 32 bits). A two-integer key has objsubid = 2, with the first integer in classid and the second in objid. Rows with granted = false are waiting sessions.