Load Testing WebSockets with k6: Scripts, Metrics, and Failure Patterns

Load Testing WebSockets with k6: Scripts, Metrics, and Failure Patterns

Most teams load test their HTTP APIs and assume WebSocket performance will be fine. It usually isn't. WebSocket servers fail differently under load — they don't slow down gracefully, they fall off cliffs. Connection counts hit OS limits, memory spikes as open sockets accumulate, and broadcast operations that were imperceptible at 100 connections become your bottleneck at 10,000.

k6 is the right tool for this. It supports WebSockets natively, has a clean JavaScript API, and produces metrics that map directly to the questions you need to answer. This guide covers everything from writing your first WS script to understanding what your results actually mean.

k6 WebSocket Basics

k6's WebSocket API uses a synchronous-looking callback model. You call ws.connect(), pass a callback, and all WebSocket operations happen inside that callback. The function doesn't return until the connection closes.

import ws from 'k6/ws';
import { check } from 'k6';

export default function () {
  const url = 'wss://api.example.com/ws';
  
  const response = ws.connect(url, {}, function (socket) {
    socket.on('open', () => {
      console.log('Connected');
      socket.send(JSON.stringify({ type: 'ping' }));
    });
    
    socket.on('message', (data) => {
      const msg = JSON.parse(data);
      check(msg, {
        'received pong': (m) => m.type === 'pong',
      });
      socket.close();
    });
    
    socket.on('close', () => {
      console.log('Disconnected');
    });
    
    socket.on('error', (e) => {
      console.error('Error:', e.error());
    });
  });
  
  check(response, {
    'connection status 101': (r) => r && r.status === 101,
  });
}

Run it:

k6 run script.js

# With options
k6 run --vus 50 --duration 30s script.js

Each virtual user (VU) runs the default function in a loop. For WebSockets, you typically want each VU to maintain a persistent connection for a duration, not connect/disconnect repeatedly.

Writing a Realistic Load Test Script

A WebSocket load test should reflect how real users behave. Typically: connect, do some initial setup (auth, subscribe to channels), then exchange messages for a while before disconnecting.

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

// Custom metrics
const msgReceived = new Counter('messages_received');
const msgLatency = new Trend('message_latency_ms');
const errorRate = new Rate('error_rate');

export const options = {
  scenarios: {
    websocket_load: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '1m', target: 100 },  // Ramp up to 100 VUs
        { duration: '3m', target: 100 },  // Hold at 100 VUs
        { duration: '1m', target: 0 },    // Ramp down
      ],
    },
  },
  thresholds: {
    'messages_received': ['count>1000'],
    'message_latency_ms': ['p95<500'],   // 95th percentile under 500ms
    'error_rate': ['rate<0.01'],          // Less than 1% errors
    'ws_connecting': ['p95<1000'],        // Connection time under 1s
  },
};

export default function () {
  const userId = `user-${__VU}-${__ITER}`;
  const token = generateToken(userId); // Implement this
  
  const url = `wss://api.example.com/ws?token=${token}`;
  const pendingMessages = new Map();
  
  ws.connect(url, {}, function (socket) {
    socket.on('open', () => {
      // Subscribe to a channel
      socket.send(JSON.stringify({
        type: 'subscribe',
        channel: 'prices',
      }));
    });
    
    socket.on('message', (data) => {
      const msg = JSON.parse(data);
      
      if (msg.type === 'subscribed') {
        // Start sending periodic messages
        socket.setInterval(() => {
          const sentAt = Date.now();
          const msgId = `${__VU}-${Date.now()}`;
          
          pendingMessages.set(msgId, sentAt);
          socket.send(JSON.stringify({
            type: 'ping',
            id: msgId,
          }));
        }, 2000); // Every 2 seconds
      }
      
      if (msg.type === 'pong') {
        const sentAt = pendingMessages.get(msg.id);
        if (sentAt) {
          msgLatency.add(Date.now() - sentAt);
          pendingMessages.delete(msg.id);
          msgReceived.add(1);
        }
      }
      
      if (msg.type === 'price-update') {
        msgReceived.add(1);
        check(msg, {
          'price update has symbol': (m) => m.symbol !== undefined,
          'price update has value': (m) => m.price > 0,
        });
      }
    });
    
    socket.on('error', (e) => {
      errorRate.add(1);
      console.error(`VU ${__VU}: Error: ${e.error()}`);
    });
    
    // Hold connection open for 2 minutes, then close
    socket.setTimeout(() => {
      socket.close();
    }, 120000);
  });
}

function generateToken(userId) {
  // In a real test, implement actual JWT generation or use pre-generated tokens
  return `test-token-${userId}`;
}

Metrics to Watch

k6 provides built-in WebSocket metrics plus any custom ones you define. Here are the ones that matter:

Built-in WS Metrics

ws_connecting — Time from connection initiation to the 101 Switching Protocols response. This is your handshake latency. At low load it's typically 1-20ms. If this creeps above 100ms under load, you have a handshake bottleneck (often auth-related).

ws_session_duration — How long connections stay open. For load tests of persistent connections, this should match your test duration.

ws_msgs_sent / ws_msgs_received — Message counts. Use these to verify your test is doing what you think.

