Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Implement distributed locks and cron leader election in PostgreSQL using advisory locks. Compare session vs transaction locks and non-blocking try locks.
Quick answer
PostgreSQL advisory locks are application-defined mutexes managed directly by the database engine without locking table rows. Applications use them to coordinate background workers, prevent overlapping cron jobs, and implement distributed leader election using 64-bit application keys.
FAQs
Do PostgreSQL advisory locks lock any tables or rows?
No. Advisory locks operate entirely in shared memory within the PostgreSQL lock manager. They do not read, write, or lock physical table rows.
What happens to an advisory lock if the client connection drops?
PostgreSQL automatically releases all advisory locks (both session-level and transaction-level) held by a connection when the client disconnects.
Can advisory locks cause deadlocks?
Yes. If Session A acquires lock 1 and waits for lock 2, while Session B holds lock 2 and waits for lock 1, PostgreSQL detects the deadlock and aborts one transaction with error 40P01.
Are advisory locks replicated to PostgreSQL read replicas?
No. Advisory locks are local to the primary database instance and do not replicate through WAL streaming to read replicas.
Discover 7 dangerous SQL anti-patterns that degrade query performance and corrupt results. Learn how to refactor non-SARGable predicates and NULL pitfalls.
Compare natural keys, auto-increment surrogate keys, and UUIDs for primary keys. Learn how UUIDv7 and sequential IDs impact B-tree index fragmentation.
Distributed systems often require mutual exclusion: ensuring only one worker processes a billing queue, electing a leader among competing microservices, or preventing concurrent execution of hourly synchronization jobs. Engineering teams frequently deploy external coordination services like Redis (Redlock) or Apache ZooKeeper to manage distributed locks.
If your application already uses PostgreSQL, you already possess a distributed locking service. PostgreSQL advisory locks provide application-level mutexes managed by the database lock manager with zero row-level locking, zero table contention, and zero external infrastructure.
What are PostgreSQL advisory locks?
Standard database locks (SELECT FOR UPDATE, table locks) lock specific physical rows or tables. An advisory lock locks an abstract 64-bit integer or a pair of two 32-bit integers defined entirely by your application.
PostgreSQL does not enforce any meaning on the lock keys. If your application decides that key 42 represents the billing worker, the database simply tracks whether key 42 is currently held. Any other session attempting to acquire lock 42 will either wait or return false. Read our guide on PostgreSQL deadlock detection for lock hierarchy rules.
Session-level vs transaction-level advisory locks
PostgreSQL provides two distinct scopes for advisory locks:
Session-level locks: Held until explicitly released with pg_advisory_unlock() or until the database connection disconnects. They can span multiple transactions.
Transaction-level locks (xact): Acquired within an active transaction and automatically released when the transaction commits or rolls back. They require zero manual release overhead!
Session vs transaction advisory locks
-- 1. Session-level lock: requires explicit unlockSELECT pg_advisory_lock(1001);-- ... perform work ...SELECT pg_advisory_unlock(1001);-- 2. Transaction-level lock (recommended for web applications):BEGIN; -- Automatically released on COMMIT or ROLLBACK! SELECT pg_advisory_xact_lock(1001); -- ... perform work safely ...COMMIT;
According to the PostgreSQL explicit locking documentation, transaction-level locks (pg_advisory_xact_lock) eliminate connection leak risks. If your application crashes or throws an exception, PostgreSQL releases the lock automatically when the transaction closes.
Non-blocking try locks for background cron workers
When scheduling background tasks (such as an hourly email dispatch), you usually do not want a second worker to wait in line if the first worker is still running. You want the second worker to skip execution immediately.
PostgreSQL provides non-blocking try locks: pg_try_advisory_lock() and pg_try_advisory_xact_lock(). These functions return true if the lock was acquired immediately, or false if another worker already holds it.
Non-blocking cron worker pattern in SQL
-- Attempt to acquire exclusive transaction lock for task ID 5001BEGIN;SELECT pg_try_advisory_xact_lock(5001) AS acquired;-- If acquired returns true:-- Worker executes the batch dispatch:UPDATE notification_queueSET status = 'sent', sent_at = now()WHERE status = 'pending';-- If acquired returns false:-- Worker exits immediately without waiting!COMMIT;
Using 64-bit hashtext() for string-based resource locks
Advisory lock functions accept either a single bigint or two integer arguments. If your application locks resources by string identifiers (such as user_uuid or tenant_subdomain), convert the string into a 64-bit integer using hashtext():
Hashing string identifiers into advisory lock keys
-- Lock a specific tenant domain during migrationBEGIN; SELECT pg_advisory_xact_lock(hashtext('tenant_acme_corp')); -- Migration updates for acme corp proceed exclusively...COMMIT;
Monitoring active advisory locks with pg_locks
You can inspect all active advisory locks across your database by querying the pg_locks system view:
Inspecting active advisory locks in pg_locks
SELECT a.pid, a.usename, a.client_addr, l.locktype, l.mode, l.granted, l.objsubid, l.objidFROM pg_locks lJOIN pg_stat_activity a ON a.pid = l.pidWHERE l.locktype = 'advisory';
Actionable checklist for PostgreSQL advisory locks
Prefer transaction-level locks: use pg_advisory_xact_lock to ensure locks release automatically on commit or rollback.
Use try locks for cron jobs: implement pg_try_advisory_xact_lock so redundant cron executions skip gracefully.
Hash string keys: use hashtext(string) to convert text identifiers into 64-bit lock keys reliably.
Monitor active locks: query pg_locks where locktype = 'advisory' to detect stale session locks.
Avoid lock starvation: remember that pg_advisory_lock queues indefinitely until the holding session releases.
Handle disconnect cleanup: be aware that session-level locks remain held until the client connection terminates.
Wrapping up
PostgreSQL advisory locks provide a resilient, distributed locking mechanism built directly into your database engine. By managing background workers and cron tasks with transaction-level advisory locks, you eliminate external locking dependencies while guaranteeing absolute mutual exclusion. Keep your database functions and transaction scripts formatted with sqlfmt.