How-To Guide

How to Use Advisory Locks for Serialization

Serialize application-level work with advisory locks: session versus transaction locks, keying, ordering, and avoiding lock leaks.

On this page

  1. Introduction
  2. What an Advisory Lock Is
  3. Session Versus Transaction Locks
  4. Keying the Lock
  5. Try Versus Wait
  6. Coordination Patterns
  7. Failure Modes and Cleanup
  8. Common Pitfalls and Conclusion

Introduction

Sometimes the thing you must serialize is not a row and not a table; it is an application-level operation, such as a background job that must not run twice, a cache rebuild, or a migration step. Advisory locks let your application acquire a lock by an arbitrary key that the database does not otherwise know about. They are a coordination primitive built into the database, useful exactly when a row lock or a table lock does not express what you need, and dangerous when their session-scoped lifetime is not respected.

What an Advisory Lock Is

An advisory lock is a lock identified by a key you choose, held by a database session, and honoured only by code that also takes the same key. The database does not enforce anything about it; it merely provides mutual exclusion on the key. It is called advisory because it is cooperation, not a constraint.

Because it is cooperative, every participant must agree on the key and take the lock before the protected work. A code path that does the work without taking the lock is not serialized by it. This is the same caveat as any application-level mutex, with the advantage that the lock is visible to all processes sharing the database and is released automatically if a session dies.

-- Acquire a lock on an arbitrary 64-bit key; returns immediately or waits.
SELECT pg_advisory_lock(42001);           -- blocks until acquired
-- ... protected work ...
SELECT pg_advisory_unlock(42001);         -- release

-- Or try without waiting:
SELECT pg_try_advisory_lock(42001);       -- returns true / false at once

Session Versus Transaction Locks

A session-level advisory lock is held until explicitly unlocked or the session ends. A transaction-level lock is released automatically at commit or rollback. Transaction-level is safer because it cannot leak: if an exception aborts the transaction, the lock is released, whereas a session lock held by a process that then throws and returns a pooled connection can leak and block everyone.

Use transaction-level locks when the protected work fits in a transaction, which it usually should. Use session-level locks only when the work spans multiple transactions, and then be rigorous about releasing them in a finally block, because a leaked session lock held by a pooled connection is one of the worst failure modes.

-- Transaction-level lock: released automatically on commit/rollback.
BEGIN;
SELECT pg_advisory_xact_lock(42001);      -- held until end of transaction
-- ... protected work in the same transaction ...
COMMIT;                                    -- lock released here

-- Session-level must be released explicitly; a leak blocks everyone.
SELECT pg_advisory_lock(42001);
-- ... work across transactions ...
SELECT pg_advisory_unlock(42001);         -- MUST run (finally block)

Keying the Lock

Advisory locks are keyed by one 64-bit integer or two 32-bit integers. Choose keys deliberately so different operations do not collide and the same operation uses the same key everywhere, including across application versions. Derive the key from a versioned enumeration or a namespace plus an id, and document it, because a key collision lock-orders two unrelated operations.

For a per-entity lock, use a lock key derived from the entity id, so the lock serializes work for that entity without serializing work for others. Two 32-bit keys make this natural: a namespace integer and the entity id. For a global singleton operation, a fixed key in a dedicated namespace is clear and avoids collisions.

-- Namespaced keys: (namespace, id) to avoid collisions between operations.
-- namespace 1 = "rebuild cache for tenant", id = tenant id
SELECT pg_try_advisory_xact_lock(1, $tenant_id);
-- namespace 2 = "run migration step", fixed id
SELECT pg_try_advisory_xact_lock(2, 0);      -- singleton
-- document each namespace value in code so keys never collide

Try Versus Wait

pg_advisory_lock waits indefinitely for the lock, which can hang a request if the holder is stuck. pg_try_advisory_lock returns immediately with a boolean, letting you decide: skip the work, return a clear busy response, or retry with backoff. For a request path, try-then-decide is almost always better than an indefinite wait.

