Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Postgres performance optimization and best practices guide maintained by Supabase
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/lock-advisory.md
1---2title: Use Advisory Locks for Application-Level Locking3impact: MEDIUM4impactDescription: Efficient coordination without row-level lock overhead5tags: advisory-locks, coordination, application-locks6---78## Use Advisory Locks for Application-Level Locking910Advisory locks provide application-level coordination without requiring database rows to lock.1112**Incorrect (creating rows just for locking):**1314```sql15-- Creating dummy rows to lock on16create table resource_locks (17resource_name text primary key18);1920insert into resource_locks values ('report_generator');2122-- Lock by selecting the row23select * from resource_locks where resource_name = 'report_generator' for update;24```2526**Correct (advisory locks):**2728```sql29-- Session-level advisory lock (released on disconnect or unlock)30select pg_advisory_lock(hashtext('report_generator'));31-- ... do exclusive work ...32select pg_advisory_unlock(hashtext('report_generator'));3334-- Transaction-level lock (released on commit/rollback)35begin;36select pg_advisory_xact_lock(hashtext('daily_report'));37-- ... do work ...38commit; -- Lock automatically released39```4041Try-lock for non-blocking operations:4243```sql44-- Returns immediately with true/false instead of waiting45select pg_try_advisory_lock(hashtext('resource_name'));4647-- Use in application48if (acquired) {49-- Do work50select pg_advisory_unlock(hashtext('resource_name'));51} else {52-- Skip or retry later53}54```5556Reference: [Advisory Locks](https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS)57