Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What are PostgreSQL advisory locks? Explain pg_advisory_lock, pg_try_advisory_lock and pg_advisory_xact_lock, and give one use case where they are better than a row lock.

Advisory locks are locks whose meaning the application decides: we lock a 64-bit number (or a pair of 32-bit numbers) and PostgreSQL tracks who holds it, but never takes one on its own. pg_advisory_lock waits for the lock and keeps it until we unlock it or the session ends, pg_try_advisory_lock returns false at once if someone else holds it, and pg_advisory_xact_lock is released automatically when the transaction ends, which is safer with connection pools. A good use is making sure only one instance runs a scheduled job, without needing a special row to lock.

Why this question is asked

Sometimes what we want to protect is not a row but an activity: run this nightly job once, migrate this tenant only from one place, rebuild this cache entry in one pod. Advisory locks give us a named mutex inside the database we already have. Interviewers ask about them to see whether we know the difference between session and transaction scope, which is where most bugs come from. In this answer, we will recap what an advisory lock is, go through the three functions, look at a scheduled-job example in Spring, compare with row locks, and mention the MySQL and library alternatives.

1A Quick Recap of Advisory Locks

Ordinary locks in PostgreSQL protect tables and rows, and the database takes them automatically when we read or write. An advisory lock protects nothing by itself. It is a lock on a number, and the only thing PostgreSQL guarantees is that two sessions cannot hold it exclusively at the same time. It is advisory because it only works if every participant agrees to take the lock before doing the work; code that skips the lock is not stopped.

The key is either one bigint, such as 42, or two int values, such as (7, 1001), which is handy for namespace plus id. Advisory locks live in PostgreSQL's shared lock table and are visible in pg_locks with locktype = 'advisory'. There are exclusive and shared variants, for example pg_advisory_lock_shared, with the usual rule that shared locks are compatible with each other.

2The Three Functions

pg_advisory_lock(key) waits until the lock is free, then holds it at session level: until we call pg_advisory_unlock(key) or the connection closes. Session locks are re-entrant: if we lock the same key twice, we must unlock it twice.

pg_try_advisory_lock(key) never waits. It returns true and takes the lock if it is free, or false immediately if another session holds it, which is exactly what a scheduler wants: if someone else is already running the job, skip it.

pg_advisory_xact_lock(key), and pg_try_advisory_xact_lock(key), take a transaction-level lock instead, released automatically at commit or rollback; there is no unlock function for them. That is the safer choice behind a connection pool, because the lock cannot outlive the transaction and leak onto a connection that another request borrows next.

SQL
-- session 1
SELECT pg_try_advisory_lock(42); -- true
-- session 2
SELECT pg_try_advisory_lock(42); -- false, returns immediately
SELECT pg_advisory_lock(42); -- waits ...
-- session 1
SELECT pg_advisory_unlock(42); -- true; session 2's call now returns
-- transaction scope
BEGIN;
SELECT pg_try_advisory_xact_lock(42); -- true
COMMIT; -- released automatically
Advisory lock functions
FunctionWaits?Released when
pg_advisory_lockyespg_advisory_unlock or session end
pg_try_advisory_lockno, returns falsepg_advisory_unlock or session end
pg_advisory_xact_lockyestransaction commit or rollback
pg_try_advisory_xact_lockno, returns falsetransaction commit or rollback

3Use Case: One Instance Runs the Scheduled Job

A Spring Boot service runs in four pods, and each has the same @Scheduled method for the nightly invoice run. We want exactly one pod to run it. The job's work is in the same database, so we can wrap it in one transaction that first tries the advisory lock; the pod that gets it runs, the others skip.

Java
@Component
class NightlyInvoices {
private static final long LOCK_KEY = 7_001L; // documented in a shared registry of keys
private final JdbcClient jdbc;
private final InvoiceService invoices;
NightlyInvoices(JdbcClient jdbc, InvoiceService invoices) { this.jdbc = jdbc; this.invoices = invoices; }
@Scheduled(cron = "0 0 2 * * *")
@Transactional
public void run() {
Boolean got = jdbc.sql("SELECT pg_try_advisory_xact_lock(?)").param(LOCK_KEY)
.query(Boolean.class).single();
if (!got) return; // another pod is running it
invoices.generateForYesterday(); // same transaction, lock held until commit
}
}
// pod A: runs; pods B, C, D: got = false, return