If you must wait, bound the wait with a statement or lock timeout so a stuck holder fails the waiter instead of hanging it. The combination of a bounded wait and a clear error is what turns a lock contention into a diagnosable event rather than a mystery hang.

-- Bounded wait: fail rather than hang if the lock is not acquired in time.
SET lock_timeout = '2s';
SELECT pg_advisory_lock(42001);   -- errors if not acquired within 2s

-- Or decide explicitly with try:
--   SELECT pg_try_advisory_xact_lock(1, $id);
--   if false: skip/serve a busy response/retry with backoff

Coordination Patterns

Advisory locks are the coordination primitive behind several useful patterns. A single-run job takes a fixed key so only one instance runs it even across a fleet. A per-tenant cache rebuild takes a per-tenant key so tenants rebuild independently. A migration takes a version-keyed lock so concurrent deploys do not both migrate.

They are a building block, not a full distributed lock service: they rely on all participants sharing the same database, and they do not survive a database failover in the same way a dedicated lock service might. Use them for coordination within one database’s ecosystem, and reach for a dedicated system when the coordination spans databases or must be highly available independently.

// Fleet-wide single-run job via a fixed advisory key.
export async function runOnce(db: Db, jobKey: number, fn: () => Promise<void>) {
  await db.transaction(async (tx) => {
    const { rows } = await tx.query('SELECT pg_try_advisory_xact_lock($1) AS got', [jobKey]);
    if (!rows[0].got) return;             // another instance is running it
    await fn();                            // serialized: only one runs
  });                                      // lock released at commit
}

Failure Modes and Cleanup

The worst failure mode is a leaked session lock held by a pooled connection: the process moved on but the lock is still held, and every other instance waits or skips. Always release session locks in a finally block, and prefer transaction locks that cannot leak. Monitor for long-held advisory locks as a signal.

A dead session releases its advisory locks automatically, which is an advantage over application-level mutexes stored in memory. But a session that is idle in a transaction still holds a transaction lock, so a client that opens a transaction and then hangs blocks the lock until the transaction times out or the connection is killed.

-- Find advisory locks and their holders (PostgreSQL).
SELECT l.locktype, l.objid, l.pid, a.usename, a.state,
       now() - a.xact_start AS tx_age, left(a.query, 60) AS query
FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid
WHERE l.locktype = 'advisory'
ORDER BY tx_age DESC NULLS LAST;
-- a long-held advisory lock => a leaked session lock or a hung transaction

Common Pitfalls and Conclusion

Do not use a session lock without releasing it in a finally, or a pooled connection will leak it. Do not let two unrelated operations use the same key. Do not wait indefinitely when try-and-decide would do. Do not treat advisory locks as a distributed lock across databases. And do not forget that a transaction lock is held for the whole transaction, so keep that transaction short.

Advisory locks are the database’s coordinated mutex: a key you choose, honoured by agreement, with a lifetime that follows the transaction or the session. Prefer transaction-level locks so they cannot leak, namespace the keys so they never collide, try before waiting and bound any wait, and monitor for long-held locks. They serialize exactly the application-level work a row lock cannot express.

Test the lock by attempting a concurrent acquisition and confirming it is denied.

Sources: PostgreSQL: Advisory locks, PostgreSQL: pg_advisory_lock, MySQL: GET_LOCK.

FAQ

Session or transaction advisory lock?
Prefer transaction-level: it releases automatically on commit or rollback, so it cannot leak. Use a session-level lock only when the work spans multiple transactions, and always release it in a finally block, because a leaked lock held by a pooled connection blocks every other instance.
Can advisory locks coordinate across multiple databases?
No. An advisory lock is scoped to one database on one server, honoured only by sessions of that database. For coordination across databases or independence from a single database, use a dedicated distributed lock service.

Related Examples