npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nestjs-pg-lock

v0.1.0

Published

Distributed lock for NestJS using PostgreSQL Advisory Locks

Readme

🔒 nestjs-pg-lock

An enterprise-grade, distributed locking library for NestJS utilizing PostgreSQL Advisory Locks.

Built with scalability, safety, and operational excellence in mind, nestjs-pg-lock prevents race conditions and ensures safe concurrency control in distributed environments (microservices, multi-instance deployments)—all without the infrastructure overhead of Redis.

✨ Key Features

  • AOP Based Lifecycle: Locks are strictly acquired and safely released via standard NestJS interceptors (rxjs).
  • Dynamic Lock Keys: Bind lock keys dynamically using ExecutionContext (e.g., req.user.id, body.itemId).
  • Fast Fail Mechanism: Instantly rejects conflicting requests throwing a dedicated PgLockConflictException (HTTP 409) rather than causing server deadlocks or infinite holding.
  • Safe Pool Management: Manages its own dedicated pg.Pool to bypass ORM (Prisma/TypeORM) connection-swapping bottlenecks, entirely eliminating connection leaks.
  • Robust Hashing: Safely compresses long dynamic strings into PostgreSQL-compatible 32-bit integer limits using internal SHA-256 hashing.

🚀 Installation

npm install nestjs-pg-lock pg

(Ensure you have PostgreSQL installed. The library leverages standard pg as a peer dependency.)


🛠 Usage

1. Module Registration

Register the PgLockModule globally in your Application, providing standard PostgreSQL pool credentials.

import { Module } from '@nestjs/common';
import { PgLockModule } from 'nestjs-pg-lock';

@Module({
  imports: [
    // Sync setup
    PgLockModule.forRoot({
      host: 'localhost',
      port: 5432,
      user: 'postgres',
      password: 'password',
      database: 'my_db',
      max: 5, // Dedicated lock pool size
      connectionTimeoutMillis: 5000,
    }),
    
    // OR Async setup via ConfigService
    PgLockModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        connectionString: config.get('DATABASE_URL'),
      }),
    }),
  ]
})
export class AppModule {}

2. Method Decorator

Attach the @UsePgLock decorator to any NestJS controllers or providers.

Static Lock Key

Locks all incoming requests attempting to execute the method globally.

import { UsePgLock } from 'nestjs-pg-lock';

@Post('global-sync')
@UsePgLock('global-sync-job')
async triggerGlobalSync() {
  // Only one instance/thread worldwide can run this concurrently.
}

Dynamic Lock Key (Contextual)

Create highly granular locks by evaluating the runtime ExecutionContext.

@Post('order')
@UsePgLock((ctx) => `checkout-user-${ctx.switchToHttp().getRequest().user.id}`)
async checkout() {
  // A specific user cannot trigger multiple checkouts at once.
  // However, different users can checkout in parallel safely!
}

3. Exception Handling (Fast Fail)

If a lock is already held by another process, the interceptor immediately rejects the incoming traffic. Catch the standard PgLockConflictException in your global filters for graceful API responses:

import { Catch, ExceptionFilter, ArgumentsHost } from '@nestjs/common';
import { PgLockConflictException } from 'nestjs-pg-lock';

@Catch(PgLockConflictException)
export class LockConflictFilter implements ExceptionFilter {
  catch(exception: PgLockConflictException, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    
    response.status(409).json({
      statusCode: 409,
      message: 'The requested resource is currently locked and processing. Please try again soon.',
      error: 'Conflict',
    });
  }
}

⚠️ Important Infrastructure Notice (PgBouncer)

PostgreSQL Advisory Locks are strictly session-level (bound to the physical connection). If your architecture relies on a database connection pooler like PgBouncer or AWS RDS Proxy operating in Transaction Pooling Mode, session-level state will be dropped or swapped across clients.

Solution: The PgLockModule connection must bypass transaction poolers. Provide a direct connection string (Bypass Port) pointing strictly to your physical DB instance for this module.