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
Maintainers
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-sdkQuick 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 notificationssms- SMS text messagesinapp- In-application notificationspush- Push notificationswhatsapp- WhatsApp messagesbulk-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
- Always handle errors: Listen to the
errorevent to monitor issues - Use templates: Leverage templates for consistent messaging
- Monitor queue: Listen to the
queuedevent to track offline messages - Graceful shutdown: The SDK handles SIGINT/SIGTERM automatically, but you can also manually disconnect
- 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.
