When one microservice calls the next over HTTP and waits, a single slow or failed service stalls the whole chain. A Redis Pub/Sub event broker in Node.js fixes that: services publish events to a channel and move on, and any service that cares subscribes. This tutorial builds a small broker class with ioredis, two services that talk through it, reconnect handling and pattern subscriptions.
Quick answer: Open two ioredis connections, one to publish and one to subscribe, because a subscribed connection cannot run other commands. Publish JSON with publisher.publish(channel, payload) and handle it in one message listener on the subscriber. Remember that Pub/Sub does not store messages.
- Install
ioredisanddotenv, and start Redis. - Create an
EventBrokerclass with separate publisher and subscriber clients. - Subscribe in one service and publish from another.
- Route all messages through a single listener so callbacks are not duplicated.
- Use
psubscribe('user.*')to receive a whole family of events.
In this guide
- Before You Start
- What You Will Build
- Why Redis Pub/Sub for Events
- Step 1: Set Up the Project
- Step 2: Build the EventBroker Class
- Step 3: Create a Subscriber and a Publisher
- Test It: Send Events Between the Two Services
- Step 4: Handle Reconnects Without Duplicate Listeners
- Step 5: Subscribe to Many Channels with PSUBSCRIBE
- Redis Pub/Sub vs Message Queues: When to Use Which
- Common Production Gotchas
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps
Heavier tools such as RabbitMQ or Kafka are built for this too, but they add infrastructure to run and configure. If you already run Redis for caching, its built-in publish/subscribe feature handles simple real-time broadcasts with no extra setup.

