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

@apiratorjs/locking-redis

v2.0.0

Published

An extension to the core @apiratorjs/locking library, providing Redis-based implementations of distributed mutexes and semaphores for true cross-process concurrency control in Node.js.

Readme

@apiratorjs/locking-redis

NPM version License: MIT

An extension to the core @apiratorjs/locking library, providing a Redis-backed IDistributedLockManager with distributed mutexes and semaphores for true cross-process concurrency control in Node.js.

Note: Requires Node.js version >=16.4.0, @apiratorjs/locking ^5.0.0, and a running Redis instance (version 5+ recommended).

Upgrading from 1.x? See CHANGELOG and 2.0.0 release notes.


Why Use Redis for Distributed Locking?

  • Multi-instance deployments: If you have multiple Node.js processes or servers behind a load balancer, an in-memory lock is insufficient. Redis provides a single, centralized coordination point.
  • Fault tolerance: Configurable timeouts (TTLs) prevent indefinite locks if a process crashes.
  • Scalability: Redis can handle many simultaneous locking requests at scale.

Features

  • RedisDistributedLockManager — implements types.IDistributedLockManager from @apiratorjs/locking.
  • Distributed Mutex and Semaphore — same acquire / release / cancel / wait-for-unlock API as the core distributed primitives, coordinated through Redis.
  • Named locks — the same name returns the same live instance while it is alive; list(), count(), snapshot(), cancelAll(), and destroyAll() for inspection and shutdown.
  • Time-limited locks (TTL) — prevents deadlocks if processes crash without releasing.
  • Cancellation, timeouts, and FIFO waiters — cancel blocked acquisitions, fail fast with timeoutMs: 0, queue waiters in order.
  • Read-write locks — not implemented yet; readWriteLock() throws LockingError.

Installation

Install with npm:

npm install @apiratorjs/locking @apiratorjs/locking-redis

Or with yarn:

yarn add @apiratorjs/locking @apiratorjs/locking-redis

Usage

Default acquire timeout is 1 minute (same as the core library). Pass timeoutMs: 0 to fail fast with a TimeoutLockingError when the lock is not immediately available.

cancel() / cancelAll() reject pending acquisitions only: held locks stay held, and waitForUnlock() / waitForAnyUnlock() / waitForFullyUnlock() keep waiting until holders release (or until destroy() / destroyAll(), which resolves those waiters).

Quick start

import { RedisDistributedLockManager } from "@apiratorjs/locking-redis";

const locks = await RedisDistributedLockManager.create({
  url: "redis://localhost:6379",
});

async function example() {
  const mutex = locks.mutex("shared-resource");

  const releaser = await mutex.acquire({ timeoutMs: 5000 });
  try {
    console.log("Distributed mutex acquired");
  } finally {
    await releaser.release();
  }

  await locks.semaphore("api-rate-limiter", 5).runExclusive(async () => {
    console.log("Distributed semaphore slot acquired");
  });
}

process.on("SIGTERM", async () => {
  await locks.destroyAll("Shutting down");
  await locks.disconnect();
});

Inject an existing Redis client

When you already own a redis client, pass it into the constructor. In that case disconnect() is a no-op — you close the client yourself.

import { createClient } from "redis";
import { RedisDistributedLockManager } from "@apiratorjs/locking-redis";

const redisClient = createClient({ url: "redis://localhost:6379" });
await redisClient.connect();

const locks = new RedisDistributedLockManager({ redisClient });

Distributed Mutex

const mutex = locks.mutex("orders");

const releaser = await mutex.acquire({ timeoutMs: 5000 });
try {
  // Critical section — exclusive across all processes sharing this Redis
} finally {
  await releaser.release();
}

await mutex.runExclusive(async () => {
  // Acquired and released automatically
});

await mutex.cancel("Operation cancelled");
await mutex.waitForUnlock();

Distributed Semaphore

const semaphore = locks.semaphore("uploads", 5);

const releaser = await semaphore.acquire({ timeoutMs: 5000 });
try {
  // Up to 5 concurrent holders across processes
} finally {
  await releaser.release();
}

await semaphore.runExclusive(async () => {
  // Acquired and released automatically
});

await semaphore.cancelAll("Operation cancelled");
await semaphore.waitForAnyUnlock();
await semaphore.waitForFullyUnlock();

Managing locks

import { ELockDisplayType } from "@apiratorjs/locking";

locks.hasMutex("orders");
locks.hasSemaphore("uploads");
locks.count();
locks.count(ELockDisplayType.Semaphore);
locks.list();
await locks.snapshot();

await locks.cancelAll("Draining before deploy");
await locks.destroyAll("Shutting down");

Requesting the same semaphore name with a different maxCount throws LockConfigMismatchError.

Swapping backends

Because both managers implement IDistributedLockManager, application code can depend on the interface and receive either an in-memory or Redis manager:

import { types, InMemoryDistributedLockManager } from "@apiratorjs/locking";
import { RedisDistributedLockManager } from "@apiratorjs/locking-redis";

export const locks: types.IDistributedLockManager =
  process.env.REDIS_URL
    ? await RedisDistributedLockManager.create({ url: process.env.REDIS_URL })
    : new InMemoryDistributedLockManager();

Nothing is global, so a Redis-backed manager and an in-memory one can coexist — useful when only part of the system needs cross-process coordination, and in tests.

Low-level classes

RedisDistributedMutex and RedisDistributedSemaphore are also exported for advanced use (for example custom managers). Prefer RedisDistributedLockManager in application code so named instances, listing, and shutdown stay consistent.


Error handling

Errors come from @apiratorjs/locking:

| Error Class | When thrown | |-------------|-------------| | TimeoutLockingError | acquire() exceeds timeoutMs | | CancelledLockingError | cancel() / cancelAll() or destroy | | LockNotFoundError | Lock was destroyed | | LockConfigMismatchError | Same name requested with conflicting maxCount | | LockingError | Base class; also thrown by unimplemented readWriteLock() |


Contributing

Contributions, issues, and feature requests are welcome! Please open an issue or submit a pull request on GitHub.