Writing a High-Performance WebSockets Server with uWebSockets.js
Introduction
uWebSockets.js offers ultra-fast WebSocket handling in Node.js, capable of managing tens of thousands of connections with low latency.
Prerequisites
- Node.js >=14
- npm or pnpm
Step 1: Install uWebSockets.js
pnpm add uNetworking/uWebSockets.js#v20.7.0
Step 2: Basic Server Setup
const uWS = require('uWebSockets.js');
const port = 9001;
uWS.App().ws('/*', {
/* Settings */
compression: uWS.SHARED_COMPRESSOR,
maxPayloadLength: 16 * 1024,
idleTimeout: 10,
/* Handlers */
open: (ws, req) => {
ws.subscribe('broadcast');
console.log('Connection opened');
},
message: (ws, message, isBinary) => {
/* Broadcast message to all subscribers */
ws.publish('broadcast', message, isBinary);
},
close: (ws, code, message) => {
console.log('Connection closed');
}
}).listen(port, (token) => {
if (token) {
console.log(`Server listening on port ${port}`);
} else {
console.error(`Failed to listen on port ${port}`);
}
});
Step 3: Handling HTTP
uWebSockets can serve HTTP alongside WebSockets:
uWS.App()
.get('/health', (res, req) => {
res.writeStatus('200 OK').end('healthy');
})
.post('/broadcast', (res, req) => {
let buffer = Buffer.alloc(0);
res.onData((chunk, isLast) => {
buffer = Buffer.concat([buffer, Buffer.from(chunk)]);
if (isLast) {
res.writeStatus('200 OK').end('ok');
// Broadcast via WebSocket server instance
// wsServer.publish('broadcast', buffer, false);
}
});
})
.listen(port, /* ... */);
Step 4: Scaling with Workers
Cluster across CPU cores:
const { clone } = require('uWebSockets.js');
const server = require('./server');
const os = require('os');
if (cluster.isPrimary) {
const cpuCount = os.cpus().length;
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
} else {
/* Each worker runs uWS.App() */
require('./server');
}
Step 5: Performance Tips
- Use
SHARED_COMPRESSOR
for gzip/payload compression. - Tune
maxPayloadLength
to expected message size. - Set
idleTimeout
to disconnect inactive clients. - Use
ws.subscribe()
andws.publish()
for channel-based messaging.
Step 6: Client Example
import WebSocket from 'ws';
const ws = new WebSocket('ws://localhost:9001');
ws.on('open', () => {
console.log('Connected');
ws.send('Hello server');
});
ws.on('message', (data) => {
console.log('Received:', data.toString());
});
Summary
uWebSockets.js provides extreme performance for WebSocket servers. Use clustering, shared compressors, and efficient subscription patterns to handle high throughput with minimal resource usage.