Load Testing Real-Time Systems: WebSockets, SSE, and Beyond

Load Testing Real-Time Systems: WebSockets, SSE, and Beyond

Load testing a REST API is well-understood: ramp up concurrent requests, measure latency percentiles, find where the server breaks. Real-time systems are different. WebSocket servers maintain persistent connections — a server handling 10,000 concurrent WebSocket clients is under a fundamentally different kind of load than one serving 10,000 HTTP requests per second. The connections are stateful, long-lived, and bidirectional.

This post covers how to load test real-time systems properly, using k6 as the primary tool.

What Makes Real-Time Load Different

With REST, load is mostly about request throughput: requests per second, latency under concurrency. With real-time systems, you care about:

  • Connection capacity: how many simultaneous persistent connections can the server hold?
  • Message throughput: at peak connection count, can the server still deliver messages within latency SLAs?
  • Broadcast fan-out: if one event triggers messages to 1,000 subscribers, what's the delay to the last subscriber?
  • Memory growth: do server-side connection objects leak memory over time?
  • Reconnect storms: what happens when 5,000 clients all reconnect simultaneously after a restart?

Setting Up k6 for WebSocket Load Tests

k6 has built-in WebSocket support via the k6/ws module. Install k6:

# macOS
brew install k6

# Docker
docker pull grafana/k6

A basic WebSocket load test:

// ws-load-test.js
import ws from 'k6/ws';
import { check, sleep } from 'k6';
import { Counter, Trend } from 'k6/metrics';

const messageLatency = new Trend('ws_message_latency');
const messagesReceived = new Counter('ws_messages_received');

export const options = {
  stages: [
    { duration: '30s', target: 100 },   // ramp to 100 connections
    { duration: '2m', target: 100 },    // hold
    { duration: '30s', target: 500 },   // ramp to 500
    { duration: '3m', target: 500 },    // hold
    { duration: '30s', target: 0 },     // ramp down
  ],
  thresholds: {
    ws_message_latency: ['p(95)<500'],  // 95th percentile under 500ms
    ws_connecting: ['p(95)<1000'],      // connect within 1s
  },
};

export default function () {
  const url = 'wss://your-server.example.com/ws';

  const res = 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);
      messagesReceived.add(1);

      // Measure round-trip latency for ping/pong
      if (msg.type === 'pong' && msg.sentAt) {
        messageLatency.add(Date.now() - msg.sentAt);
      }
    });

    socket.on('error', (e) => {
      console.error('WebSocket error:', e.error());
    });

    // Send a ping every 10 seconds to measure latency
    socket.setInterval(() => {
      socket.send(JSON.stringify({ type: 'ping', sentAt: Date.now() }));
    }, 10000);

    // Hold the connection for 3 minutes
    socket.setTimeout(() => {
      socket.close();
    }, 180000);
  });

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

Run it:

k6 run ws-load-test.js

Testing Message Fan-Out

Fan-out — one event broadcast to many subscribers — is where real-time servers commonly struggle. Test it explicitly:

// fan-out-test.js
import ws from 'k6/ws';
import { check } from 'k6';
import { Trend, Counter } from 'k6/metrics';

const fanoutDelay = new Trend('fanout_delay_ms');
const broadcastsReceived = new Counter('broadcasts_received');

export const options = {
  scenarios: {
    // Many subscribers holding connections
    subscribers: {
      executor: 'constant-vus',
      vus: 1000,
      duration: '5m',
      exec: 'subscriber',
    },
    // One publisher sending messages
    publisher: {
      executor: 'constant-vus',
      vus: 1,
      duration: '5m',
      exec: 'publisher',
      startTime: '10s', // Give subscribers time to connect first
    },
  },
};

export function subscriber() {
  ws.connect('wss://your-server.example.com/ws', {}, (socket) => {
    socket.on('open', () => {
      socket.send(JSON.stringify({ type: 'subscribe', channel: 'broadcast-test' }));
    });

    socket.on('message', (data) => {
      const msg = JSON.parse(data);
      if (msg.type === 'broadcast') {
        const delay = Date.now() - msg.publishedAt;
        fanoutDelay.add(delay);
        broadcastsReceived.add(1);
      }
    });

    socket.setTimeout(() => socket.close(), 280000);
  });
}

export function publisher() {
  ws.connect('wss://your-server.example.com/ws?role=publisher', {}, (socket) => {
    socket.on('open', () => {
      // Publish every 5 seconds
      socket.setInterval(() => {
        socket.send(JSON.stringify({
          type: 'publish',
          channel: 'broadcast-test',
          publishedAt: Date.now(),
        }));
      }, 5000);
    });

    socket.setTimeout(() => socket.close(), 280000);
  });
}

