0
0
Node.jsframework~8 mins

WebSocket protocol concept in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: WebSocket protocol concept
MEDIUM IMPACT
WebSocket affects the speed and responsiveness of real-time data exchange between client and server.
Sending frequent real-time updates from server to client
Node.js
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', ws => {
  // Persistent connection allows sending updates anytime
  setInterval(() => {
    ws.send('Update data');
  }, 1000);
});
WebSocket keeps connection open, reducing handshake overhead and enabling instant data push.
📈 Performance GainReduces network latency and CPU usage, improving INP and user experience.
Sending frequent real-time updates from server to client
Node.js
const http = require('http');
const server = http.createServer((req, res) => {
  // On each request, server sends data and closes connection
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Update data');
});
server.listen(8080);
HTTP requires opening and closing a new connection for each update, causing high latency and overhead.
📉 Performance CostTriggers multiple TCP handshakes and TLS negotiations, blocking rendering and increasing INP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
HTTP polling for updatesMultiple new DOM updates per requestTriggers reflow per updateHigh paint cost due to frequent changes[X] Bad
WebSocket persistent connectionDOM updates only on new dataMinimal reflows triggeredLower paint cost with batched updates[OK] Good
Rendering Pipeline
WebSocket maintains a persistent TCP connection allowing continuous data flow without repeated handshakes, minimizing delays in data arrival and UI updates.
Network
JavaScript Execution
Paint
⚠️ BottleneckNetwork latency during initial handshake if not reused
Core Web Vital Affected
INP
WebSocket affects the speed and responsiveness of real-time data exchange between client and server.
Optimization Tips
1Use WebSocket to maintain a persistent connection for real-time data to reduce latency.
2Avoid opening new WebSocket connections repeatedly; reuse existing ones to save handshake costs.
3Monitor WebSocket frames in DevTools Network panel to ensure efficient data flow.
Performance Quiz - 3 Questions
Test your performance knowledge
How does using WebSocket improve interaction responsiveness compared to HTTP polling?
ABy caching all data on the client side
BBy sending larger data packets less frequently
CBy keeping a persistent connection and reducing handshake overhead
DBy compressing data before sending
DevTools: Network
How to check: Open DevTools > Network tab, filter by WS to see WebSocket frames and connection status.
What to look for: Look for a single persistent WebSocket connection with frequent frames instead of many HTTP requests.