JMeter HTTP/2 and WebSocket Testing: A Practical Guide

JMeter HTTP/2 and WebSocket Testing: A Practical Guide

JMeter's built-in HTTP sampler defaults to HTTP/1.1. If your API runs over HTTP/2 or your application uses WebSockets for real-time features, you need additional plugins and a different approach to test plan design.

This guide covers practical setup and common patterns for testing both HTTP/2 APIs and WebSocket connections in JMeter.

HTTP/2 Testing in JMeter

Why HTTP/2 Matters for Load Testing

HTTP/2 introduces multiplexing — multiple requests share a single TCP connection instead of requiring separate connections. This changes how load generators behave:

  • HTTP/1.1: JMeter opens multiple TCP connections per thread to simulate concurrent requests
  • HTTP/2: A single connection handles multiple concurrent streams

Testing an HTTP/2 API with JMeter's default HTTP/1.1 sampler doesn't simulate real client behavior. Your load test might also underperform because HTTP/1.1 clients need connection pool management that HTTP/2 doesn't.

Installing the HTTP/2 Plugin

JMeter's built-in HTTP sampler doesn't natively support HTTP/2. Use the HTTP/2 Sampler from JMeter Plugins.

Via Plugins Manager (recommended):

  1. Download JMeter Plugins Manager
  2. Place the JAR in JMETER_HOME/lib/ext/
  3. Restart JMeter
  4. Go to Options → Plugins Manager
  5. Search for "HTTP2 Sampler" and install

Manually: Download jmeter-plugins-http2-X.X.X.jar from the repository and place it in JMETER_HOME/lib/ext/. You also need the Jetty HTTP/2 client JARs:

  • jetty-http-*.jar
  • jetty-io-*.jar
  • jetty-util-*.jar
  • http2-client-*.jar
  • http2-common-*.jar
  • http2-hpack-*.jar

Place all in JMETER_HOME/lib/.

Configuring HTTP/2 Requests

After installation, add an "HTTP/2 Sampler" from the Sampler menu:

Field Value Notes
Server Name api.example.com Without protocol prefix
Port 443 HTTP/2 typically requires TLS
Path /api/v2/users Request path
Method GET/POST/etc. Standard HTTP methods
Protocol https HTTP/2 requires HTTPS in most cases

HTTP/2 connections are shared per host within a thread, so multiple HTTP/2 Samplers in the same thread automatically benefit from multiplexing.

Verifying HTTP/2 is Active

Add a JSR223 Post-Processor to confirm your requests are using HTTP/2:

def responseHeaders = prev.getResponseHeaders()
log.info("Response headers for ${prev.getSampleLabel()}:")
log.info(responseHeaders)

// HTTP/2 responses include this pseudo-header in some implementations
// Check server response headers for h2 protocol indicators
if (responseHeaders.contains("x-http2-stream-id") || 
    responseHeaders.contains(":status")) {
    log.info("HTTP/2 confirmed for ${prev.getSampleLabel()}")
}

Alternatively, enable jmeter.httpsampler.response_header to see raw protocol headers.

HTTP/2 Server Push Testing

HTTP/2 server push is a feature where the server proactively sends resources the client hasn't requested. The HTTP/2 plugin handles pushed resources automatically — they appear as sub-samples in the results.

To verify push is working:

// Post-processor after a request that triggers server push
def subResults = prev.getSubResults()
if (subResults != null && subResults.length > 0) {
    log.info("Server pushed ${subResults.length} resources:")
    subResults.each { sub ->
        log.info("  - ${sub.getUrlAsString()} (${sub.getBytes()} bytes)")
    }
}

WebSocket Testing

WebSocket vs HTTP: What's Different

HTTP is request-response: client sends a request, server responds, connection closes (or is reused for the next request). WebSocket is a persistent bidirectional channel: the connection stays open and either side can send messages at any time.

For load testing, this means:

  • Each virtual user maintains a persistent WebSocket connection
  • You need to model connect, send messages, receive messages, and disconnect separately
  • Think time between messages matters more than in HTTP testing
  • Connection count is a key metric (WebSocket connections are stateful resources)

Installing the WebSocket Sampler

Use the WebSocket Samplers by Peter Doornbosch plugin. It's the most actively maintained and feature-complete.

Via Plugins Manager:

  1. Options → Plugins Manager
  2. Search "WebSocket Samplers by Peter Doornbosch"
  3. Install

This plugin adds four samplers:

  • WebSocket Open Connection — establishes the WebSocket connection
  • WebSocket Close — cleanly closes the connection
  • WebSocket Single Read Sampler — reads one message from the server
  • WebSocket request-response Sampler — sends a message and waits for a response
  • WebSocket Ping/Pong Sampler — sends a ping and waits for pong

Basic Test Plan Structure

A typical WebSocket test looks like:

Thread Group (100 users)
├── HTTP Cookie Manager  (if auth cookies are needed)
├── [Once Only Controller]
│   └── HTTP Request — Login (get auth token)
├── WebSocket Open Connection
│   └── Server: ws.example.com
│       Path: /chat?token=${auth_token}
├── Loop Controller (10 iterations)
│   ├── JSR223 Sampler — Build message
│   ├── WebSocket request-response Sampler
│   └── Uniform Random Timer (500ms-2000ms)
└── WebSocket Close

