Overview
A real-time notification system delivers immediate updates to users across web, mobile, and email channels. For a multi-tenant SaaS application, the system must handle connections efficiently without crashing backend application servers.
Architectural Components
- WebSocket Gateway: Manages persistent bi-directional TCP connections with client browsers.
- Message Broker: Uses Apache Kafka or RabbitMQ to decouple notification triggers from message delivery.
- Pub/Sub State Store: Uses Redis Pub/Sub to route messages to the specific gateway instance where the target user is connected.
WebSocket Node Server Pattern
The following example demonstrates how a server registers and pushes messages to targeted client sessions:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const userSockets = new Map();
wss.on('connection', (ws, req) => {
const userId = getUserIdFromReq(req);
userSockets.set(userId, ws);
ws.on('close', () => {
userSockets.delete(userId);
});
});
function sendNotification(userId, message) {
const socket = userSockets.get(userId);
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(message));
}
}