← Back to SQL, page 20

sql-0383 · Hard senior

What are PostgreSQL advisory locks, and when are they useful?

Advisory locks are application-defined locks on an arbitrary number, taken with functions such as pg_advisory_lock(key) or pg_try_advisory_xact_lock(key). The database does not tie them to rows; the application decides what a key means. They are handy for 'only one worker runs this job' or serialising work per customer without a dedicated lock table.

Full answer
sql
BEGIN;
SELECT pg_try_advisory_xact_lock(42) AS got_lock;
got_lock
true

pg_try_advisory_xact_lock returns true when the lock was taken and false when another session holds it, without waiting. The _xact_ variant releases automatically at the end of the transaction; session-level locks (pg_advisory_lock) last until explicitly released or the session ends.

Typical uses:

  • Cron jobs on several servers: each tries the lock for 'nightly-report' and only the winner runs.
  • Per-entity serialisation: lock hashtext('customer:' || id) before recalculating that customer's balance.
  • Migrations: tools take an advisory lock so two deploys do not migrate at once.

Cautions: session locks leak if code forgets to release them, and with transaction-mode connection poolers a session lock may stay attached to a pooled connection. Prefer transaction-level locks in pooled setups. SQLite has no equivalent; its single-writer lock covers the whole database.

Key points

  • Locks on application-chosen keys
  • try variants do not wait
  • Transaction-level locks release at commit or rollback
  • Useful for singleton jobs and per-entity serialisation
  • Session locks and poolers mix badly

Common mistakes

  • Forgetting to release session-level locks
  • Using session locks behind a transaction pooler

Follow-ups

  • How would you map a string key to a lock number?
  • How do advisory locks differ from SELECT ... FOR UPDATE?

Tips

  • Contrast session and transaction locks