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

@flash-analytics/redis

v0.1.0

Published

A robust Redis client package optimized for Cloud Run environments with comprehensive connection management, health monitoring, and graceful shutdown handling.

Readme

Redis Package

A robust Redis client package optimized for Cloud Run environments with comprehensive connection management, health monitoring, and graceful shutdown handling.

Features

  • 🚀 Cloud Run Optimized: Configured for serverless environments with VPC connectors
  • 🔍 Connection Health Monitoring: Real-time status tracking for all Redis clients
  • 🔄 Graceful Shutdown: Proper connection cleanup on application termination
  • 📊 Comprehensive Logging: Detailed connection event tracking and error reporting
  • 🛡️ Type Safety: Enhanced TypeScript support with proper error handling
  • Performance: Singleton pattern with lazy connection initialization

Installation

npm install @flash-analytics/redis

Usage

Basic Usage

import { getRedisCache } from '@flash-analytics/redis';

const redis = getRedisCache();
await redis.set('key', 'value');
const value = await redis.get('key');

JSON Operations

import { getRedisCache } from '@flash-analytics/redis';

const redis = getRedisCache();

// Store JSON data
await redis.setJson('user:123', 3600, { name: 'John', age: 30 });

// Retrieve JSON data with type safety
const user = await redis.getJson<{ name: string; age: number }>('user:123');
if (user) {
  console.log(user.name); // Type-safe access
}

Connection Health Monitoring

import { getRedisConnectionStatus, getRedisMetrics } from '@flash-analytics/redis';

// Check connection status for all clients
const status = getRedisConnectionStatus();
console.log(status);
// {
//   cache: true,
//   sub: true,
//   pub: true,
//   queue: true,
//   groupQueue: true
// }

// Get detailed metrics
const metrics = getRedisMetrics();
console.log(metrics);
// {
//   status: { cache: true, sub: true, pub: true, queue: true, groupQueue: true },
//   totalConnected: 5,
//   totalClients: 5,
//   connectionRate: 1,
//   timestamp: '2024-01-20T10:30:00.000Z'
// }

Graceful Shutdown

import { closeRedisConnections } from '@flash-analytics/redis';

// In your application shutdown handler
process.on('SIGTERM', async () => {
  await closeRedisConnections();
  process.exit(0);
});

Available Clients

The package provides five specialized Redis clients:

Cache Client (getRedisCache())

General-purpose caching with JSON support.

import { getRedisCache } from '@flash-analytics/redis';

const cache = getRedisCache();
await cache.set('key', 'value', 'EX', 3600);

Pub/Sub Clients (getRedisSub(), getRedisPub())

Dedicated clients for publish/subscribe operations.

import { getRedisSub, getRedisPub } from '@flash-analytics/redis';

const subscriber = getRedisSub();
const publisher = getRedisPub();

await subscriber.subscribe('channel');
subscriber.on('message', (channel, message) => {
  console.log(`Received: ${message} from ${channel}`);
});

await publisher.publish('channel', 'Hello World!');

Queue Clients (getRedisQueue(), getRedisGroupQueue())

Optimized for BullMQ job queues with special configuration.

import { getRedisQueue, getRedisGroupQueue } from '@flash-analytics/redis';

const queue = getRedisQueue();
const groupQueue = getRedisGroupQueue();

// Use with BullMQ
import { Queue } from 'bullmq';
const myQueue = new Queue('my-queue', { connection: queue });

Configuration

Environment Variables

  • REDIS_URL: Redis connection URL (default: redis://localhost:6379)

Connection Options

All clients are configured with Cloud Run optimizations:

const baseOptions = {
  connectTimeout: 10000,
  keepAlive: 30000,           // Keep TCP connection alive
  lazyConnect: true,           // Don't connect until first command
  retryStrategy: (times) => {
    const delay = Math.min(times * 50, 2000);
    logger.debug('Redis connection retry attempt', { attempt: times, delayMs: delay });
    return delay;
  },
};

Queue clients have additional BullMQ-specific settings:

{
  enableReadyCheck: false,
  maxRetriesPerRequest: null,
  enableOfflineQueue: true,
}

Error Handling

The package includes comprehensive error handling:

JSON Operations

const data = await redis.getJson<User>('user:123');
// Returns null if key doesn't exist or JSON parsing fails
// Logs errors for debugging

Connection Errors

Connection errors are logged with detailed context:

Redis connection error: {
  name: "cache",
  event: "error",
  error: "Connection refused",
  code: "ECONNREFUSED",
  command: "get",
  args: ["user:123"]
}

Monitoring and Debugging

Connection Events

All connection events are logged for visibility:

  • connect: Connection initiated
  • ready: Connection established
  • reconnecting: Attempting reconnection
  • close: Connection closed
  • end: Connection ended
  • error: Connection error

Health Checks

Use the built-in health monitoring for application health checks:

import { getRedisConnectionStatus } from '@flash-analytics/redis';

app.get('/health', (req, res) => {
  const status = getRedisConnectionStatus();
  const allConnected = Object.values(status).every(Boolean);
  
  res.status(allConnected ? 200 : 503).json({
    status: allConnected ? 'healthy' : 'unhealthy',
    redis: status
  });
});

Development

Running Tests

npm test

Linting

npm run lint

Type Checking

npm run typecheck

Production Deployment

Cloud Run Best Practices

  1. Environment Variables: Set REDIS_URL in your Cloud Run service configuration
  2. Memory Limits: Ensure sufficient memory for Redis connections
  3. Concurrency: Configure appropriate concurrency settings
  4. Health Checks: Use the built-in health monitoring functions

Graceful Shutdown

Always implement graceful shutdown in your application:

import { closeRedisConnections } from '@flash-analytics/redis';

async function shutdown(signal: string) {
  console.log(`Received ${signal}, shutting down gracefully...`);
  
  try {
    await closeRedisConnections();
    console.log('Redis connections closed');
    process.exit(0);
  } catch (error) {
    console.error('Error during shutdown:', error);
    process.exit(1);
  }
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));

Troubleshooting

Connection Issues

  1. Check Redis URL: Ensure REDIS_URL is correctly set
  2. Network Connectivity: Verify VPC connector configuration for Cloud Run
  3. Firewall Rules: Ensure Redis instance allows connections from Cloud Run
  4. Connection Limits: Check Redis instance connection limits

Debugging

Enable debug logging to see connection events:

DEBUG=redis:* npm start

Common Issues

| Issue | Solution | |-------|----------| | "Connection is closed" | Check VPC connector and Redis instance configuration | | "ECONNREFUSED" | Verify Redis URL and instance availability | | "ETIMEDOUT" | Increase connect timeout or check network connectivity | | High reconnection rate | Review retry strategy and connection pool settings |

License

MIT