Behind a transaction-mode pooler, two workers can both hold a session advisory lock and an unlock can miss. Use transaction locks, a lease row or a session pool.
A lock that two workers hold
Advisory locks are one of PostgreSQL's most convenient tools for coordinating application work. A nightly job that rebuilds the search index for the fictional Belgavi's Book Store takes pg_try_advisory_lock(42) before it starts, and a second copy of the job, started by a retry or a second scheduler, sees false and exits. No table, no row, no cleanup.
Then a connection pooler is added in front of the database, in transaction mode, because the application opens more connections than the server should hold. The job keeps working in testing. In production, two copies run at once, and a week later a third copy can never get the lock even though no job is running. Neither failure produces an error.
This guide explains both failures from the documented semantics of session-level advisory locks and of transaction pooling, shows the sequence in a small model, and gives the replacements that work behind any pooler.
Two kinds of advisory lock
The PostgreSQL documentation (section 13.3.5, Advisory Locks) describes two ways to take an advisory lock:
- At session level, with
pg_advisory_lockorpg_try_advisory_lock. The lock is held until it is explicitly released or the session ends. Session-level requests do not honor transaction semantics: a lock taken in a transaction that rolls back is still held, and an unlock takes effect even if the transaction fails later. A session can take the same lock several times, and each completed request needs a matching unlock. - At transaction level, with
pg_advisory_xact_lockorpg_try_advisory_xact_lock. The lock is released automatically at the end of the transaction, and there is no explicit unlock.
The same section adds a property that matters here: if a session already holds a lock, further requests by that session always succeed, even if other sessions are waiting. Locks belong to the session, which on the server is one backend process behind one connection.
What transaction pooling changes
PgBouncer's documentation describes transaction pooling as assigning a server connection to a client only for the duration of a transaction, and returning it to the pool when the transaction ends. Its feature map lists session-level advisory locks as supported in session pooling and "Never" in transaction pooling, alongside SET/RESET, LISTEN and other session state. Its configuration reference adds that server_reset_query, DISCARD ALL by default, is not used in transaction pooling, because clients are expected not to use session features at all.
Put the two documents together. Each autocommit statement is its own transaction, so each can run on a different backend. A session-level lock is taken by whichever backend ran the statement, stays with that backend after the statement ends, and is visible to whichever client runs on that backend next.
The sequence, in a model
The companion example models two backends, S1 and S2, a transaction-mode pool that hands each transaction the backend that has been idle longest, and two workers, Tanishka and Jenya, running the same job. It encodes the rules quoted above; it is not a run against PostgreSQL or PgBouncer.
- Tanishka calls
pg_try_advisory_lock(42). The statement runs on S1 and returns true. S1 now holds lock 42. - Tanishka's job does its work in a transaction, which runs on S2.
- Jenya calls
pg_try_advisory_lock(42). The statement runs on S1, which already holds the lock, so the request succeeds. Both workers now believe they hold the lock, and both rebuild the index. - Tanishka calls
pg_advisory_unlock(42). The statement runs on S2, which holds nothing; PostgreSQL returns false with a warning. - Jenya's unlock runs on S1 and releases one of the two holds.
S1 is left holding lock 42 once, with no client that knows about it. Any later pg_try_advisory_lock(42) from a transaction that lands on S2 returns false, and one that lands on S1 succeeds, so the job now runs or skips depending on which backend the pooler picks. The lock is released only when S1's server connection closes, which with a pooler may be days later.
With a session pool, the same sequence keeps each worker on its own backend: Jenya is refused, and Tanishka's unlock releases the lock. That is why the code passed every test before the pooler mode changed.
Replacement one: transaction-level locks
If the work that needs mutual exclusion fits in one transaction, take a transaction-level lock at its start:
BEGIN;
SELECT pg_try_advisory_xact_lock(42) AS got_it;
-- if got_it is false: ROLLBACK and exit
-- ... the job's writes ...
COMMIT; -- the lock is released here, on whichever backend ran the transactionIn the model, Tanishka's transaction takes the lock on S1, Jenya's attempt during that transaction runs on S2 and is refused, and Jenya's retry after the commit succeeds. Nothing is left held, because the lock ends with the transaction, and the transaction cannot span two backends.
The limitation is the transaction itself. A job that runs for twenty minutes holds a transaction open for twenty minutes, which keeps old row versions from being vacuumed and holds whatever row locks it has taken. Transaction-level locks are right for short critical sections.
Replacement two: a lease row
For long jobs, use a row that records who owns the work and until when:
CREATE TABLE job_leases (job TEXT PRIMARY KEY, owner TEXT NOT NULL, expires_at TIMESTAMPTZ NOT NULL);
-- take or renew the lease in one statement
INSERT INTO job_leases AS l VALUES ('reindex', 'worker-tanishka', now() + interval '5 minutes')
ON CONFLICT (job) DO UPDATE SET owner = excluded.owner, expires_at = excluded.expires_at
WHERE l.expires_at < now() OR l.owner = excluded.owner
RETURNING owner;A returned row means the caller owns the lease; no row means someone else does. The owner renews before expiry, and every write the job makes should check that it still owns the lease, so a worker that stalled past its expiry cannot keep writing after another has taken over. This works through any pooler, survives restarts, and is visible in a query.
Replacement three: a dedicated session
If you need session-level locks, for example because a migration tool uses them, give that client a direct connection or a separate pool in session mode. Some schema migration tools take a session-level advisory lock to serialize their runs; check yours, because pointing such a tool at a transaction-mode pool reproduces the sequence above.
Choosing lock keys
Advisory locks are identified by one 64-bit integer or by two 32-bit integers, and PostgreSQL attaches no meaning to either. Teams that derive keys by hashing a job name, such as hashtext('reindex'), should remember that unrelated names can collide, and two jobs that never conflict will then serialize, or one will skip because the other is running. The two-integer form gives a cheap namespace: use the first integer for the subsystem and the second for the resource. Record the mapping in code, not in someone's memory, so that whoever later inspects pg_locks can tell what a held key means.
Finding a leaked lock
Advisory locks appear in the pg_locks view with locktype = 'advisory'. Join on pid to pg_stat_activity to see which backend holds one and whether it is idle. An idle backend from the pooler's own user holding an advisory lock is the signature of the leak. Terminating that backend releases its locks; fixing the code is the only thing that stops the leak returning.
Failure modes to test
- Unlock returns false and nobody checks it. Treat a false unlock as an error in logs and metrics.
- A lock taken in a rolled-back transaction is still held at session level. Code that relies on rollback to release it leaks even without a pooler.
- Re-entrancy hides double ownership. Tests with one connection per worker never see it; run them through the pooler with more workers than server connections.
- Prepared statements and session settings break under transaction pooling for the same reason. If advisory locks were in use, look for the others too.
Verification
The companion model's five tests check that transaction pooling lets both workers hold lock 42 on backends S1, S2, S1, S2, S1; that the unlock on the wrong backend fails and one hold leaks; that session pooling keeps mutual exclusion; that a transaction-level lock is released at commit; and that a session pool's DISCARD ALL clears locks on disconnect. Reproduce the sequence against your own PostgreSQL and pooler versions, watching pg_locks, before trusting any of it in production.
Run the example yourself
The model of session and transaction advisory locks behind both pool modes, with five tests. It does not run PostgreSQL. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.