What are advisory locks in PostgreSQL?
Answer
Advisory locks are application-level locks managed by PostgreSQL that your code explicitly acquires and releases — the database doesn't use them automatically. They're useful for ensuring only one process runs a specific task (distributed mutex). Session-level (persist until released or session ends): SELECT pg_advisory_lock(12345); / SELECT pg_advisory_unlock(12345);. Transaction-level (auto-released at transaction end): SELECT pg_advisory_xact_lock(12345);. Non-blocking try: SELECT pg_try_advisory_lock(12345); returns false instead of blocking. Use integer keys; use hashtext('my_lock_name') to convert strings. Advisory locks are stored in memory only and are not logged. Common uses: preventing concurrent cron jobs, distributed leader election, and ensuring single-process batch jobs.
Previous
What is the hstore extension in PostgreSQL?
Next
How does connection pooling work with PostgreSQL?