WebSocket · Load Testing · k6 · Node.js

Load Testing WebSocket Servers: Connections, Message Latency and Reconnect Storms

How to load test a WebSocket server: modelling concurrent connections, measuring message round-trip latency with k6, OS limits on the load generator and testing reconnect storms.

Sander Yazıcıoğlu Published: 4 min read Türkçe oku

Load Testing WebSocket Servers: Connections, Message Latency and Reconnect Storms

At LiveTesting, every action a user takes on a real device, every tap, swipe and log line, travels over a WebSocket. At Loadium, my day job was helping people put load on systems. Combining the two taught me that a WebSocket server can't be load tested the way you test a REST endpoint. Requests per second barely matters; what matters is how many connections you hold, how fast messages move through them and what happens when they all drop at once.

Why HTTP thinking doesn't fit

An HTTP load test asks: "How many requests per second can we answer within 300 ms?" A WebSocket server has a different cost profile:

DimensionHTTP APIWebSocket server
Main resourceCPU per requestMemory and file descriptors per connection
Key metricRequests/s and latencyConcurrent connections and message latency
Typical failureSlow responses, 5xxSilent drops, growing latency, memory leaks
Dangerous eventTraffic spikeEveryone reconnecting at the same moment

So the test has three separate questions: how many idle connections fit, how many messages per second flow through them, and how the system recovers from a mass disconnect.

Model the traffic first

Before writing a script, write down what one real client does. For a device-control session it looks roughly like this: connect, authenticate, subscribe to a device channel, send a small command every few seconds, receive a steady stream of status and log messages, keep the connection open for many minutes. A dashboard client is different: mostly idle, occasional broadcasts. Mixing these profiles in the right ratio matters more than the total number of virtual users. The general approach to scenarios is in the performance testing guide.

A k6 script that measures what matters

k6 has a WebSocket module, and the trick is to measure round-trip latency yourself by putting a timestamp in each message and having the server echo or acknowledge it.

import ws from 'k6/ws';
import { check } from 'k6';
import { Trend, Counter } from 'k6/metrics';

const rtt = new Trend('ws_message_rtt', true);
const dropped = new Counter('ws_unexpected_close');

export const options = {
  scenarios: {
    sessions: {
      executor: 'ramping-vus',
      stages: [
        { duration: '5m', target: 2000 },  // ramp connections slowly
        { duration: '15m', target: 2000 }, // hold
        { duration: '2m', target: 0 },
      ],
    },
  },
  thresholds: {
    ws_message_rtt: ['p(95)<250'],
    ws_connecting: ['p(95)<1000'],
    ws_unexpected_close: ['count<20'],
  },
};

export default function () {
  const url = `${__ENV.WS_URL}?token=${__ENV.TOKEN}`;
  const res = ws.connect(url, {}, (socket) => {
    let closedByUs = false;

    socket.on('open', () => {
      socket.send(JSON.stringify({ type: 'subscribe', channel: `device:${__VU % 50}` }));
      socket.setInterval(() => {
        socket.send(JSON.stringify({ type: 'ping', sentAt: Date.now() }));
      }, 3000);
    });

    socket.on('message', (raw) => {
      const msg = JSON.parse(raw);
      if (msg.type === 'pong') rtt.add(Date.now() - msg.sentAt);
    });

    socket.on('close', () => { if (!closedByUs) dropped.add(1); });

    socket.setTimeout(() => { closedByUs = true; socket.close(); }, 10 * 60 * 1000);
  });

  check(res, { 'upgraded (101)': (r) => r && r.status === 101 });
}

Built-in metrics such as ws_connecting, ws_sessions, ws_msgs_sent and ws_msgs_received come for free. The custom ws_message_rtt trend is the one that tells you whether users feel the load, and counting closes you didn't initiate is how you find silent drops.

Watch the server, not only the client

Client-side numbers tell you something is wrong; server metrics tell you what. During the hold phase, track:

  • Memory per connection. Divide resident memory by open connections. If it keeps climbing while connection count is flat, something holds references to closed sockets.
  • Event loop lag. One slow JSON parse or a synchronous broadcast loop over thousands of sockets blocks every connection at once. The Node.js event loop explained post covers how to measure it.
  • Send buffer growth. In ws, socket.bufferedAmount growing means a client can't keep up. Without a limit, one slow consumer can eat a lot of memory.
function safeSend(socket: WebSocket, data: string) {
  if (socket.bufferedAmount > 1_000_000) {
    socket.terminate(); // slow consumer; let it reconnect and resync
    return;
  }
  socket.send(data);
}

The load generator hits limits first

Often the first thing that breaks is the machine running k6, not your server.

  • File descriptors. Each connection is a socket. Raise ulimit -n on both the generator and the server.
  • Ephemeral ports. One source IP talking to one destination IP and port has a limited range of local ports (check net.ipv4.ip_local_port_range). For tens of thousands of connections, use several generator machines or IPs. This is where a distributed platform like Loadium is genuinely useful.
  • Proxies and load balancers. Many have an idle timeout. If your test sends nothing for a minute, connections are cut and you measure the proxy, not your app. Real clients need a heartbeat anyway.

Test the reconnect storm

The most dangerous moment for a WebSocket system is a deploy or a crash: every client disconnects and tries to reconnect at once, each one re-authenticating and re-subscribing. Test it on purpose: hold the full connection count, restart one server instance, and watch connect latency and error rates for the next minute.

The fix lives in the client: exponential backoff with jitter.

function reconnectDelay(attempt: number) {
  const base = Math.min(30_000, 500 * 2 ** attempt);
  return base / 2 + Math.random() * (base / 2);
}

On the server side, draining connections gradually during shutdown spreads the storm; the graceful shutdown guide shows how.

Conclusion

A useful WebSocket load test models real client behaviour, ramps connections slowly, measures message round-trip time with timestamps and counts unexpected closes. Watch memory per connection and event loop lag on the server, make sure your load generator isn't the bottleneck, and always rehearse the reconnect storm before production does it for you. For the server patterns themselves, see realtime systems with Node.js and WebSocket.

All articles →