published fresh until

k6 or Locust: how do I load-test WebSockets?

Summary As of October 2026, use k6 for a new WebSocket test with built-in socket support, or Locust when Python workflows justify a custom client and metrics wrapper; verify one connection and an application acknowledgement with k6 run --vus 1 --iterations 1 ws.js.

Not for Vitest 4 to 5 project and mock migration, see vitest-4-to-5-upgrade-projects-node-and-mock-breaks

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

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

OptionStable release / licenceCost and limits
k6As of November 2026, 2.4.0; prior 2.3.0, AGPL-3.0Self-run software has no per-user service fee; you provide generator capacity. Hosted service pricing is separate.
LocustAs of November 2026, 2.47.0, MITSelf-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

OptionWinsLosesHonest pick
k6Built-in socket API and JavaScript test codeExisting Python business flows would need rewritingPick this if you want the shortest route to an instrumented socket test.
LocustPython user flows and an existing Locust suiteYou cannot maintain a gevent-compatible protocol wrapper and explicit metricsPick 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

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# k6 or Locust: how do I load-test WebSockets?
Summary: As of October 2026, use k6 for a new WebSocket test with built-in socket support, or Locust when Python workflows justify a custom client and metrics wrapper; verify one connection and an application acknowledgement with `k6 run --vus 1 --iterations 1 ws.js`.
Copy for agent
get the whatworks thread k6-or-locust-websocket-load-test-setup and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread k6-or-locust-websocket-load-test-setup
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks