Most teams reach for Redis (Redlock, SET NX PX) the first time they need to stop two workers from running the same billing sweep, schema migration, or tenant publish job at the exact same moment. Then they inherit a second distributed system, clock-drift caveats, lock TTL expiry mid-work, and split-brain edge cases—all while PostgreSQL is already sitting right there with built-in, memory-backed advisory locks.
A PostgreSQL advisory lock is a fast, application-defined lock stored in Postgres’s shared lock memory (zero disk writes, zero dead tuples, zero vacuum overhead). Used cleanly, it eliminates whole classes of race conditions and lock-upgrade deadlocks. Used carelessly—especially with connection poolers like PgBouncer—it silently leaks locks and stalls workers.
Here is how advisory locks work under the hood, the exact variants to use in production, and the four traps that bite real systems.
Session-level vs. transaction-level advisory locks
PostgreSQL provides two lifetimes and two blocking modes, plus a 64-bit (bigint) or two-32-bit (int, int) key signature:
| Function | Lifetime | Blocking? | Safe with PgBouncer transaction pooling? | Typical use case |
|---|---|---|---|---|
pg_advisory_xact_lock(key) | Auto-released on COMMIT/ROLLBACK | Waits until free | Yes | Serializing concurrent writes per tenant/entity inside a transaction |
pg_try_advisory_xact_lock(key) | Auto-released on COMMIT/ROLLBACK | Returns true/false immediately | Yes | Skipping duplicate short jobs / idempotent webhooks without blocking |
pg_advisory_lock(key) | Held until explicit unlock or disconnect | Waits until free | No (dangerous) | Long-lived leader election on a dedicated direct connection |
pg_try_advisory_lock(key) | Held until explicit unlock or disconnect | Returns true/false immediately | No (dangerous) | Singleton background daemon holding a dedicated non-pooled session |
Default rule: Use pg_advisory_xact_lock or pg_try_advisory_xact_lock 95% of the time. You never have to remember unlock in every error/panic branch, and a rolled-back transaction can never leak a stuck lock.
Pattern 1: Preventing race conditions before a row exists
Row-level SELECT ... FOR UPDATE only locks rows that already exist. When two concurrent requests both check “does tenant X have a draft release?”, both see zero rows, and both try to create one—or upgrade a shared lock into an exclusive lock and deadlock (see the deadlock that only exists when two people publish at once).
Acquiring a transaction-scoped advisory lock on (namespace_id, tenant_id) serializes both requests cleanly before the first SELECT:
BEGIN;
-- Namespace 42 = "release_publish". Uses the (int4, int4) overload
-- so different features can never collide on lock keys.
SELECT pg_advisory_xact_lock(42, hashtext(current_setting('app.tenant_id')));
-- Now only one transaction for this tenant executes this critical section at a time.
SELECT id, version
FROM releases
WHERE tenant_id = current_setting('app.tenant_id')::uuid
ORDER BY version DESC
LIMIT 1;
-- Insert next version, write outbox row, etc.
COMMIT; -- Advisory lock released automatically here
Why the two-argument (int, int) form matters: advisory lock keys live in a single database-wide integer namespace. If your billing job locks user_id = 104 and your export job also locks site_id = 104, they block each other silently. Always reserve a fixed constant integer namespace per feature (or hash a prefixed string with hashtextextended('release:' || tenant_id, 0) into a single 64-bit key).
Pattern 2: Singleton cron / periodic worker without Redis
Suppose you run three replicas of a backend service and only want one replica running a 5-second cleanup sweep at a time, while the other two skip immediately instead of piling up:
BEGIN;
-- Non-blocking check: returns false immediately if another replica holds the lock
SELECT pg_try_advisory_xact_lock(hashtextextended('cron:expired_sessions', 0)) AS acquired;
In your application code (Rust sqlx, Go pgx, Node pg):
- If
acquired == false,ROLLBACKimmediately and sleep until the next tick. - If
acquired == true, run the bounded batch (DELETE ... LIMIT 500), thenCOMMITto release the lock.
Keep the transaction short (milliseconds to a few seconds). Never hold a transaction-scoped advisory lock while making slow third-party HTTP calls—an open Postgres transaction holds back VACUUM horizon cleanup and pins a pool connection.
Pattern 3: Safe leader election for long-running jobs
If a job needs to call external APIs for 2 minutes, do not keep an open database transaction for 2 minutes. You have two clean options:
- Lease row in Postgres (preferred for multi-minute work): Claim a row with
lease_until = now() + interval '60 seconds'inside a 2-millisecond transaction usingFOR UPDATE SKIP LOCKED, close the transaction, do the HTTP work, and renew/complete the row (the exact model behind PostgreSQL vs Redis for background job queues). - Dedicated direct session lock: Open a non-pooled direct connection to Postgres (never through PgBouncer transaction pooling), call
pg_try_advisory_lock(key), and monitor connection health. If the worker crashes (kill -9), TCP teardown closes the Postgres backend session and releases the lock automatically—though TCP keepalive timeouts mean dead-peer detection can take tens of seconds unless tuned.
Four real production traps (and how to avoid them)
1. Session locks + PgBouncer transaction pooling = silent corruption
In PgBouncer pool_mode = transaction, Worker A acquires pg_advisory_lock(99) on backend connection #7, finishes its transaction, and returns connection #7 to the pool with the lock still held. Worker B borrows connection #7—and can re-enter the exact same session lock because PostgreSQL session advisory locks are re-entrant on the same backend session! Even worse, when Worker A later calls pg_advisory_unlock(99), PgBouncer may route that call to connection #12, returning false while connection #7 stays locked until restart.
Fix: Ban session-level pg_advisory_lock on pooled connections. Use pg_advisory_xact_lock exclusively through transaction poolers.
2. Re-entrancy surprises on the same session
Calling pg_advisory_lock(1) twice on the same connection increments a stack counter to 2; calling pg_advisory_unlock(1) once leaves the lock still held. If you use session locks in tests or scripts, prefer pg_advisory_unlock_all() on cleanup—or switch to transaction-scoped locks where COMMIT/ROLLBACK clears all counts cleanly.
3. Acquiring multiple advisory locks in inconsistent order
Just like row locks, advisory locks can deadlock if Transaction A locks (1, 10) then (1, 20) while Transaction B locks (1, 20) then (1, 10). PostgreSQL detects the cycle after deadlock_timeout (default 1 s) and aborts one transaction with SQLSTATE 40P01.
Fix: Whenever a transaction acquires multiple advisory keys (for example, transferring between two accounts), always sort the keys ascending before locking them.
4. Exhausting max_locks_per_transaction
Advisory locks live in PostgreSQL’s shared lock table (max_locks_per_transaction × (max_connections + max_prepared_transactions)). Acquiring one lock per request is cheap; acquiring 50,000 distinct advisory locks inside one giant batch transaction can blow the shared lock table and crash concurrent queries with out of shared memory.
Fix: Lock coarse aggregates (tenant, batch, or account), never tens of thousands of individual rows in one transaction.
Inspecting live advisory locks when something hangs
Every active advisory lock is visible in pg_locks:
SELECT
l.pid,
a.usename,
a.application_name,
a.state,
l.classid,
l.objid,
l.mode,
l.granted,
now() - a.xact_start AS xact_age,
left(a.query, 80) AS query
FROM pg_locks l
JOIN pg_stat_activity a ON a.pid = l.pid
WHERE l.locktype = 'advisory'
ORDER BY l.granted ASC, xact_age DESC;
Look for granted = false (waiters) matched against granted = true on the same (classid, objid) pair—and always set a lock_timeout (e.g., SET LOCAL lock_timeout = '3s') so a stuck peer fails fast with a clean retryable error instead of exhausting your entire connection pool.
Frequently asked questions
What is the difference between pg_advisory_lock and pg_advisory_xact_lock?
pg_advisory_lock holds a session-level lock until you explicitly call pg_advisory_unlock or the database connection closes, and it does not roll back when a transaction aborts. pg_advisory_xact_lock is transaction-scoped: PostgreSQL releases it automatically on COMMIT or ROLLBACK, which makes it far safer with connection pools.
Do PostgreSQL advisory locks work with PgBouncer transaction pooling?
Transaction-level advisory locks (pg_advisory_xact_lock and pg_try_advisory_xact_lock) work safely with PgBouncer in transaction pooling mode because the lock lives strictly inside one transaction. Session-level pg_advisory_lock is dangerous with transaction pooling because the lock can stay pinned on a backend connection handed to another client.
Do PostgreSQL advisory locks block normal SELECT or UPDATE queries?
No. Advisory locks are purely cooperative, application-defined locks stored in PostgreSQL’s in-memory lock table. They only coordinate processes that explicitly agree to acquire the same lock key—regular SQL reads and writes ignore them completely.