Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Protocols and APIs

Load Testing WebSockets and gRPC with k6

Test long-lived WebSocket sessions and gRPC calls with k6: event handlers, timers, message metrics, proto files, status codes and what to measure for real-time systems.

HTTP request/response is only one shape of traffic. Chat, live dashboards and multiplayer games keep a connection open and push messages both ways. Internal microservices often talk gRPC. k6 supports both, and the way you think about load changes: you are no longer counting requests per second but sessions, messages and call latency.

Honesty note. k6 cannot run on this site, so k6/ws and k6/net/grpc code is read-only. The runnable blocks are Node stand-ins that show the event model and the status handling; they are not k6 and do not speak the real WebSocket or gRPC wire protocols.

WebSockets in k6

The classic module is k6/ws. You open a connection and describe what happens through event handlers; the function you pass runs until the socket closes.

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

export default function () {
  const url = 'wss://chat.example.test/socket';
  const res = ws.connect(url, { tags: { name: 'chat' } }, function (socket) {
    socket.on('open', () => {
      socket.send(JSON.stringify({ type: 'join', room: 'lobby' }));
      socket.setInterval(() => socket.send(JSON.stringify({ type: 'ping' })), 1000);
    });

    socket.on('message', (data) => {
      const msg = JSON.parse(data);
      if (msg.type === 'welcome') console.log('joined as', msg.user);
    });

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

    socket.setTimeout(() => socket.close(), 10000); // stay for 10 s
  });

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

Key ideas:

  • ws.connect(url, params, callback) blocks the VU until the socket closes. A VU holds one session at a time, so 500 VUs means about 500 concurrent connections.
  • Use socket.setTimeout and socket.setInterval, not the global timers, to schedule work tied to the socket.
  • Handlers include open, message, binaryMessage, ping, pong, close and error.
  • The HTTP upgrade response has status 101 Switching Protocols, which you can check.

k6 also ships a newer, browser-style API (k6/websockets) with new WebSocket(url), ws.onopen, ws.onmessage and so on, and it lets one VU run several sockets concurrently. The concepts below apply to both.

Metrics you get for free

Metric Meaning
ws_sessions Number of sessions started
ws_session_duration How long sessions lasted
ws_connecting Time to establish the connection
ws_msgs_sent / ws_msgs_received Message counts
ws_ping Round-trip time of ping frames

For a chat system, the number that users feel is message latency (send to receive). k6 does not measure it for you because only your protocol knows which reply matches which message. You compute it yourself with a custom Trend metric (see Custom metrics): put a timestamp in the message and subtract it when the echo returns.

Node.js Stand-in: socket events and message round-trip latency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Designing a WebSocket test

A realistic realtime test has three phases per session: connect, an activity pattern (messages at human or device pace), and a clean close. Avoid two common traps:

  1. Everyone connecting at once. A ramp-up gives the server time to accept connections; a thundering herd tests the load balancer, not your application.
  2. Sessions that never end. Always close sockets with a timeout; otherwise iterations pile up and the VU count means nothing.

Also vary the message rate. A user who types occasionally and a sensor that sends 10 messages a second are different workloads.

gRPC in k6

gRPC uses Protocol Buffers over HTTP/2. k6 loads your .proto files at startup, opens a client connection once per VU, and invokes methods by their full name.

JavaScript
import grpc from 'k6/net/grpc';
import { check, sleep } from 'k6';

const client = new grpc.Client();
client.load(['./proto'], 'orders.proto'); // init stage

export default function () {
  client.connect('orders.example.test:443'); // add { plaintext: true } for non-TLS
  const response = client.invoke('shop.Orders/GetOrder', { id: 42 });

  check(response, {
    'status is OK': (r) => r && r.status === grpc.StatusOK,
    'order has items': (r) => r.message.items.length > 0,
  });

  client.close();
  sleep(1);
}

Things to remember:

  • client.load(importPaths, ...protoFiles) must be called in the init context.
  • The method name is package.Service/Method.
  • A response has status (a gRPC code, not an HTTP code), message, headers and trailers.
  • Unary calls use invoke. Streaming uses grpc.Stream.
  • If the server exposes reflection, client.connect(addr, { reflect: true }) lets you skip the proto files.
  • Metrics include grpc_req_duration and, for streams, grpc_streams, grpc_streams_msgs_sent and grpc_streams_msgs_received.

Important status codes: 0 OK, 3 INVALID_ARGUMENT, 5 NOT_FOUND, 8 RESOURCE_EXHAUSTED (often rate limits), 13 INTERNAL, 14 UNAVAILABLE, 4 DEADLINE_EXCEEDED. Under overload, UNAVAILABLE and DEADLINE_EXCEEDED are the ones to watch.

Node.js Stand-in: checking gRPC-style status codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What to measure

Protocol Primary signals
WebSocket Concurrent sessions held, connect time, message latency, dropped sessions, error events
gRPC grpc_req_duration percentiles, share of non-OK statuses, stream message rates

Put thresholds on the ones that matter, such as checks for message arrival and grpc_req_duration p(95). Built-in metrics shows what k6 records for you in the next chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In k6/ws, what does ws.connect() do with the VU?

    The callback runs until the socket closes, so each VU holds one session at a time. Concurrent connections roughly equal VUs.
  2. 2. Why does k6 not report end-to-end chat message latency automatically?

    You embed a timestamp or id in the message and record the difference in a custom Trend metric when the reply arrives.
  3. 3. Where must client.load() for gRPC proto files be called?

    Proto files are loaded at init time. The connection and invoke calls then happen in the VU code.
  4. 4. Which gRPC status suggests the service is overloaded or unreachable?

    UNAVAILABLE and DEADLINE_EXCEEDED are typical under overload; NOT_FOUND and INVALID_ARGUMENT are usually test-data problems.

Summary

  • k6/ws runs one session per VU through event handlers and timers; the 101 status confirms the upgrade.
  • Measure message latency yourself with a custom Trend.
  • gRPC needs .proto loading at init, package.Service/Method names and checks on gRPC status codes.
  • Ramp connections gradually and always close sockets.

Next: Authentication and Correlation