← Lessons

quiz vs the machine

Silver1120

Databases

Advisory Locks

Application defined locks coordinate logic the database cannot see in the data.

4 min read · intro · beat Silver to climb

Locks With No Rows

Normal locks protect rows and tables the database knows about. An advisory lock is a lock on an arbitrary key chosen by the application. The database enforces mutual exclusion on that key but attaches no meaning to it. The meaning is an agreement between application instances.

Why Use Them

  • Coordinate work that is not tied to a single row, like ensuring only one worker runs a nightly job.
  • Build a simple distributed mutex using the database you already have, avoiding a separate lock service.
  • Serialize an external side effect, such as calling a rate limited API, across many app servers.

Session Versus Transaction Scope

  • Session level advisory locks are held until explicitly released or the connection ends.
  • Transaction level advisory locks release automatically at commit or rollback, which is safer because a crash frees them.

The Caveat

Advisory locks are cooperative. Nothing forces code to ask for the lock before doing the work. If one code path takes the lock and another ignores it, the protection is gone. They also bind a worker to a database connection, so connection poolers need care.

Key idea

Advisory locks let applications lock arbitrary keys for coordination, but they are cooperative so every code path must honor the same lock.

Check yourself

Answer to earn rating on the learn ladder.

1. What does an advisory lock protect?

2. Why is a transaction level advisory lock often safer than a session level one?

3. What is the main risk of advisory locks?