How-to, notes, thoughts

Search

Search loads after the Pagefind index is built into public/pagefind.


Postgres Advisory Locks Are Application Mutexes

Postgres advisory locks are useful when the thing that needs coordination is not a single row. They let an application ask the database to hold a named lock, identified by a 64-bit integer or a pair of 32-bit integers, without creating a table just to represent the lock.

That makes them a clean fit for jobs like “only one worker may refresh this cache key” or “only one deployment task may run for this tenant.” The database already has the shared state, connection pooling, and crash behavior. If the session ends, a session-level advisory lock is released. If the transaction ends, a transaction-level advisory lock is released.

The sharp edge is that advisory locks are only advisory. Postgres will not connect the lock to a row, constraint, or permission check. Every code path that touches the protected resource has to agree on the same locking convention. Miss one path and the mutex becomes theater — very organized theater, but still theater.

A practical pattern is to derive the lock key from a stable namespace plus the resource id, keep the locked section small, and prefer transaction-scoped locks unless a longer session lock is genuinely needed.