Before You Start
- Node.js 18 or newer (a current LTS release is best).
- Docker to run Redis locally, or any Redis server you can reach.
- Two terminal windows, one per service. The tutorial takes about 30 minutes.
- Know the trade-off: messages published while a subscriber is offline are lost. If every event must be processed, use Redis Streams or a queue instead (compared at the end).
What You Will Build
.env– the Redis URL.EventBroker.js– a class that owns the publisher and subscriber connections.notification-service.js– a subscriber that reacts touser.registeredevents.web-app.js– a publisher that sends a registration event every 3 seconds.analytics-service.js(optional) – a pattern subscriber that receives everyuser.*event.
Why Redis Pub/Sub for Events
Redis Pub/Sub is fire-and-forget. A publisher sends a message to a channel, and Redis pushes it straight to every client subscribed to that channel. It is fast because Redis does not write the messages to disk or track who received what.
That also means nothing waits for offline workers. If messages must wait until a worker is back, use a persistent queue, as in the guide to managing rate limits with BullMQ. For instant broadcasts, such as updating a dashboard, triggering notification workers or syncing state, Pub/Sub is the simplest tool.
One rule shapes the code, and the Redis Pub/Sub documentation explains it: once a connection subscribes, it can only run subscription commands. So you need at least two connections, one to publish and one to subscribe.
Step 1: Set Up the Project
Run these commands in your terminal. They create the project, switch it to ES modules and install the packages:
mkdir redis-pubsub-broker
cd redis-pubsub-broker
npm init -y
npm pkg set type=module
npm install ioredis dotenvThe npm pkg set type=module line is what lets the .js files use import. The ioredis client library reconnects automatically and works with ES modules.
Create a .env file in the project folder:
REDIS_URL=redis://127.0.0.1:6379
PORT=3000If you do not have Redis running yet, start a container:
docker run -d --name local-redis -p 127.0.0.1:6379:6379 redis:7.2-alpineStep 2: Build the EventBroker Class
The broker class creates the two connections, logs errors, publishes events with a consistent shape and subscribes to channels. Create EventBroker.js:
import Redis from 'ioredis';
import dotenv from 'dotenv';
dotenv.config();
class EventBroker {
constructor() {
const redisUrl = process.env.REDIS_URL || 'redis://127.0.0.1:6379';
// We need two separate clients
this.publisher = new Redis(redisUrl, { maxRetriesPerRequest: null });
this.subscriber = new Redis(redisUrl, { maxRetriesPerRequest: null });
this.setupErrorHandling();
}
setupErrorHandling() {
this.publisher.on('error', (err) => {
console.error('Redis Publisher Error:', err.message);
});
this.subscriber.on('error', (err) => {
console.error('Redis Subscriber Error:', err.message);
});
this.subscriber.on('connect', () => {
console.log('Redis Subscriber connected successfully.');
});
}
async publish(channel, eventData) {
try {
const payload = JSON.stringify({
event: channel,
timestamp: Date.now(),
data: eventData
});
await this.publisher.publish(channel, payload);
} catch (error) {
console.error(`Failed to publish to channel ${channel}:`, error);
throw error;
}
}
async subscribe(channel, callback) {
try {
await this.subscriber.subscribe(channel);
this.subscriber.on('message', (chan, message) => {
if (chan === channel) {
try {
const parsed = JSON.parse(message);
callback(parsed);
} catch (parseError) {
console.error('Failed to parse incoming message:', message);
}
}
});
console.log(`Subscribed to channel: ${channel}`);
} catch (error) {
console.error(`Failed to subscribe to channel ${channel}:`, error);
throw error;
}
}
async disconnect() {
await Promise.all([this.publisher.quit(), this.subscriber.quit()]);
console.log('Redis connections closed.');
}
}
export const broker = new EventBroker();Every payload has the same structure: the event name, a timestamp and the data. That way each subscriber can parse and check messages the same way.
Step 3: Create a Subscriber and a Publisher
To try the broker, you will run two scripts that stand in for two microservices. In production each would run in its own container or server.
First, the subscriber. Create notification-service.js. It listens for user registration events, where a real service would send a confirmation email:
import { broker } from './EventBroker.js';
console.log('Starting Notification Service...');
broker.subscribe('user.registered', (payload) => {
const { data, timestamp } = payload;
const delay = Date.now() - timestamp;
console.log(`[Notification Service] Received user.registered event!`);
console.log(`User ID: ${data.userId}`);
console.log(`Email: ${data.email}`);
console.log(`Event delivery delay: ${delay}ms`);
console.log('--------------------------------------------');
});Next, the publisher. Create web-app.js. It simulates a web app that registers a new user every 3 seconds:
import { broker } from './EventBroker.js';
async function simulateUserRegistration() {
const mockUser = {
userId: `user_${Math.floor(Math.random() * 1000000)}`,
email: 'dev@example.com',
signupSource: 'organic'
};
console.log(`[Web App] Registering user: ${mockUser.userId}`);
// Publish the event
await broker.publish('user.registered', mockUser);
}
// Run every 3 seconds to simulate real organic traffic
setInterval(simulateUserRegistration, 3000);Test It: Send Events Between the Two Services
Start the subscriber first, because Pub/Sub only delivers to clients that are already listening. In the first terminal, run:
node notification-service.jsYou should see Starting Notification Service..., Redis Subscriber connected successfully. and Subscribed to channel: user.registered. In the second terminal, start the publisher:
node web-app.jsEvery 3 seconds the web app logs [Web App] Registering user: user_…, and the notification service logs Received user.registered event! with the same user ID, the email and the delivery delay it measured.
To confirm the subscription from Redis itself, run docker exec local-redis redis-cli pubsub numsub user.registered. It prints the channel name followed by the number of subscribers, which should be 1. Stop both scripts with Ctrl+C when you are done.
Step 4: Handle Reconnects Without Duplicate Listeners
If Redis restarts or the network drops, the subscriber connection drops too. ioredis reconnects on its own, and because its autoResubscribe option is on by default, it subscribes to the same channels again. What it cannot do is recover messages published while the connection was down; with Pub/Sub those are gone.
The class has a different problem that shows up as it grows: every call to subscribe() adds another message listener to the connection. The updated version below keeps a single listener that routes each message to the callbacks registered for its channel, and logs reconnects so gaps are visible.
In EventBroker.js, replace the constructor and subscribe() with these versions. Keep the imports at the top and the export const broker line at the bottom:
class EventBroker {
constructor() {
const redisUrl = process.env.REDIS_URL || 'redis://127.0.0.1:6379';
this.publisher = new Redis(redisUrl, { maxRetriesPerRequest: null });
this.subscriber = new Redis(redisUrl, { maxRetriesPerRequest: null });
// Keep track of the callbacks registered for each channel
this.activeSubscriptions = new Map();
// Single message handler that routes to the registered callbacks
this.subscriber.on('message', (chan, message) => {
const callbacks = this.activeSubscriptions.get(chan);
if (callbacks) {
try {
const parsed = JSON.parse(message);
callbacks.forEach(cb => cb(parsed));
} catch (err) {
console.error('Failed to process message callbacks:', err);
}
}
});
this.subscriber.on('reconnecting', () => {
console.warn('Redis Subscriber reconnecting. Messages published until it is back are lost.');
});
this.setupErrorHandling();
}
// setupErrorHandling(), publish() and disconnect() stay exactly as before
async subscribe(channel, callback) {
try {
// Store callback in our active subscriptions map
if (!this.activeSubscriptions.has(channel)) {
this.activeSubscriptions.set(channel, []);
}
this.activeSubscriptions.get(channel).push(callback);
await this.subscriber.subscribe(channel);
console.log(`Subscribed and registered callback for: ${channel}`);
} catch (error) {
console.error(`Failed to subscribe to channel ${channel}:`, error);
throw error;
}
}
}To test it, keep both services running and restart Redis with docker restart local-redis. The notification service logs the reconnect warning, then carries on receiving events with no restart of your own. The warning tells you there was a gap, which matters because nothing published during it is delivered.
Step 5: Subscribe to Many Channels with PSUBSCRIBE
As your system grows, subscribing to channels one by one gets tedious. Redis supports pattern subscriptions with the PSUBSCRIBE command. An analytics worker, for example, can listen to every user event (user.registered, user.updated, user.deleted) with the single pattern user.*.
Add this method to the EventBroker class in EventBroker.js, next to subscribe():
async pSubscribe(pattern, callback) {
try {
await this.subscriber.psubscribe(pattern);
this.subscriber.on('pmessage', (matchedPattern, channel, message) => {
if (matchedPattern === pattern) {
try {
const parsed = JSON.parse(message);
callback(channel, parsed);
} catch (err) {
console.error('Failed to parse pattern message:', err);
}
}
});
console.log(`Pattern subscription active for: ${pattern}`);
} catch (error) {
console.error(`Pattern subscription failed for ${pattern}:`, error);
throw error;
}
}Then create analytics-service.js. Start it with the line import { broker } from './EventBroker.js'; and add this listener below it:
broker.pSubscribe('user.*', (channel, payload) => {
console.log(`[Analytics] Intercepted event on channel [${channel}]:`, payload.data);
});Run it with node analytics-service.js while web-app.js is publishing. It logs [Analytics] Intercepted event on channel [user.registered] for each event. New event types that match the pattern reach it without any change to the subscriber.
Redis Pub/Sub vs Message Queues: When to Use Which
Pub/Sub and queues solve different problems. This comparison helps you pick:
- Delivery: Redis Pub/Sub broadcasts each message to every current subscriber. BullMQ and RabbitMQ queues hand each message to one consumer.
- Persistence: Pub/Sub stores nothing. A queue keeps each message until it has been processed.
- Offline consumers: with Pub/Sub, messages are lost. With a queue, they wait.
- Overhead: Pub/Sub does the least work per message. A queue adds bookkeeping for storage, acknowledgements and retries.
Choose Pub/Sub when missing a message is acceptable, such as live dashboard metrics or typing indicators. Choose a queue when every message must be processed eventually, such as invoices or transactional emails. If several subscribers might write the same record, protect the write with a Redis distributed lock to prevent duplicate updates.
Common Production Gotchas
- “Connection in subscriber mode” error: ioredis rejects the call with
Connection in subscriber mode, only subscriber commands may be usedwhen you callbroker.subscriber.set()or another normal command on the subscriber client. Use the publisher connection, or a third connection, for normal key-value commands. - Slow subscribers get disconnected: if a subscriber processes messages slowly, Redis buffers them in memory. When that buffer passes the configured limit, Redis closes the client connection. Keep callbacks short, and hand heavy database work to a background worker.
- Every instance gets every message: if you run several copies of a subscriber service, each copy receives its own copy of each event. If only one instance should handle each event, pure Pub/Sub cannot do it; use consumer groups in Redis Streams instead.
If It Still Doesn’t Work
ECONNREFUSED 127.0.0.1:6379: Redis is not running. Start it withdocker start local-redis.SyntaxError: Cannot use import statement outside a module: the project is not set to ES modules. Runnpm pkg set type=modulein the project folder.- The subscriber prints nothing: it was started after the events were sent, or the channel names differ. Start the subscriber first and check both use
user.registeredexactly. - Each event is handled twice:
subscribe()was called twice with the original class, which adds a second listener. Use the single-listener version from Step 4.
Frequently Asked Questions
Can I use Redis Pub/Sub for chat applications?
Yes, it works well for chat across several servers. Each server subscribes to the chat channels and pushes messages to its own connected users over WebSockets. Pub/Sub only relays live messages, so store the chat history in a database if users need to scroll back.
What happens if my subscriber goes offline?
Any message published while it is offline is lost for good. Redis does not keep Pub/Sub messages for later delivery. If you need subscribers to catch up after downtime, use Redis Streams, which keep messages until they are acknowledged, or a job queue such as BullMQ.
Is there a limit to the number of channels I can create?
No, there is no hard limit on channels. A channel only exists while it has subscribers, so unused channels cost nothing. Memory grows with the number of active subscriptions and with any messages buffered for slow clients.
How do I secure Redis Pub/Sub connections?
Use TLS and Redis ACLs in production. TLS encrypts the traffic between your services and Redis. ACLs (Access Control Lists) let you give each service its own user and restrict which channels it may publish or subscribe to, so one compromised service cannot read every event.
Next Steps
You now have a working event broker. Move one slow HTTP call between your services onto a channel first, and keep the reconnect warning in your logs so you can see any gaps. To show these events live in a browser, see how to stream events to the browser with SSE and Node.js. For tying Redis messages into native Node.js patterns, the Node.js EventEmitter API docs are the reference.