Notice that the lock and the work share one transaction, so the lock is released exactly when the work commits or fails. For a job that runs for an hour, one long transaction may not be acceptable; then the job either uses a session lock on a dedicated, non-pooled connection, or a lock table with a lease, as ShedLock does.

4Why This Can Be Better Than a Row Lock

We could get the same effect with SELECT ... FOR UPDATE on a row in a job_lock table. But that needs the table and a row per job to exist, migrations to create them, and the row lock waits by default instead of skipping. An advisory lock needs no schema at all, pg_try_advisory_xact_lock gives skip-if-busy behaviour directly, and it does not touch any data pages, so there are no dead tuples or write-ahead log records from locking.

Advisory locks are also useful for protecting a logical thing that is not a single row, for example all rows of one tenant during a migration step, keyed by (namespace, tenant id). The cost is that the key space is shared by everyone using the database, so keys need a registry or a scheme that avoids collisions between teams.

5Equivalents Outside PostgreSQL

MySQL has named locks: GET_LOCK('nightly-invoices', 0) returns 1 if acquired and 0 if not, with the second argument as the wait in seconds, and RELEASE_LOCK('nightly-invoices') releases it. They are session-scoped, so the same pooling care applies. For Spring applications, the ShedLock library wraps the pattern in an annotation, @SchedulerLock, and stores lock state with an expiry in a table, Redis or other stores, which works across databases and survives pod crashes through the lease.

6Follow-up questions

How do you map a string name to an advisory lock key?

Hash the name to a 64-bit number in a stable way. In the application, take the first 8 bytes of a SHA-256 of the name as a long, which is stable across languages and versions. PostgreSQL's hashtext() is convenient but internal and undocumented, and only 32 bits, so collisions are likelier and its output is not guaranteed to stay the same across major versions. Alternatively, use the two-int form with a fixed namespace number per team and a small id per lock, kept in a registry.

What happens to a session advisory lock if the pod crashes?

When the connection drops, PostgreSQL ends the session and releases its locks. But if the pod freezes while the TCP connection stays open, for example during a long GC pause or a network partition, the lock stays held until the connection is detected as dead, which depends on TCP keepalive settings. That is one reason long-running work prefers leases with expiry.

Can advisory locks deadlock?

Yes. They follow the same rules as other heavyweight locks, so two sessions taking keys 1 and 2 in opposite orders deadlock, and PostgreSQL detects and aborts one as usual. The try variants never wait, so they cannot be part of a deadlock cycle.

7Conclusion

In this answer, we saw that advisory locks are application-defined locks on a 64-bit key, or two 32-bit keys, that PostgreSQL tracks but never takes by itself. pg_advisory_lock waits and holds until unlock or session end, pg_try_advisory_lock returns false immediately when the lock is held, and pg_advisory_xact_lock is released at transaction end, which suits connection pools. They are a schema-free way to make one pod run a scheduled job, and MySQL's GET_LOCK and libraries such as ShedLock offer the same idea elsewhere.

What to say in the interviewAbout 80 seconds aloud

Open with

Advisory locks are locks on a number whose meaning we define. PostgreSQL tracks who holds them, but it never takes one by itself, so they only work if every participant agrees to take the lock first.

Then, if they want more

The key is a bigint or two ints, and they show up in pg_locks as advisory. pg_advisory_lock waits until it gets the lock and holds it for the session, until pg_advisory_unlock or the connection closes, and it's re-entrant, so two locks need two unlocks. pg_try_advisory_lock doesn't wait; it returns false straight away if someone else has it. pg_advisory_xact_lock is scoped to the transaction and released automatically at commit or rollback, which is what I'd use with a connection pool, because a session lock can leak onto a pooled connection.

A typical use is a scheduled job in several pods: in a transaction, call pg_try_advisory_xact_lock with the job's key, and if it returns false, skip. Compared with a row lock, I don't need a lock table or rows, I get skip-if-busy for free, and it writes nothing to data pages.

In MySQL the equivalent is GET_LOCK and RELEASE_LOCK with string names, and ShedLock does the same with a lease table.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What are PostgreSQL advisory locks? Explain pg_advisory_lock, pg_try_advisory_lock and...": https://scrivio-interview-library.netlify.app/databases/database-locking/f1a2ff4e05/