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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Real-Time Notifications</title>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
</head>
<body>
<h1>Notification Center</h1>
<ul id="notifications"></ul>
<button onclick="sendNotification()">Send Test Notification</button>
<script>
const socket = io();
socket.on('notification', (msg) => {
const li = document.createElement('li');
li.textContent = msg;
document.getElementById('notifications').appendChild(li);
});
function sendNotification() {
socket.emit('notify', '🔔 New notification at ' + new Date().toLocaleTimeString());
}
</script>
</body>
</html>
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
Top comments (0)