Skip to main content
Test WebSocket connections for real-time applications including chat, notifications, live updates, and streaming data.

WebSocket Testing Overview

WebSockets provide full-duplex communication over a single TCP connection. Unlike HTTP, WebSocket connections remain open, allowing servers to push data to clients. Common use cases:
  • Real-time chat applications
  • Live notifications
  • Collaborative editing
  • Gaming servers
  • Financial market data streams
  • IoT device communication

Basic WebSocket Example

This example tests the QuickPizza WebSocket API where multiple users connect and exchange messages:
Status code 101 indicates “Switching Protocols” - the expected response when upgrading from HTTP to WebSocket.

WebSocket Event Handlers

k6 WebSocket API provides several event handlers:
Triggered when the connection is established:

Advanced Patterns

Authenticated WebSocket Connection

Authenticate during setup and use token in WebSocket connection:

Message Rate Control

Control how frequently messages are sent:

Response Validation

Validate server responses and track metrics:

Load Testing Scenarios

Ramping VUs for WebSocket Connections

Gradually increase concurrent connections:

Multiple WebSocket Connections per VU

Simulate users with multiple concurrent WebSocket connections:
Each VU opens separate connections. With 10 VUs and 3 connections each, you’ll have 30 total WebSocket connections.

Best Practices

Always close connections gracefully:
Match production behavior:
Track connection status and errors:
Define success criteria for WebSocket tests:

Common Issues

Connection Refused

If connections fail, verify:
  • URL scheme is wss:// (secure) or ws:// (insecure)
  • Server accepts WebSocket upgrade requests
  • Authentication tokens are valid
  • Firewall rules allow WebSocket connections

High Memory Usage

For long-running tests:
  • Close connections properly
  • Don’t accumulate messages in memory
  • Use appropriate VU ramp-down periods

Timeout Issues

Adjust WebSocket timeout settings:

Custom Metrics

Track WebSocket-specific metrics

Test Scenarios

Create realistic load patterns

Data Generation

Generate realistic message payloads

API Reference: k6/ws

Complete WebSocket API documentation