Sub topic 13
Advisory Locks in PostgreSQL
This chapter assumes you know basic SQL, transactions, primary keys, and foreign keys. You should also be able to use two concurrent psql sessions. Advisory locks are an advanced coordination tool, so first understand the usual row and table locks.
What an advisory lock is
An advisory lock is a lock identified by an application-chosen number. PostgreSQL does not attach that number to a table row or database object. Your application decides what the number means.
For example, an application might use:
42for “the nightly billing job”1001for “account 1001”- A pair such as
(7, 1001)for “tenant 7, account 1001”
Any session that uses the same key follows the same mutual-exclusion rule. PostgreSQL does not know whether the key represents a customer, a file, or a scheduled task.
Advisory locks do not automatically protect rows. A transaction can update a row without acquiring an advisory lock, and PostgreSQL will allow it. Every participating code path must agree to use the same advisory key.
Session-level and transaction-level locks
PostgreSQL provides two important lifetimes:
| Lock type | Common functions | Released when |
|---|---|---|
| Session-level | `pg_advisory_lock`, `pg_try_advisory_lock` | The session ends or explicitly unlocks |
| Transaction-level | `pg_advisory_xact_lock`, `pg_try_advisory_xact_lock` | The transaction commits or rolls back |
Transaction-level locks are usually safer for request processing. They cannot accidentally remain held after a transaction ends.
The blocking form waits until the key is available. The try form returns true or false immediately.
BEGIN;
SELECT pg_try_advisory_xact_lock(42) AS got_lock;
-- If got_lock is true, perform the exclusive work here.
-- If it is false, take another action or return a retry response.
COMMIT;The lock is released automatically by COMMIT, including when the transaction rolls back. A session-level lock requires explicit cleanup:
SELECT pg_advisory_lock(42);
-- Exclusive work for key 42.
SELECT pg_advisory_unlock(42);If a session takes the same session-level lock more than once, PostgreSQL tracks the acquisitions. The lock is released only after the matching number of unlock operations. This is another reason to prefer transaction-level locks.
Choosing and using keys
Choose a stable key that every process can calculate in exactly the same way. Avoid using an in-memory object identity or a value that changes between processes.
For separate namespaces, use the two-integer functions:
BEGIN;
SELECT pg_advisory_xact_lock(7, 1001);
-- Lock key: tenant 7, account 1001
-- Perform work that must be exclusive for this account.
COMMIT;Use one lock order consistently when a transaction needs multiple advisory locks. For example, always acquire account keys in ascending order. Advisory locks can participate in deadlocks just like other locks.
Inspecting advisory locks
Advisory locks appear in pg_locks. The following query lists advisory locks and whether each request has been granted:
SELECT pid,
locktype,
mode,
granted,
classid,
objid
FROM pg_locks
WHERE locktype = 'advisory';The numeric columns identify the advisory key, but their interpretation depends on whether the one-key or two-key function was used. Join this information with pg_stat_activity when you need to identify the SQL and application session involved.
When to use advisory locks
Advisory locks fit work that has no natural row to lock, such as:
- Running one scheduled task per database at a time
- Preventing two processes from rebuilding the same cache
- Serializing changes for an application-defined resource
- Coordinating work across several tables
Keep the protected work short. A long transaction holds its advisory lock for a long time and can create a queue. Define the key scheme, lock lifetime, timeout or retry behavior, and lock ordering as part of the application design.
Exercise
Which function should you normally choose when a lock must be released automatically at the end of the transaction, and what does a false result from its try variant mean?
Show answer
Choose pgadvisoryxactlock or pgtryadvisoryxact_lock. A false result means another transaction or session currently holds the key, and the try function did not wait.