The fanout_delay_ms metric tells you how long it takes from message publish to receipt across all 1,000 subscribers. A rising p99 under load indicates a bottleneck in your broadcast pipeline.

Simulating Reconnect Storms

After a server restart or network partition, all clients attempt reconnection simultaneously. This is often the worst-case load scenario.

// reconnect-storm.js
import ws from 'k6/ws';
import { sleep, check } from 'k6';
import { Counter } from 'k6/metrics';

const reconnectAttempts = new Counter('reconnect_attempts');
const reconnectSuccess = new Counter('reconnect_success');

export const options = {
  vus: 500,
  duration: '2m',
};

export default function () {
  // Simulate clients that were connected, then all reconnect at once
  // (no staggered delay — worst case)
  let connected = false;
  let attempts = 0;

  while (!connected && attempts < 5) {
    attempts++;
    reconnectAttempts.add(1);

    const res = ws.connect('wss://your-server.example.com/ws', {}, (socket) => {
      socket.on('open', () => {
        connected = true;
        reconnectSuccess.add(1);
        socket.setTimeout(() => socket.close(), 30000);
      });

      socket.on('error', () => {
        socket.close();
      });
    });

    if (!connected) {
      sleep(0.1 + Math.random() * 0.5); // Brief backoff before retry
    }
  }

  check(connected, { 'reconnected successfully': (v) => v });
}

Run this immediately after a planned server restart to validate your reconnection handling and server capacity under thundering herd conditions.

Key Metrics to Watch

Connection-level:

  • ws_connecting (built-in k6 metric) — time to establish the WebSocket handshake
  • Connection error rate — connections that fail vs. succeed
  • Connection duration distribution — are connections being dropped prematurely?

Message-level:

  • Round-trip latency (measure with ping/pong timestamps)
  • Message loss rate (use sequence numbers: if you send messages 1-100 but only receive 90, loss rate is 10%)
  • Fan-out delay at p50/p95/p99

Server-side (from your monitoring):

  • Memory per connection — multiply by target max connections to find your memory floor
  • File descriptor usage — each WebSocket connection uses a file descriptor; ulimit -n sets the ceiling
  • CPU during broadcast — N-client broadcasts are O(N) CPU work

Load Testing SSE Endpoints

SSE is simpler — it's a one-way HTTP stream. k6's HTTP module handles it:

// sse-load-test.js
import http from 'k6/http';
import { check } from 'k6';
import { Counter } from 'k6/metrics';

const eventsReceived = new Counter('sse_events_received');

export const options = {
  vus: 200,
  duration: '3m',
};

export default function () {
  // SSE connections are long-lived GET requests with streaming response
  const response = http.get('https://your-server.example.com/events', {
    headers: { Accept: 'text/event-stream' },
    timeout: '180s',
  });

  check(response, {
    'SSE connection established': (r) => r.status === 200,
    'content-type is event-stream': (r) =>
      r.headers['Content-Type'].includes('text/event-stream'),
  });

  // Count events in the response body
  const lines = response.body.split('\n');
  const dataLines = lines.filter(l => l.startsWith('data:'));
  eventsReceived.add(dataLines.length);
}

Note: k6's HTTP module waits for the full response, so for SSE you need to set a long timeout and let the connection close naturally (or use the timeout option to bound it).

Establishing Your Baseline

Before load testing, establish a single-connection baseline:

  1. Single client, 10 minutes: measure memory, CPU, message latency
  2. 10 clients: verify linear scaling
  3. 100 clients: first real test of your server's event loop
  4. 1,000 clients: where most hobby servers start struggling
  5. Target production load × 2: your actual stress test target

If latency at 100 clients equals latency at 1 client, you're scaling well. If p99 starts climbing at 500 clients, you've found your inflection point — that's where you need to optimize before shipping.

For end-to-end validation of your real-time features (does the UI actually update when messages arrive?), pair k6 load tests with functional tests in a tool like HelpMeTest, which can run parallel browser sessions against your staging environment to confirm message delivery from the client's perspective.

Summary

Load testing real-time systems requires thinking beyond throughput:

  • Test connection capacity, not just request rate
  • Measure fan-out latency explicitly, not just average latency
  • Simulate reconnect storms as a distinct load scenario
  • Watch server-side memory and file descriptor counts alongside latency
  • Use k6's multi-scenario support to run publishers and subscribers in parallel

The goal isn't just "the server stays up under load" — it's "messages arrive within your latency SLA when 10,000 clients are connected and a broadcast goes out every second."

Read more

Start now free