Serving & Proxying
WebSockets
The Upgrade handshake, long-lived connections, and pinning
A WebSocket starts as an HTTP/1.1 request with Upgrade: websocket and
Connection: Upgrade. If the server agrees (101 Switching Protocols),
the same TCP connection becomes a two-way message channel that can stay
open for hours.
Upgrade and Connection are hop-by-hop headers: a proxy doesn't
forward them unless told to. So a WebSocket through Nginx needs explicit
configuration.
Tested
docker compose -f compose_prod.yaml run --rm labs python websockets_lab.py
9 connections, served by: app-1: 3, app-2: 3, app-3: 3
example echo: app-1 echo: message 0
one connection, 5 messages over 2.5 s: always ['app-2'] (opened on app-2)
handshake through /api/ (no Upgrade forwarding): InvalidStatus server rejected WebSocket connection: HTTP 200- Connections are balanced; messages aren't. Once upgraded, Nginx just copies bytes both ways on that TCP connection. Every message on it goes to the same instance for the connection's whole life.
- Through
/api/, which doesn't forwardUpgrade, the backend saw an ordinary GET and answered200with JSON. The client was expecting101and gave up.
Long-lived connections change operations
Common mistake
proxy_read_timeout applies to WebSockets too. With the server-wide 5 s,
any socket quiet for 5 seconds would be cut. This location sets an hour,
and the app sends a ping every 20 seconds (heartbeat=20) so idle
connections stay alive through every proxy and load balancer on the way.
- Reloads don't cut WebSockets immediately: old workers keep them until
they close or
worker_shutdown_timeoutexpires. Without that setting, a reload can leave old workers alive for hours, holding memory. - Deploying the app closes its sockets; clients must reconnect, with backoff and jitter, or a deploy becomes a thundering herd.
- Balance is uneven over time: a restarted instance gets no existing connections back. Least-connections helps for new ones.
- Capacity counts connections, not requests: 50,000 idle sockets need
worker_connectionsand file descriptors for 100,000 (client plus upstream side).
Lab
- Run
websockets_lab.py. Then stop the instance holding a connection (docker stop app-2) while the lab is mid-session. What does the client see? - Set
proxy_read_timeout 5sin/ws, start the app without heartbeats, and measure when the socket dies. - Open 100 WebSockets and reload Nginx. How many old worker processes remain afterwards, and for how long?