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

@leoribeiroweb/nest-redis

v0.1.0

Published

Shared Redis building blocks: one dual-mode connection (REDIS_URL or host/port/password), an atomic token bucket and a distributed lock.

Readme

@leoribeiroweb/nest-redis

One Redis connection for a NestJS service, plus the two coordination primitives that keep getting rewritten around it: an atomic token bucket and a distributed lock.

This package is part of the shared framework behind my own services. It is published publicly so builds need no registry credentials, but it is not an open-source project: there is no support commitment, and the API changes to suit the services that consume it. Pin a major version.

The connection

Two configuration modes, because both exist and each is the only one exercised somewhere:

| Mode | Variables | Where it runs | | --- | --- | --- | | URL | REDIS_URL | local development, docker-compose | | Discrete | REDIS_HOST, REDIS_PORT, REDIS_PASSWORD | the k3s cluster, where the password is a declarative secret reference rather than a substring of a URL |

REDIS_URL wins when both are set. REDIS_PORT defaults to 6379 and is validated: a non-numeric or out-of-range value throws RedisConfigError instead of reaching ioredis as NaN. The throw happens when Nest instantiates the module, not when the file is imported, so it arrives inside the bootstrap with a stack that points at it.

import { RedisModule, REDIS_CLIENT } from '@leoribeiroweb/nest-redis';

@Module({
  imports: [
    RedisModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({ source: config }),
    }),
  ],
})
export class AppModule {}

REDIS_CLIENT resolves to Redis | null. null is a supported answer, not a failure: it is how a single-instance process — local development, the test suite, a service deployed without Redis — tells a caller to fall back to an in-memory Map or disable a feature. A misconfigured Redis is a different thing and throws.

RedisModule closes the client in onApplicationShutdown with a deadline, so a connection that will not close politely is disconnected rather than left holding the shutdown sequence open.

For a client outside the DI graph, createRedisClient(source, overrides) and resolveRedisConnection(source) do the same work as plain functions.

Connection defaults

maxRetriesPerRequest: 1 and enableOfflineQueue: false make a command fail promptly during an outage, so callers reject and degrade instead of piling up work that lands minutes late. retryStrategy reconnects indefinitely with capped backoff: returning null would make ioredis end the client permanently, and a transient Redis restart would then break the feature until the pod restarts.

Token bucket

const { allowed, remaining, resetInSeconds } = await consumeTokenBucket(redis, {
  key: `rl:apikey:${apiKeyId}`,
  capacity: 60,
  windowSeconds: 60,
});

INCR + EXPIRE + TTL run as a single Lua script. A pipeline is not atomic across replicas or against other concurrent clients, so three round trips leave a window where two callers both read count == capacity and both pass the cap. EXPIRE runs only on the first increment, which anchors the window to the first request — re-expiring on every call would slide the window forward and a bucket under sustained traffic would never reset.

capacity and windowSeconds must be integers of at least 1, or the call throws TokenBucketConfigError. EXPIRE key 0 deletes the key, so a zero window would make every request see a fresh counter and pass — a limiter that silently does not limit. A counter that somehow lost its TTL is re-anchored rather than left to climb forever.

A Redis error propagates. A rate limiter that silently allows everything on error stops existing exactly when it is needed.

Distributed lock

const lock = new DistributedLock(redis, { keyPrefix: 'cache-lock' });

const outcome = await lock.withLock('participants:refresh', () => refresh(groupJid));
if (!outcome.acquired) return; // another replica is already on it

SET NX PX to take it; a Lua compare-and-delete to release it, so a lease that lapsed and was taken by another replica is never deleted by its previous holder. extend(ttlMs) pushes the lease out under the same ownership check. acquire returns null immediately unless given a retryTimeoutMs budget.

A throw from the work inside withLock propagates after the lock is released. Turning it into a result field is how a failing refresh becomes invisible. A failure of the release is swallowed instead — it would otherwise replace a completed result, or displace the error the work threw — and the lease expires on its TTL. Pass onReleaseFailure to have it logged. A caller that releases a handle by hand still sees the rejection.

There is deliberately no in-memory fallback when Redis is absent. A local lock answers "acquired" on every replica at once — the exact opposite of what the caller asked for — and does so silently. Construct the lock only when createRedisClient returned a client, and take the un-coordinated path otherwise.

Requirements

Node >=20.11.0. Peer dependencies: @nestjs/common ^11, ioredis ^5 || ^6, reflect-metadata ^0.2.

Both ioredis majors are exercised in CI: the lockfile installs 6, which the live services run, and a separate job installs the floor of the range and re-runs the suite.

Not in this package

The idempotency decorator, interceptor and store are deferred, not forgotten — see docs/decisions/2026-09-18-a4-redis-and-queue.md in the repository.