Video in progress
What is an advisory lock, and when do you use it in a backend?
An advisory lock is a PostgreSQL lock taken on a numeric key, whose meaning the application defines itself. It isn't tied to any row. It's handy when only one of several instances should run a cron job, or to process one resource sequentially.
📖 Answer
There are two kinds:
- session-level:
pg_advisory_lock(key), held until an explicitpg_advisory_unlockor until the connection closes; - transaction-level:
pg_advisory_xact_lock(key), released on its own at commit/rollback.
With a connection pool I almost always use the transaction variant and the try_ form:
@Transactional
public void runNightlyBilling() {
Boolean got = jdbc.queryForObject(
"SELECT pg_try_advisory_xact_lock(hashtext('nightly-billing'))", Boolean.class);
if (!Boolean.TRUE.equals(got)) {
return; // another instance is already running it
}
// ... the work
}
A session lock is dangerous with a pool: the connection goes back to the pool while the lock stays on it, and then another request that gets that connection holds an "unexpected" lock. If you forget the unlock, the lock may not be released even after the instance restarts.
Where else it's useful:
- running operations for one customer sequentially:
pg_advisory_xact_lock(customerId), which works even if no row exists; - making sure only one instance runs migrations at a time: Flyway does exactly that internally with an advisory lock.
Limitations: the key is a bigint or two ints, and if you hash a string there's a chance of collisions. Session locks don't work in PgBouncer's transaction mode. A large number of locks takes space from the shared lock table (max_locks_per_transaction).
Sign up to mark studied questions and save your progress.