Mastering PostgreSQL Advisory Locks for Application Coordination

Última actualización: 10/05/2026
  • Advisory locks provide a way to coordinate processes using arbitrary 64-bit keys without affecting actual database rows.
  • Transaction-level locks are safer as they auto-release on commit/rollback, while session locks require manual unlocking.
  • Connection poolers in transaction mode can break session locks, making transaction-scoped locks the preferred choice for pooled environments.

Modern data center server racks symbolizing the backend infrastructure where PostgreSQL advisory locks operate.

Ever felt like you needed a lightweight way to coordinate processes without cluttering your database schema with lock tables? That’s exactly where PostgreSQL advisory locks come into play. Think of them as virtual rendezvous points—arbitrary keys that your application agrees to respect to ensure that only one worker is touching a specific resource at a time. Because they are entirely voluntary, the database doesn’t force them on your data; instead, your code handles the logic of when to grab and release them.

Whether you’re trying to stop a cron job from running twice or managing access to an external API that can’t handle concurrency, these locks offer a fast, memory-resident primitive that avoids the overhead of traditional row-level locking. Since they live in shared memory and aren’t written to the WAL, they are incredibly cheap to use, provided you understand the nuances between session and transaction scopes to avoid the dreaded orphaned lock.

PostgreSQL
Related article:
PostgreSQL in the Cloud: Security, Migration, and Performance Evolution

The Core Mechanics: How They Work

Close-up of a secure steel padlock representing the concept of database locking and resource protection.

Advisory locks don’t guard actual tables or rows; they guard conceptual ideas defined by a 64-bit key. You can define this key as a single bigint or a pair of two 32-bit integers. This duality is quite handy because the two-integer version allows you to create a natural namespace—for instance, using the first integer for the “category” of the lock and the second for the specific resource ID.

When a session requests a lock, Postgres checks if that specific key is already held. If it’s an exclusive lock and someone else has it, your request will either block until it’s free or return immediately with a failure, depending on which function you call. You can also use shared locks, which allow multiple sessions to hold the lock simultaneously, but will block any session attempting to acquire an exclusive lock. This is a classic reader-writer pattern implemented directly in your database.

Session vs. Transaction Scopes

Hand holding a padlock, symbolizing the process of acquiring a session or transaction level advisory lock.

Choosing the right scope is where most developers trip up. Session-level locks are long-lived; once you call pg_advisory_lock, that lock stays put until you explicitly call pg_advisory_unlock or the connection drops. This is great for leader election where a process needs to stay “the boss” across many different transactions.

On the flip side, transaction-level locks (acquired via pg_advisory_xact_lock) are much safer for most tasks. They are automatically released the moment your transaction ends, whether it’s via a COMMIT or a ROLLBACK. This eliminates the risk of leaking locks if your application crashes mid-process, making them the gold standard for idempotent job processing.

Rack de servidores con disco extraído en centro de datos con iluminación azul
Related article:
Mastering Managed Relational Databases and NoSQL Alternatives

The Danger Zone: Connection Poolers like PgBouncer

If you’re running your app behind PgBouncer in transaction mode, session-level locks become a nightmare. In this mode, PgBouncer swaps the underlying server connection between transactions. If you acquire a session lock on Connection A, and then your next statement is routed to Connection B, you’ve lost control of your lock, but the database still thinks it’s held. This often leads to phantom deadlocks or jobs that never run because a lock was orphaned on a recycled backend.

To dodge this bullet, you should stick to transaction-level locks when using transaction pooling. If you absolutely must use session locks, you’ll need to configure PgBouncer to session mode, which maintains a strict one-to-one mapping between your client and the server backend.

Practical Implementation Patterns

Developer workspace with code on screen, illustrating the implementation of idempotent job queues using advisory locks.

  • Idempotent Job Queues: Use pg_try_advisory_xact_lock. If it returns true, the worker processes the job; if false, it simply skips it because another worker is already on the case.
  • Distributed Mutex: Use a hashed string (via hashtext) to create a consistent bigint key. This allows different microservices to synchronize on the same resource name without sharing a common ID.
  • Rate Limiting: You can simulate a resource pool by trying to acquire one of several numbered locks (e.g., keys 1001 through 1005) to limit concurrent calls to a flaky external API.

When dealing with complex locking requirements, the Fetch-Lock-Refetch pattern is a lifesaver. Since you might not know exactly what to lock until you read the data, you first perform an unsafe fetch to find your candidates, acquire the locks in a consistent sorted order (to prevent deadlocks), and then refetch the data to ensure it hasn’t changed while you were waiting in line.

Monitoring and Debugging

High-tech digital interface showing system data, representing the monitoring of locks via pg_locks view.

When things go sideways, the pg_locks view is your best friend. By filtering for locktype = 'advisory', you can see exactly which PID holds which key. If you used a bigint key, remember that Postgres might split it across classid and objid, so you may need to reassemble the 64-bit value using bit-shifting to match it back to your application’s keys.

To keep your system healthy, always implement a lock timeout using SET lock_timeout. This prevents your application threads from hanging indefinitely if a lock is held by a zombie process, allowing your app to fail fast and recover rather than slowly grinding to a halt.

Mastering these tools allows you to build highly coordinated distributed systems without the complexity of adding Redis or ZooKeeper to your stack. By balancing session and transaction scopes and remaining mindful of how connection poolers handle backends, you can ensure your application remains race-condition free and performant even under heavy concurrent load.

Related posts: