Distributed Task Scheduling in NestJS with PostgreSQL Advisory Locks
How to execute reliable, concurrency-safe cron jobs and scheduled article releases across multi-instance server clusters without distributed deadlocks.
When scaling backend microservices across multiple container replicas (e.g., Kubernetes or AWS ECS), standard in-memory scheduling mechanisms like @nestjs/schedule or node-cron introduce dangerous concurrency bugs. Every running instance triggers the cron job simultaneously, causing duplicate invoice billing, duplicated emails, or race conditions during scheduled content publishing.
In this guide, we walk through building a resilient, distributed task scheduler using PostgreSQL Session-Level Advisory Locks.
1. What Are PostgreSQL Advisory Locks?
Unlike table or row locks (FOR UPDATE), which lock concrete table records during transactions, PostgreSQL Advisory Locks are application-defined mutexes managed entirely in Postgres memory:
- They are fast (zero disk I/O).
- They can be non-blocking using
pg_try_advisory_lock(bigint). - If an instance acquires the lock, all other competing instances skip execution immediately rather than hanging in queue.
-- Non-blocking lock acquisition
SELECT pg_try_advisory_lock(84920482019482);
-- Returns true if lock acquired, false if another instance holds it
2. Implementing the Distributed Scheduler Service
Here is our production BlogScheduler implementation in NestJS, ensuring that scheduled articles are published exactly once across distributed server fleets:
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
const SCHEDULER_LOCK_ID = 91827364528192n;
@Injectable()
export class BlogScheduler {
private readonly logger = new Logger(BlogScheduler.name);
constructor(private prisma: PrismaService) {}
@Cron(CronExpression.EVERY_MINUTE)
async handleScheduledPublishing() {
// Attempt non-blocking distributed lock acquisition
const lock = await this.prisma.$queryRaw<{ acquired: boolean }[]>`
SELECT pg_try_advisory_lock(${SCHEDULER_LOCK_ID}) AS acquired
`;
if (!lock[0]?.acquired) {
this.logger.debug('Another instance is currently executing the publishing sweep.');
return;
}
try {
const now = new Date();
const duePosts = await this.prisma.blog.findMany({
where: {
status: 'SCHEDULED',
scheduledAt: { lte: now },
},
});
for (const post of duePosts) {
await this.prisma.blog.update({
where: { id: post.id },
data: {
status: 'PUBLISHED',
published: true,
publishedAt: now,
},
});
this.logger.log(`Successfully published scheduled article: "${post.title}"`);
}
} finally {
// Always release the lock in the finally block
await this.prisma.$queryRaw`SELECT pg_advisory_unlock(${SCHEDULER_LOCK_ID})`;
}
}
}
3. Failure Recovery and Exponential Backoff
If database connectivity drops during a scheduled sweep:
- The scheduler captures the failure and records an audit log with correlation IDs.
- It backs off exponentially (e.g., 30s, 60s, 120s) to prevent spamming a struggling database.
- Once connectivity recovers, all overdue articles published during the outage are processed safely in batch.
PostgreSQL advisory locks provide an elegant, zero-dependency alternative to heavy distributed coordinator setups like Redis Redlock or Apache ZooKeeper.


