WebSocket management — handle thousands of connections efficiently.
1const { WebSocketServer } = require("ws");2const Redis = require("ioredis");34// Connection manager5class ConnectionManager {6 constructor() {7 this.connections = new Map();8 this.redis = new Redis();9 this.subscriber = new Redis();10 }1112 add(userId, ws) {13 if (!this.connections.has(userId)) {14 this.connections.set(userId, new Set());15 }16 this.connections.get(userId).add(ws);17 this.redis.sadd(`user:${userId}:sockets`, ws.id);18 }1920 remove(userId, ws) {21 const sockets = this.connections.get(userId);22 if (sockets) {23 sockets.delete(ws);24 if (sockets.size === 0) this.connections.delete(userId);25 }26 this.redis.srem(`user:${userId}:sockets`, ws.id);27 }2829 sendToUser(userId, message) {30 const sockets = this.connections.get(userId);31 if (sockets) {32 const data = JSON.stringify(message);33 sockets.forEach(ws => {34 if (ws.readyState === WebSocket.OPEN) {35 ws.send(data);36 }37 });38 } else {39 // User on another server — use Redis pub/sub40 this.redis.publish(`user:${userId}`, data);41 }42 }43}
Scaling: