Building a Real-Time Notification System With WebSockets and Redis
Real-time features are a critical part of modern web applications. In this tutorial, you'll learn how to create a scalable real-time notification system using WebSockets (via socket.io
) and Redis for pub/sub messaging across instances.
Why Use Redis?
When deploying multiple Node.js instances, WebSocket connections don’t share state across processes. Redis helps by broadcasting events between instances using its publish/subscribe mechanism.
Step 1: Set Up Your Project
npm init -y
npm install express socket.io redis
Step 2: Create the Server
// server.js
const express = require('express');
const http = require('http');
const { createClient } = require('redis');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const pubClient = createClient();
const subClient = pubClient.duplicate();
Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
io.adapter(require('@socket.io/redis-adapter')(pubClient, subClient));
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('notify', (msg) => {
io.emit('notification', msg);
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
});
Step 3: Create the Client
Real-Time Notifications
Notification Center
Step 4: Test It Out
Run multiple instances using a process manager like PM2 or simply multiple terminals, and see how Redis allows them to communicate and share notifications in real-time.
Conclusion
Combining WebSockets with Redis gives you the tools to scale real-time features like notifications, chat, and presence across distributed infrastructure. This architecture is used in many production-grade applications for seamless live updates.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift