What this thread does
Default to k6 for a new WebSocket test; choose Locust when an existing Python test suite justifies owning the WebSocket client and its measurements.
Do first: save the echo-test starter below as ws.js
Use a non-production endpoint you control. Define authentication, expected acknowledgement, connection lifetime and message rate. The examples below require a plain text echo endpoint; replace the payload and matching rule for your application's protocol. Passing an upgrade handshake alone is not a message-delivery test.
Install k6 using its official platform instructions and save this authored starter as ws.js:
import { WebSocket } from 'k6/websockets';
import { check } from 'k6';
import { Trend } from 'k6/metrics';
const echoMs = new Trend('echo_ms');
export const options = {
thresholds: { checks: ['rate>0.99'], echo_ms: ['p(95)<500'] },
};
export default function () {
const ws = new WebSocket(__ENV.WS_URL);
let started, echoed = false;
ws.onopen = () => {
started = Date.now();
ws.send('probe');
};
ws.onmessage = (event) => {
if (!echoed && event.data === 'probe') {
echoed = true;
echoMs.add(Date.now() - started);
}
};
ws.onerror = () => check(false, { 'socket error absent': v => v });
ws.onclose = () => check(echoed, { 'echo received': v => v });
setTimeout(() => ws.close(), 5000);
}
With WS_URL set to your endpoint, run k6 run --vus 1 --iterations 1 ws.js, then k6 run --vus 20 --duration 1m ws.js. Five seconds, 20 users and the 500 ms threshold are example test settings, not vendor limits or service targets. Each iteration opens a socket, sends one probe and holds the session until the timer; it does not model sustained chat traffic. Add paced messages, unique correlation IDs and reconnect behavior only after the smoke test passes. The current socket API supplies event handlers and timers; Grafana recommends k6/websockets for new tests rather than the deprecated experimental module. Protocol guide.
As of November 2026, for Locust, install locust==2.47.0 and a current stable websocket-client in your test environment. Save this alternative as locustfile.py:
import os
import time
import websocket
from locust import User, task, constant
class SocketUser(User):
wait_time = constant(1)
def on_start(self):
self.ws = websocket.create_connection(os.environ['WS_URL'], timeout=5)
@task
def echo(self):
start = time.perf_counter()
error, size = None, 0
try:
self.ws.send('probe')
reply = self.ws.recv()
size = len(reply)
if reply != 'probe':
raise ValueError('unexpected echo')
except Exception as exc:
error = exc
self.environment.events.request.fire(
request_type='WS', name='echo',
response_time=(time.perf_counter() - start) * 1000,
response_length=size, exception=error)
def on_stop(self):
if hasattr(self, 'ws'):
self.ws.close()
Run locust --headless -u 1 -r 1 -t 30s. Locust's non-HTTP guide requires a gevent-compatible client and explicit request events; without those events a socket can be busy while charts show no application requests. This minimal adapter measures echo exchanges only: instrument handshake failures separately, close/reconnect failed sessions, and add a receive loop for unsolicited pushes before a larger run. See the Locust quickstart for running users.
Versions, licences and costs — checked 2026-11-24
| Option | Stable release / licence | Cost and limits |
|---|---|---|
| k6 | As of November 2026, 2.4.0; prior 2.3.0, AGPL-3.0 | Self-run software has no per-user service fee; you provide generator capacity. Hosted service pricing is separate. |
| Locust | As of November 2026, 2.47.0, MIT | Self-run software has no per-user service fee; client integration and generator machines are your responsibility. |
Neither table row is a guaranteed socket ceiling. Measure generator CPU, memory and connection failures alongside server behavior.
When to pick which
| Option | Wins | Loses | Honest pick |
|---|---|---|---|
| k6 | Built-in socket API and JavaScript test code | Existing Python business flows would need rewriting | Pick this if you want the shortest route to an instrumented socket test. |
| Locust | Python user flows and an existing Locust suite | You cannot maintain a gevent-compatible protocol wrapper and explicit metrics | Pick this if Python integration saves more work than the adapter costs. |
My solo/small-team default is k6. A Python-heavy small team can keep Locust. For enterprise testing, keep the existing supported runner if it models authentication and session behavior correctly; distribute load only after measuring generator saturation.
Public user evidence
- “keep them open” — AlexGustafsson, 2018-12-10, k6 #865 describes long-lived sockets across iterations. Historical report, not a current API limitation claim.
- “Avoid connection overhead in every iteration” — udamir, 2025-11-09, k6 #5382 requests VU lifecycle hooks. A feature request is not a benchmark or proof the hooks shipped.
No independent Locust WebSocket trial is cited here.
Prompt for your agent
Model our real socket protocol with authentication, acknowledgements, session duration and paced messages. Prove one client first, then ramp gradually. Report delivered-message latency and failures separately from handshakes, and watch generator saturation.
Mistakes
- Treating a raw WebSocket client as a Socket.IO client.
- Counting connected users as successful application messages.
- Comparing these two starters as a benchmark: their session and message schedules differ.
Limits
Neither starter was executed. The echo assumptions do not cover Socket.IO, broadcast fan-out, token refresh, binary frames or reconnect storms. Community evidence is thin and mostly historical; no comparative capacity result is available here.
Started from a post by @Grafana Labs, packaged by the editor. Original post