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

notification-producer-sdk

v1.0.21

Published

A lightweight, Redis-based SDK for producing and managing notifications in distributed systems. Built on Redis Streams with automatic reconnection, queuing, and retry mechanisms.

Downloads

75

Readme

Notification Producer SDK

Overview

A lightweight, Redis-based SDK for producing and managing notifications in distributed systems. Built on Redis Streams with automatic reconnection, queuing, and retry mechanisms.

Features

  • Multiple notification types: Email, SMS, In-App, Push, WhatsApp, and Bulk Email
  • Automatic reconnection: Built-in connection retry with exponential backoff
  • Offline queuing: Messages are queued when Redis is unavailable and sent when connection is restored
  • Retry mechanism: Failed messages are automatically retried with configurable backoff
  • Event-driven architecture: Built on EventEmitter for monitoring connection state and errors
  • Graceful shutdown: Automatically handles SIGINT/SIGTERM signals
  • Thread-safe implementation: Safe for concurrent operations

Installation

npm install notification-producer-sdk

Quick Start

import { NotificationProducer } from 'notification-producer-sdk';

const producer = new NotificationProducer({
  REDIS_URL: 'redis://localhost:6379',
  STREAM: 'notifications',
  GROUP: 'notification-processors'
});

// Connect to Redis
await producer.connect();

// Send a notification
await producer.push({
  type: ['email'],
  to: '[email protected]',
  subject: 'Welcome!',
  body: 'Welcome to our service.'
});

Configuration Options

interface ProducerOptions {
  // Redis Connection (provide either REDIS_URL or client)
  REDIS_URL?: string;              // Redis connection URL
  REDIS_USERNAME?: string;         // Redis username (optional)
  REDIS_PASSWORD?: string;         // Redis password (optional)
  client?: RedisClientType;        // Pre-configured Redis client (alternative to REDIS_URL)
  
  // Stream Configuration
  STREAM: string;                  // Redis stream name (required)
  GROUP?: string;                  // Consumer group name (optional)
  
  // Connection Settings
  connectionTimeout?: number;      // Connection timeout in ms (default: 20000)
  connectionRetries?: number;      // Max connection attempts (default: 5)
  retryBackoffMs?: number;         // Initial retry delay in ms (default: 200)
  maxBackoffMs?: number;           // Maximum retry delay in ms (default: 30000)
  
  // Queue Settings
  drainIntervalMs?: number;        // Queue drain interval in ms (default: 500)
  
  // Lifecycle
  quitOnShutdown?: boolean;        // Auto-disconnect on SIGINT/SIGTERM (default: true)
}

Notification Types

The SDK supports the following notification types:

  • email - Standard email notifications
  • sms - SMS text messages
  • inapp - In-application notifications
  • push - Push notifications
  • whatsapp - WhatsApp messages
  • bulk-email - Bulk email campaigns

Usage Examples

Basic Email Notification

await producer.push({
  type: ['email'],
  to: '[email protected]',
  subject: 'Password Reset',
  body: 'Click here to reset your password.'
});

SMS Notification

await producer.push({
  type: ['sms'],
  to: '+1234567890',
  message: 'Your verification code is: 123456'
});

Multi-Channel Notification

await producer.push({
  type: ['email', 'sms', 'push'],
  to: '[email protected]',
  subject: 'Order Confirmation',
  body: 'Your order #12345 has been confirmed.',
  message: 'Order #12345 confirmed'
});

Template-Based Notification

await producer.push({
  type: ['email'],
  to: '[email protected]',
  template: 'welcome-email',
  context: {
    firstName: 'John',
    activationLink: 'https://example.com/activate/token123'
  }
});

Email with Attachment

await producer.push({
  type: ['email'],
  to: '[email protected]',
  subject: 'Your Invoice',
  body: 'Please find your invoice attached.',
  attachment: 'https://example.com/invoices/invoice-123.pdf'
});

Bulk Email with Unique Context

await producer.push({
  type: ['bulk-email'],
  to: '[email protected]',
  subject: 'Monthly Newsletter',
  template: 'newsletter',
  uniq: [
    { to: '[email protected]', context: { name: 'Alice', discount: '10%' } },
    { to: '[email protected]', context: { name: 'Bob', discount: '15%' } },
    { to: '[email protected]', context: { name: 'Carol', discount: '20%' } }
  ]
});

Event Handling

The SDK extends EventEmitter and emits the following events:

// Connection established
producer.on('connected', () => {
  console.log('Connected to Redis');
});

// Connection lost
producer.on('disconnected', () => {
  console.log('Disconnected from Redis');
});

// Error occurred
producer.on('error', (error: Error) => {
  console.error('Producer error:', error);
});

// Message queued (when Redis is unavailable)
producer.on('queued', () => {
  console.log('Message queued for later delivery');
});

Error Handling

The SDK automatically handles connection failures and retries. Messages are queued when Redis is unavailable:

try {
  await producer.push({
    type: ['email'],
    to: '[email protected]',
    subject: 'Test',
    body: 'This is a test'
  });
} catch (error) {
  // Error will only be thrown after all retry attempts fail
  console.error('Failed to send notification:', error);
}

Connection Management

Manual Connection Control

// Connect to Redis
await producer.connect();

// Disconnect gracefully
await producer.disconnect();

Automatic Reconnection

The SDK automatically reconnects with exponential backoff when the connection is lost. Messages sent during disconnection are queued and delivered once the connection is restored.

Using a Custom Redis Client

import { createClient } from 'redis';

const customClient = createClient({
  url: 'redis://localhost:6379',
  socket: {
    reconnectStrategy: (retries) => Math.min(retries * 50, 500)
  }
});

const producer = new NotificationProducer({
  client: customClient,
  STREAM: 'notifications'
});

Payload Structure

interface EventPayload {
  type: NotificationTypes[];      // Array of notification types
  to: string;                      // Recipient identifier
  subject?: string;                // Email subject (for email types)
  body?: string;                   // Email/notification body
  template?: string;               // Template name
  attachment?: string;             // Attachment URL
  context?: any;                   // Template context data
  message?: string;                // SMS/Push message
  uniq?: Array<{                   // Bulk email unique data
    to?: string;
    context?: any;
  }>;
}

Best Practices

  1. Always handle errors: Listen to the error event to monitor issues
  2. Use templates: Leverage templates for consistent messaging
  3. Monitor queue: Listen to the queued event to track offline messages
  4. Graceful shutdown: The SDK handles SIGINT/SIGTERM automatically, but you can also manually disconnect
  5. Connection pooling: Reuse producer instances rather than creating new ones for each message

Advanced Configuration

High-Throughput Scenarios

const producer = new NotificationProducer({
  REDIS_URL: 'redis://localhost:6379',
  STREAM: 'notifications',
  drainIntervalMs: 100,      // Drain queue more frequently
  connectionRetries: 10,      // More retry attempts
  maxBackoffMs: 60000        // Higher max backoff
});

Development Environment

const producer = new NotificationProducer({
  REDIS_URL: 'redis://localhost:6379',
  STREAM: 'dev-notifications',
  quitOnShutdown: false,     // Don't auto-quit in dev
  connectionTimeout: 5000    // Shorter timeout for faster feedback
});

License

MIT

Support

For issues and feature requests, please visit our GitHub repository.