Load Testing WebSocket Servers with k6 and Artillery
A WebSocket server that handles 10 simultaneous connections perfectly can collapse at 500. The failure modes are different from HTTP: connection exhaustion, message queuing latency, broadcast fan-out amplification, and memory growth per-connection. Load testing WebSocket servers requires different tooling and mental models than load testing REST APIs. This guide covers both k6 and Artillery with real scripts you can adapt.
Why WebSocket Load Testing Differs from HTTP
HTTP load testing is stateless: each virtual user makes a request, waits for a response, and the transaction is complete. Connection setup cost is amortized across many requests via keep-alive, but each virtual user's memory footprint is small.
WebSocket load testing is stateful:
- Each virtual user holds an open TCP connection for the duration of the test
- Server memory grows linearly with connection count
- Broadcasting to N connections means N write operations — quadratic fan-out if every client broadcasts to all others
- Connection churn (rapid connect/disconnect) is a separate stress vector from sustained connection count
Before writing a load test, define what you're measuring:
- Maximum concurrent connections at acceptable latency
- Message throughput (messages/second) per connection
- Broadcast fan-out — how does latency grow as room size increases?
- Connection churn resilience — rapid connect/disconnect cycles
k6: WebSocket Load Testing
k6 has built-in WebSocket support via the k6/ws module. Scripts are written in JavaScript; k6 compiles and runs them with its Go runtime (not Node.js — no npm, no require).
Basic k6 WebSocket Script
// k6-ws-basic.js
import ws from 'k6/ws';
import { check, sleep } from 'k6';
import { Counter, Trend } from 'k6/metrics';
const messageLatency = new Trend('ws_message_latency', true); // true = report in ms
const messagesReceived = new Counter('ws_messages_received');
export const options = {
stages: [
{ duration: '30s', target: 50 }, // Ramp up to 50 VUs over 30s
{ duration: '1m', target: 50 }, // Hold at 50 VUs for 1 minute
{ duration: '30s', target: 200 }, // Ramp up to 200 VUs
{ duration: '2m', target: 200 }, // Hold at 200 VUs for 2 minutes
{ duration: '30s', target: 0 }, // Ramp down
],
thresholds: {
ws_connecting: ['p(95)<500'], // 95% of connections establish in <500ms
ws_message_latency: ['p(99)<100'], // 99% of messages round-trip in <100ms
ws_msgs_received: ['count>1000'], // At least 1000 messages received
},
};
export default function () {
const url = 'ws://localhost:8080/ws';
const params = {
headers: { Authorization: 'Bearer test-token' },
};
const response = ws.connect(url, params, function (socket) {
socket.on('open', () => {
// Subscribe to a channel
socket.send(JSON.stringify({ type: 'subscribe', channel: 'prices' }));
});
socket.on('message', (data) => {
messagesReceived.add(1);
try {
const msg = JSON.parse(data);
if (msg.type === 'pong' && msg.sentAt) {
const latency = Date.now() - msg.sentAt;
messageLatency.add(latency);
}
} catch (_) {
// not JSON, skip
}
});
socket.on('error', (e) => {
console.error('WebSocket error:', e.error());
});
// Send a ping every 5 seconds and measure round-trip
socket.setInterval(() => {
socket.send(JSON.stringify({ type: 'ping', sentAt: Date.now() }));
}, 5000);
// Keep connection open for 30 seconds
socket.setTimeout(() => {
socket.close();
}, 30000);
});
check(response, {
'connected successfully': (r) => r && r.status === 101,
});
}Run it:
k6 run k6-ws-basic.jsMeasuring Connection Ramp-Up
The ramp-up phase is where most WebSocket servers show their first problems. Each new connection requires OS resources: a file descriptor, memory for the socket buffer, and any per-connection state your application allocates.
// k6-ramp-test.js
import ws from 'k6/ws';
import { check, sleep } from 'k6';
import { Gauge } from 'k6/metrics';
const activeConnections = new Gauge('active_connections');
export const options = {
scenarios: {
ramp_connections: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '1m', target: 100 },
{ duration: '1m', target: 500 },
{ duration: '1m', target: 1000 },
{ duration: '2m', target: 1000 }, // Sustain peak
{ duration: '1m', target: 0 },
],
gracefulRampDown: '30s',
},
},
thresholds: {
'ws_connecting': ['p(95)<1000', 'p(99)<2000'],
'ws_session_duration': ['p(95)<65000'], // sessions last near-full test duration
},
};
export default function () {
const res = ws.connect('ws://localhost:8080', {}, function (socket) {
activeConnections.add(1);
socket.on('open', () => {
socket.send(JSON.stringify({ type: 'hello' }));
});
socket.on('close', () => {
activeConnections.add(-1);
});
// Stay connected for the test duration
socket.setTimeout(() => socket.close(), 60000);
});
check(res, { 'status 101': (r) => r && r.status === 101 });
}Watch for the "knee" in your latency graph — the point where ws_connecting p95 starts climbing. That's where your server runs out of headroom. Common causes: file descriptor limits (ulimit -n), accept backlog overflow, or thread pool exhaustion.
Testing Message Throughput
Throughput testing measures how many messages per second the server can process without message queuing latency growing unbounded.
// k6-throughput.js
import ws from 'k6/ws';
import { check } from 'k6';
import { Counter, Rate, Trend } from 'k6/metrics';
const sentMessages = new Counter('messages_sent');
const receivedMessages = new Counter('messages_received');
const messageDropRate = new Rate('message_drop_rate');
const processingLatency = new Trend('processing_latency');
export const options = {
vus: 100,
duration: '2m',
thresholds: {
message_drop_rate: ['rate<0.01'], // Less than 1% message drop
processing_latency: ['p(95)<50'], // 95% processed in <50ms
},
};
let messageCounter = 0;
export default function () {
const pendingAcks = new Map();
ws.connect('ws://localhost:8080', {}, function (socket) {
socket.on('open', () => {
// Send messages at 10/second
socket.setInterval(() => {
const id = ++messageCounter;
const payload = JSON.stringify({
type: 'echo',
id,
sentAt: Date.now(),
});
pendingAcks.set(id, Date.now());
socket.send(payload);
sentMessages.add(1);
}, 100); // 10 messages/second per VU → 1000/s total across 100 VUs
});
socket.on('message', (data) => {
try {
const msg = JSON.parse(data);
if (msg.type === 'echo_response' && pendingAcks.has(msg.id)) {
const latency = Date.now() - pendingAcks.get(msg.id);
processingLatency.add(latency);
pendingAcks.delete(msg.id);
receivedMessages.add(1);
messageDropRate.add(0); // This message was received
}
} catch (_) {}
});
socket.setTimeout(() => {
// Count any messages still pending as dropped
pendingAcks.forEach(() => messageDropRate.add(1));
socket.close();
}, 115000);
});
}Artillery WebSocket Scenarios
Artillery is YAML-first and better suited to scenario-based testing. It supports WebSockets out of the box.
# artillery-ws.yml
config:
target: "ws://localhost:8080"
phases:
- duration: 30
arrivalRate: 5 # 5 new virtual users per second for 30s
name: Warm up
- duration: 60
arrivalRate: 20 # 20/s for 1 minute
name: Sustained load
- duration: 30
arrivalRate: 50 # 50/s spike
name: Spike
ws:
rejectUnauthorized: false
plugins:
metrics-by-endpoint:
useOnlyRequestNames: true
scenarios:
- name: "Chat room user"
engine: ws
flow:
- connect: "ws://localhost:8080/chat"
- send:
json:
type: "join"
room: "general"
username: "user-{{ $randomNumber(1, 10000) }}"
- think: 1 # Wait 1 second (simulates reading)
- loop:
- send:
json:
type: "message"
room: "general"
text: "Message {{ $loopCount }}"
- think: 2
count: 10
- close: {}artillery run artillery-ws.yml --output results.json
artillery report results.jsonFor more complex scenarios with custom message handling:
# artillery-ws-advanced.yml
config:
target: "ws://localhost:8080"
phases:
- duration: 120
arrivalRate: 10
processor: "./artillery-functions.js"
scenarios:
- name: "Subscription flow"
engine: ws
flow:
- connect:
headers:
Authorization: "Bearer load-test-token"
- function: "sendSubscription"
- waitFor:
response:
json:
type: "subscribed"
timeout: 5000
- think: 5
- function: "sendUnsubscription"
- close: {}// artillery-functions.js
module.exports = {
sendSubscription(context, events, done) {
const channels = ['prices', 'orders', 'users'];
const channel = channels[Math.floor(Math.random() * channels.length)];
context.vars.channel = channel;
events.emit('send', JSON.stringify({
type: 'subscribe',
channel,
clientId: context.vars.$uuid,
}));
done();
},
sendUnsubscription(context, events, done) {
events.emit('send', JSON.stringify({
type: 'unsubscribe',
channel: context.vars.channel,
}));
done();
},
};Finding Concurrency Limits
The goal of concurrency testing is finding your server's practical ceiling — the point where you start refusing connections or latency degrades beyond SLA.
Binary-search approach:
// k6-find-limit.js
import ws from 'k6/ws';
import { check } from 'k6';
import { Rate } from 'k6/metrics';
const connectionFailRate = new Rate('connection_fail_rate');
// Start with __ENV.TARGET_VUS, increase until failure rate > 1%
export const options = {
vus: parseInt(__ENV.TARGET_VUS || '100'),
duration: '30s',
thresholds: {
connection_fail_rate: ['rate<0.01'],
},
};
export default function () {
const res = ws.connect('ws://localhost:8080', {}, function (socket) {
socket.setTimeout(() => socket.close(), 25000);
});
const success = check(res, { 'connected': (r) => r && r.status === 101 });
connectionFailRate.add(!success);
}# Binary search for connection limit
for vus in 100 500 1000 2000 4000; do
echo "=== Testing $vus VUs ==="
k6 run -e TARGET_VUS=$vus k6-find-limit.js 2>&1 | grep "connection_fail_rate"
doneWhen connection_fail_rate exceeds your threshold, your previous value is the safe maximum. Add 20% margin for production headroom.
Interpreting Results
k6's output includes these key metrics for WebSocket tests:
| Metric | What It Means | Alert Threshold |
|---|---|---|
ws_connecting |
Time to complete WebSocket handshake | p95 > 500ms: resource pressure |
ws_msgs_sent |
Total messages sent | — |
ws_msgs_received |
Total messages received | Drop rate > 1%: queue overflow |
ws_session_duration |
How long connections stayed open | Should match your scenario intent |
| Custom latency trends | Application round-trip time | p99 > your SLA |
Warning signs in your Artillery report:
p99latency climbing over time (not just high): message queue is growing, server can't keep up- Connection errors in middle of test (not just ramp-up): server is dropping connections under load
- Mean latency fine but p99 very high: occasional large pauses — likely GC pressure or thread pool saturation
Server-Side Metrics to Correlate
Load test results only make sense when correlated with server-side metrics. While a load test runs, also collect:
# Watch file descriptor usage
watch -n1 'ls /proc/$(pgrep node)/fd | wc -l'
# Watch memory
watch -n1 'ps -o pid,rss,vsz -p $(pgrep node)'
# Watch connection count
watch -n1 'ss -s | grep ESTAB'For a Node.js WebSocket server, also expose an internal metrics endpoint:
// In your WebSocket server
const { Server } = require('ws');
const wss = new Server({ port: 8080 });
// Metrics endpoint on a different port
const metricsServer = require('http').createServer((req, res) => {
if (req.url === '/metrics') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
connections: wss.clients.size,
memory: process.memoryUsage(),
uptime: process.uptime(),
}));
}
});
metricsServer.listen(9090);Poll this during load tests and plot connection count against latency. If latency is linear with connection count, you have O(N) broadcast logic. If it's quadratic, you have a fan-out problem.
Common Issues Found by Load Testing
OS file descriptor limits: Default is 1024 on many Linux systems. A Node.js WebSocket server needs one FD per connection plus overhead. Set ulimit -n 65535 for load testing.
Node.js single-threaded broadcast: Broadcasting to 10,000 clients in a single event loop tick blocks the loop for every other operation. The fix: batch broadcasts with setImmediate to yield between chunks.
Memory per connection: If your server stores any per-connection state (user object, subscriptions, message buffer), multiply by connection count. 1MB per connection × 10,000 connections = 10GB. Load testing surfaces this before production does.
nginx buffering: If your WebSocket server sits behind nginx, check proxy_read_timeout and proxy_send_timeout. Default values cause valid long-lived WebSocket connections to be terminated as "idle".
Load testing WebSocket servers takes more setup than hitting an HTTP endpoint with wrk, but the insights are proportionally more valuable — because the failure modes are less visible and more catastrophic.