Postgres Advisory Locks in Node.js and NestJS: How We Run Cron Jobs on Exactly One Replica
Table of Contents
About the Author

Ahmed Mahmoud
Author & Developer
Software engineer passionate about web development and user experience design.
Founder of Devya · eng-ahmed.com ↗A Postgres advisory lock is a mutex that an application defines and Postgres enforces, keyed by a 64-bit integer. At Devya we use pg_try_advisory_xact_lock to make Node.js and NestJS cron jobs run on one replica at a time. The transaction-level lock releases itself at COMMIT, ROLLBACK, or disconnect, so the failure modes worth planning for are transaction-mode connection poolers and side effects that leave the database.
Key takeaways
@nestjs/schedule has no cross-instance coordination: every replica that loads the module runs every @Cron() handler, so N replicas mean N runs of every job.
For singleton jobs we call pg_try_advisory_xact_lock(key), which returns false immediately when another session holds the key, so the losing replica skips the run instead of queueing and running the job a second time.
Transaction-level advisory locks work through PgBouncer in transaction mode. Session-level advisory locks do not, and they leak when a pooled connection is returned while still holding one.
When the job's writes run on the same transaction that holds the lock, Postgres commits or rolls back the lock and the writes together.
A lock does not protect side effects outside Postgres. Emails, webhooks, and payment calls still need an idempotency key or a fencing token.
Why does a NestJS @Cron job run twice after scaling to two replicas?
A NestJS @Cron() job runs once per process, because @nestjs/schedule is an in-process scheduler with no state shared between instances. When one of our NestJS APIs went from one container to two, every scheduled job started firing twice in the same minute: two invoice syncs, two digest emails, two cleanup passes competing for the same rows.
We weighed three fixes. A dedicated worker with a replica count of one holds until someone scales it, or until a rolling deploy briefly runs old and new pods together. An external trigger, such as a Kubernetes CronJob calling an endpoint, removes the in-process timer but not the chance of that endpoint being called twice. A lock around the work itself protects the job no matter who triggered it, and because the service already used Postgres, we did not need to add Redis for it.
What is a Postgres advisory lock, and which function should we call?
A Postgres advisory lock is a lock on an application-chosen number rather than on a table or row: Postgres enforces mutual exclusion but gives the key no meaning. The key is one bigint or two integers, and every application connected to the same database shares the key space, so we namespace names such as billing:invoice-sync before hashing them to a key.
pg_advisory_lock(key): session scope, waits if the key is taken, released by pg_advisory_unlock(key) or disconnect.
pg_try_advisory_lock(key): session scope, returns false if the key is taken, released by pg_advisory_unlock(key) or disconnect.
pg_advisory_xact_lock(key): transaction scope, waits if the key is taken, released automatically at COMMIT or ROLLBACK.
pg_try_advisory_xact_lock(key): transaction scope, returns false if the key is taken, released automatically at COMMIT or ROLLBACK.
Two documented behaviours are easy to miss. Session-level advisory locks are reentrant, so a session that takes the same key twice must unlock it twice. And session-level locks ignore transactions: a session lock acquired inside a transaction that rolls back is still held afterwards.
For a cron singleton the blocking variants are wrong. pg_advisory_lock makes the second replica wait for the first and then run the same job again, which is the duplication we set out to remove.
How do we wrap a job in a transaction-level advisory lock with node-postgres?
Our helper checks out one client from the node-postgres Pool, runs BEGIN, calls SELECT pg_try_advisory_xact_lock($1::bigint), and returns early with ROLLBACK when the result is false. Otherwise it runs the job on that same client and commits. Any error triggers ROLLBACK, and the client is always released in a finally block.
We derive the 64-bit key in Node.js from the first 8 bytes of a SHA-256 hash of the lock name, using createHash('sha256') and Buffer.readBigInt64BE(0), and send it as text cast to bigint. That avoids depending on Postgres's internal hashtext() function, which is not part of the documented SQL API.
In NestJS, the @Cron(CronExpression.EVERY_10_MINUTES) handler becomes a thin wrapper: it calls the helper with the lock name and the job, and when the helper reports that the lock was taken, it logs a debug line and returns.
Passing the transaction's client into the job is the important detail. When the job writes through that client, its writes and the lock share one transaction: if the process dies halfway, Postgres rolls back the writes and frees the lock together.
The trade-off is an open transaction that holds one pooled connection for the whole job. That is fine for jobs measured in seconds. For long jobs we use a session-level lock on a dedicated connection instead, particularly where idle_in_transaction_session_timeout is configured.
Why do session-level advisory locks break behind PgBouncer, Neon, or Supabase poolers?
Session-level advisory locks break behind a transaction-mode pooler because the lock belongs to a Postgres server session, and a transaction-mode pooler hands that server session to another client after every transaction. PgBouncer's documentation lists session-level advisory locks as incompatible with transaction pooling, and the same holds for managed transaction-mode poolers such as Neon's -pooler endpoint and Supabase's transaction pooler on port 6543.
Two failures follow. The unlock call can land on a different server session, so pg_advisory_unlock returns false with a warning while the real lock stays held. Or another client's transaction lands on the session that holds the lock, and because advisory locks are reentrant per session, that client's pg_try_advisory_lock succeeds even though the key is already taken.
Without any pooler, node-postgres can still leak a session lock: a client returned to the Pool keeps its locks until that connection closes. Our session-lock helper therefore connects through the direct database URL, unlocks in a finally block, and calls client.release(true) after any error, which closes the connection and frees whatever it still holds.
To see who holds a lock, we query pg_locks joined to pg_stat_activity where locktype = 'advisory'. A bigint key is split into classid (high 32 bits) and objid (low 32 bits), and the expression (classid::bigint << 32) | objid::bigint rebuilds it. Setting application_name on every pool makes the holder obvious.
When should we use a Redis lock instead, and what are fencing tokens for?
We reach for a Redis lock when the work has no shared Postgres database to anchor to. The single-instance Redis lock is SET key token NX PX 30000, released by a Lua script that deletes the key only if it still holds our token. Its weakness is the TTL: if the job outlives it, the key expires and a second worker acquires the lock while the first is still running.
Which lock fits which job?
Advisory transaction lock: short singleton jobs; released when the transaction ends; works through transaction-mode poolers; atomic with the job's database writes.
Advisory session lock: long singleton jobs on a direct connection; released by unlock or disconnect; breaks behind transaction-mode poolers; not atomic with writes.
Redis SET NX PX: cross-service mutex; released by compare-and-delete or TTL expiry; a crashed holder keeps the lock until the TTL runs out.
SELECT … FOR UPDATE SKIP LOCKED: many workers draining a queue table, each claiming different rows; released when the transaction ends. It is a work-queue tool, not a singleton tool.
No lock protects a side effect outside its own system. A network partition, an idle timeout, or an administrator's pg_terminate_backend can end the holder's Postgres session while the Node.js process keeps running, and another replica can start while the first still calls a payment API. Martin Kleppmann's answer is a fencing token, a number that increases with each lock grant and that the downstream system checks so it rejects stale holders. When the downstream API cannot check tokens, we send idempotency keys so a duplicate call does no harm.
FAQ
Q: Do Postgres advisory locks work with Prisma or Drizzle?
A: Yes. Call the lock function with raw SQL inside an interactive transaction, such as tx.$queryRaw inside Prisma's $transaction callback or tx.execute inside Drizzle's db.transaction(). The try_ variants return a boolean that drivers read without trouble, while pg_advisory_lock returns void, which some ORMs fail to map.
Q: Are advisory locks shared across databases on the same Postgres server?
A: No. Advisory locks are scoped to the current database, but every application connected to that database shares one key space, so prefix lock names with the service name before hashing them.
Q: What happens to an advisory lock if the replica holding it crashes?
A: Postgres releases session-level and transaction-level advisory locks when the holding session ends. A process crash closes the socket and frees the lock quickly; a machine that vanishes frees it only once Postgres detects the dead connection, which depends on TCP keepalive settings.
Q: Does a Kubernetes CronJob with concurrencyPolicy: Forbid remove the need for a lock?
A: Only for overlapping runs of that one CronJob. concurrencyPolicy: Forbid does not stop the same work being triggered by an admin endpoint, a retry, or a second scheduler, while an advisory lock guards the work wherever it is called from.
Further Reading
Backend Engineering
Structured Logging in Node.js and NestJS with Pino 10: How We Add Request IDs, Redact Secrets, and Keep Error Stacks
Our Node.js logs were strings we could grep but not query, and one request's lines mixed with everyone else's. We moved our Node.js and NestJS services to Pino 10 structured JSON logs. Here is how we attach a request ID to every line with AsyncLocalStorage, redact the request headers pino-http logs by default, and avoid the argument-order mistake that drops error stacks.
Backend Engineering
Explicit Resource Management in TypeScript and Node.js 24: How We Use using, await using and DisposableStack
Connection leaks usually come from one error path that skipped a release() call. Node.js 24 runs using and await using natively, and TypeScript has compiled them since 5.2. Here is how our team makes database clients, transactions, temp directories and test fixtures disposable, when we use DisposableStack, and the two traps to avoid: SuppressedError and streams that outlive their scope.