WebSocket Open Connection Configuration

Field Value
Server ws.example.com
Port 443
Path /chat
Connection upgrade request (built-in, handled automatically)
Use SSL checked (for wss://)

For authenticated connections passing token in query params:

Path: /chat?token=${auth_token}&userId=${user_id}

For connections requiring headers: Add the headers in the element's "Additional headers" section:

Authorization: Bearer ${auth_token}

Sending and Receiving Messages

WebSocket request-response Sampler — use for request/response patterns where each message has a corresponding reply:

// Request body (set in sampler)
{
    "type": "subscribe",
    "channel": "market:${symbol}",
    "requestId": "${__UUID()}"
}

Set a response condition to know when the response has arrived:

  • Response pattern: "type":"subscribed" — regex match on the response body
  • Read timeout: 5000ms — fail if no response in 5 seconds

WebSocket Single Read Sampler — use when the server sends messages without a corresponding request (push-based):

Read timeout: 3000ms
Response pattern: .* (accept any message)
Close connection on timeout: false

Simulating Real Chat Load

A realistic chat load test needs to model multiple message types:

Thread Group (50 users)
├── WebSocket Open Connection
├── [Once Only Controller]
│   └── WebSocket request-response — Join room
│       Body: {"type":"join","room":"general"}
│       Response condition: "type":"joined"
├── Random Controller
│   ├── (60%) WebSocket request-response — Send message
│   │   Body: {"type":"message","text":"Test message ${__counter(,)}"}
│   │   Response condition: "type":"message_ack"
│   ├── (30%) WebSocket Single Read — Receive message
│   │   Timeout: 2000ms
│   └── (10%) WebSocket Ping/Pong — Keepalive
├── Uniform Random Timer (1000ms-5000ms)
└── [Teardown Thread Group]
    └── WebSocket Close

Handling WebSocket Authentication Flows

Many WebSocket servers require authentication immediately after connection:

WebSocket Open Connection
    Server: realtime.example.com
    Path: /socket
    
WebSocket request-response — Authenticate
    Body: {"type":"auth","token":"${auth_token}"}
    Response condition: "type":"auth_success"
    Timeout: 5000ms
    
[If authentication fails → treat as error]
JSR223 Post-Processor:
    if (prev.getResponseDataAsString().contains('"type":"auth_error"')) {
        prev.setSuccessful(false)
        prev.setResponseMessage("WebSocket auth failed")
    }

Metrics to Monitor for WebSocket Tests

WebSocket tests generate different metrics than HTTP tests:

Metric What it means
Connection establishment time Time for WebSocket handshake (counted in Open Connection sampler)
Message round-trip time Time from send to matching response (request-response sampler)
Messages per second Throughput — how many messages the server handles
Active connections Concurrent open WebSocket connections
Connection error rate Failed connections or dropped connections

For the server side, monitor:

  • Open file descriptors (each WebSocket connection uses one)
  • Memory per connection (WebSocket servers keep per-connection state)
  • Thread or event loop saturation

Common WebSocket Test Issues

"Connection refused" or immediate close:

  • Server may require specific subprotocols — set in the Open Connection element's "Sub protocols" field
  • Origin header may be required — add to "Additional headers"
  • Authentication may need to happen via HTTP first (get session cookie, then use wss://)

Messages not matching expected response:

  • Response pattern is case-sensitive regex
  • Adjust pattern to match actual server response format
  • Use .* during debugging to capture all responses, then narrow down

Memory growing during long test:

  • Message buffers accumulating if not consumed
  • Use WebSocket Single Read Samplers to drain the connection's receive buffer
  • Check server-side push rate vs. your client read rate

Connections dropping during sustained test:

  • Server-side idle timeout — add Ping/Pong sampler on a timer
  • Network-level timeout — add WebSocket Ping with interval matching the network timeout

Combining HTTP and WebSocket in One Test Plan

Many applications use both REST endpoints (for initial data loading) and WebSockets (for real-time updates):

Thread Group
├── HTTP Request — GET initial data (HTTP/1.1 or HTTP/2)
├── JSR223 — Extract subscription IDs from response
├── WebSocket Open Connection
├── WebSocket request-response — Subscribe to updates
│   Body: {"subscribe": ${__groovy(vars.get('ids').join(','))}}
├── Loop Controller (receive updates for 60 seconds)
│   ├── WebSocket Single Read (timeout: 1000ms, close on timeout: false)
│   └── JSR223 — Process and validate received data
└── WebSocket Close

This pattern tests the realistic user journey: load the page (HTTP), then establish real-time connection (WebSocket).

Wrapping Up

HTTP/2 and WebSocket testing in JMeter require plugins and a different mental model from HTTP/1.1 testing, but both are well-supported. The HTTP/2 plugin handles multiplexing transparently once configured. WebSocket testing requires explicit connect/send/receive/close steps that map to the protocol's stateful nature.

For WebSocket-heavy applications (chat, live dashboards, collaborative tools), the WebSocket samplers by Peter Doornbosch cover most scenarios. For HTTP/2 APIs, verify the plugin is active and that your connections are actually using multiplexing before drawing conclusions from the results.

Read more

Start now free