Learn Labs
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.

map $http_upgrade $connection_upgrade {in http {}default upgrade;'' '';plain requests keep upstream keepalive}location /ws {proxy_pass http://app;proxy_http_version 1.1;Upgrade doesn't exist in HTTP/1.0proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $connection_upgrade;proxy_set_header Host $host;proxy_read_timeout 1h;an idle socket is normal here}

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 forward Upgrade, the backend saw an ordinary GET and answered 200 with JSON. The client was expecting 101 and gave up.

Long-lived connections change operations

  • Reloads don't cut WebSockets immediately: old workers keep them until they close or worker_shutdown_timeout expires. 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_connections and file descriptors for 100,000 (client plus upstream side).

Lab

  1. 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?
  2. Set proxy_read_timeout 5s in /ws, start the app without heartbeats, and measure when the socket dies.
  3. Open 100 WebSockets and reload Nginx. How many old worker processes remain afterwards, and for how long?

On this page