0
0
Node.jsframework~8 mins

ws library for WebSocket server in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: ws library for WebSocket server
MEDIUM IMPACT
This affects the server's ability to handle real-time communication efficiently, impacting response time and resource usage.
Handling multiple WebSocket connections with message broadcasting
Node.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
function broadcast(data, sender) {
  for (const client of wss.clients) {
    if (client !== sender && client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  }
}
wss.on('connection', ws => {
  ws.on('message', message => {
    setImmediate(() => broadcast(message, ws));
  });
});
Using setImmediate defers broadcasting to next event loop cycle, preventing blocking and smoothing CPU usage.
📈 Performance GainReduces event loop blocking and improves responsiveness under load
Handling multiple WebSocket connections with message broadcasting
Node.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
});
Broadcasting messages by iterating all clients on every message causes high CPU usage and delays when many clients connect.
📉 Performance CostTriggers multiple event loop cycles and CPU spikes proportional to client count
Performance Comparison
PatternCPU UsageEvent Loop BlockingLatencyVerdict
Synchronous broadcast on message eventHigh CPU spikesBlocks event loopIncreased latency under load[X] Bad
Asynchronous broadcast with setImmediateBalanced CPU usageNon-blocking event loopLower latency and smoother response[OK] Good
Rendering Pipeline
WebSocket server operations run outside the browser rendering pipeline but affect user experience by controlling real-time data flow and interaction responsiveness.
Network I/O
Event Loop
Message Dispatch
⚠️ BottleneckEvent Loop blocking due to synchronous message handling
Core Web Vital Affected
INP
This affects the server's ability to handle real-time communication efficiently, impacting response time and resource usage.
Optimization Tips
1Avoid synchronous loops over clients for broadcasting messages.
2Use asynchronous deferral (setImmediate or process.nextTick) to prevent event loop blocking.
3Monitor CPU usage and event loop delays under load to ensure smooth real-time communication.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a common performance issue when broadcasting messages to many WebSocket clients synchronously?
AEvent loop blocking causing delayed message delivery
BIncreased CSS repaint times
CHigher memory usage in the browser
DSlower initial page load
DevTools: Performance
How to check: Record a performance profile while simulating multiple WebSocket clients sending messages; look for long tasks and event loop blocking.
What to look for: Check for long blocking tasks in the event loop and CPU usage spikes during message broadcasts.