Implementing WebSocket Support
1. Configuring WebSocket Endpoints
Example: NGINX WebSocket proxy
location /ws/ {
proxy_pass http://ws_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
| Setting | Required |
|---|---|
| HTTP/1.1 | Yes (upgrade requires) |
| Upgrade header forwarded | Yes |
| Long timeouts | Yes (idle connections) |
| No buffering | Yes (streaming) |
2. Setting Up WebSocket Routing
| Match | Example |
|---|---|
| Path prefix | /ws/chat |
| Subprotocol | Sec-WebSocket-Protocol: graphql-ws |
| Origin check | CORS for WS |
| Sticky LB | Hash by session |
3. Implementing WebSocket Authentication
| Method | Detail |
|---|---|
| Cookie + Origin check | Browser auto |
| Query param token | ?token=jwt (logged risk) |
| First message auth | Send token after connect |
| Subprotocol token | Sec-WebSocket-Protocol: token, jwt-xxx |
4. Configuring Connection Timeouts
| Timeout | Recommended |
|---|---|
| Handshake | 10s |
| Idle (no traffic) | 5 min + ping/pong |
| Max session | 1-24h, then force reconnect |
| Ping interval | 30s |
5. Setting Message Size Limits
| Limit | Default |
|---|---|
| Per-message | 64 KB - 1 MB |
| Per-frame | 64 KB |
| Per-client send rate | 100 msg/sec |
| Connections per IP | 20-100 |
6. Implementing WebSocket Load Balancing
| Strategy | Notes |
|---|---|
| IP hash | Sticky, simple |
| Cookie hash | Survives IP change |
| Least conn | Best for long-lived |
| Consistent hash | Pub/sub topic routing |
7. Using WebSocket Health Checks
| Method | Notes |
|---|---|
| HTTP /healthz | Indirect (parallel) |
| WS ping frame | Server pings client |
| Custom heartbeat | App-level {type:"ping"} |
| Close on miss | Drop after 2 missed pongs |
8. Configuring Compression
| Extension | Detail |
|---|---|
permessage-deflate | RFC 7692 |
| Server max window | 15 (default) |
| Context takeover | Reuses dictionary, more compress |
| CPU vs bandwidth | Disable for small msgs |
9. Setting Up WebSocket Logging
| Event | Log Field |
|---|---|
| Connect | session_id, user, origin, subprotocol |
| Message | count, bytes (not body for PII) |
| Close | close_code, reason, duration |
| Error | error code, stack |
10. Implementing Connection Pooling
| Setting | Value |
|---|---|
| Max conns per worker | 10k-50k (epoll) |
| Per-IP limit | 50-100 |
| Backpressure | Drop oldest msg in queue |
| Reconnect backoff (client) | Exponential + jitter |