Custom Metrics You Should Add

Message round-trip latency — Time from sending a message to receiving the corresponding response. This is the most important application-level metric. Track it as a Trend so you can see p50, p95, p99.

Message throughput — Messages per second across all VUs. Watch for throughput saturation — the point where adding more VUs doesn't increase throughput, just increases queuing.

Error rate — Proportion of operations that failed. Anything above 0.1% in a load test is a signal worth investigating.

Connection failure rate — How many ws.connect() calls fail to establish a connection at all. Separate from application-level errors.

System Metrics to Correlate

Run your load test while monitoring:

  • Server CPU — Sustained high CPU often indicates a broadcast or serialization bottleneck
  • Server memory — Should be roughly proportional to active connections; non-linear growth = memory leak
  • File descriptors — Each WebSocket connection uses one; ulimit -n is often 1024 by default on Linux
  • Network bandwidth — For high-throughput WS servers, bandwidth can be the limiting factor

Interpreting Results

Connection time spikes

If ws_connecting p95 is high, look at:

  1. Auth processing — Is your server doing database calls or JWT validation on every new connection? Cache it.
  2. TLS handshake — If using WSS, TLS adds latency. Use session resumption.
  3. Event loop blocking — A Node.js server doing synchronous work during connection setup blocks all new connections.

Message latency degradation under load

Message latency is usually stable up to a certain concurrency level, then spikes suddenly. This spike point is your practical capacity limit. The spike typically happens because:

  • Broadcast fan-out — Sending to 10,000 connections is 10,000 individual write calls. This blocks the event loop.
  • Message queue saturation — The internal message queue fills up; messages wait.
  • Database under pressure — If each message requires a DB write, the DB becomes the bottleneck.

To find the inflection point, run escalating load tests:

export const options = {
  scenarios: {
    find_limit: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '2m', target: 500 },
        { duration: '2m', target: 1000 },
        { duration: '2m', target: 2000 },
        { duration: '2m', target: 5000 },
        { duration: '2m', target: 0 },
      ],
    },
  },
};

Plot message_latency_ms p95 against time. The inflection point in the graph is your capacity limit.

High error rates

Common causes:

Server rejecting connections — Manifest as ws_connecting errors. Check server logs for the rejection reason. Often: rate limiting, max connection count, auth failures.

Connections dropping mid-test — If VUs are connecting fine but ws_session_duration is much shorter than your test duration, the server is closing connections early. Check for idle timeouts, memory pressure causing OOM kills, or application errors.

Message processing errors — If your server emits error events to clients, capture them with custom metrics. High error rates on specific message types usually point to validation or logic bugs that only surface under load.

Common Failure Patterns

The File Descriptor Wall

The server starts dropping connections at an arbitrary concurrency level — often 1024 or 65535 (common ulimit values). Connections above the limit fail immediately.

Diagnosis: ws_connecting error rate spikes sharply at a specific VU count.

Fix: ulimit -n 65536 in the process environment, or via systemd/container configuration.

The Broadcast Bottleneck

Latency is low until you add broadcast traffic, then it explodes. Sending a message to a room with 1000 members is 1000 write operations — they all happen synchronously in most naive implementations.

Diagnosis: Latency stays low under connection-only load but spikes when you add broadcast messages.

Fix: Use worker threads for broadcast, or a pub/sub system (Redis pub/sub) that offloads the fan-out.

The Memory Leak

Memory grows linearly with connection count initially (expected), then continues growing after connections close (leak). Eventually triggers OOM kill.

Diagnosis: Monitor server memory during and after load test. After all VUs disconnect, memory should return to baseline. If it doesn't, you have a leak.

Common causes: Event listeners not removed on disconnect, subscriptions not cleaned up, caches that grow without bounds.

The Thundering Herd on Reconnect

After a server restart, all clients reconnect simultaneously. Each reconnection does auth, state restoration, and subscription setup. The combined load exceeds capacity, causing more failures, causing more reconnects.

Test this explicitly:

// Simulate a server restart by disconnecting all clients and reconnecting with random jitter
socket.on('close', () => {
  const jitter = Math.random() * 5000; // 0-5s jitter
  sleep(jitter / 1000);
  // Reconnect logic
});

Fix: Exponential backoff with jitter in clients. Cap reconnect attempts per second on the server side.

Running in CI

WebSocket load tests in CI are useful for catching regressions in throughput and latency. Keep them short (under 5 minutes) and set meaningful thresholds:

export const options = {
  duration: '2m',
  vus: 50,
  thresholds: {
    'message_latency_ms': ['p95<200'],  // Fail if p95 latency exceeds 200ms
    'error_rate': ['rate<0.005'],       // Fail if error rate exceeds 0.5%
    'ws_connecting': ['p99<500'],       // Fail if any connection takes >500ms
  },
};

When k6 exits with a non-zero code (threshold violations), fail the CI job. Over time, this creates a performance safety net that catches regressions before they reach production.

The first time you run a serious WS load test against a "production-ready" service, you'll almost always find something — a missing ulimit, a broadcast bottleneck, a memory leak that only shows at scale. Better to find it with k6 at 3am on a laptop than with real users at 3am in production.

Read more

Start now free