Skip to content

Caddy WebSocket reverse proxy in production

Proxying WebSocket connections through Caddy — timeouts, buffering, keep-alives, and the operational tuning an MSP applies for chat, dashboards, and realtime APIs.

WebSocket traffic through a reverse proxy is one of those things that “just works” until you scale it: timeouts kick in mid-conversation, dashboards show TLS errors that turn out to be idle disconnects, the upstream is dropping connections that the client never closed. This article is the configuration and operational tuning we deploy at clients running chat backends, live dashboards, MQTT-over-WebSocket gateways, and any application where a long-lived bidirectional connection is on the critical path.

How to verify

A working WebSocket connection looks like this from the outside:

curl -i -N -H 'Connection: Upgrade' -H 'Upgrade: websocket' \
  -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
  -H 'Sec-WebSocket-Version: 13' \
  https://app.example.com/ws
wscat -c wss://app.example.com/ws
sudo journalctl -u caddy --since '5m ago' | grep -i 'websocket\|upgrade'
ss -tnp | grep -E ':(80|443).*ESTAB' | wc -l

The curl should return 101 Switching Protocols and not close. wscat should connect and echo. The journal should show no error reading upstream patterns. The ss count tells you how many active long-lived connections Caddy is brokering — useful for capacity sanity checks.

What’s happening

WebSocket starts as an HTTP request. The client sends a GET with Connection: Upgrade and Upgrade: websocket headers. The server (the upstream, not Caddy) accepts with a 101 Switching Protocols response. After that, the connection is no longer HTTP — both sides exchange WebSocket framed messages until one side closes.

Caddy’s reverse_proxy directive handles this natively. There is no special directive, no proxy_set_header Upgrade $http_upgrade boilerplate like Nginx requires. Caddy detects the Upgrade header in the request, opens the upstream connection, forwards the upgrade response, and then pipes bytes in both directions until either end closes. The HTTP/1.1 keep-alive plumbing in transport http does not interfere — the connection is “owned” by the WebSocket handler.

The operational issues come from timeouts. By default Caddy will hold a WebSocket connection open as long as both ends are active. But the upstream may have its own idle timeout, the load balancer or NAT in the middle may drop the connection after a quiet period, and the client may go to sleep on a mobile device. The solution is application-level pings (the WebSocket protocol has a built-in ping/pong frame for exactly this) plus per-hop timeout tuning.

The procedure

  1. The minimal WebSocket proxy. No special directives needed:

    app.example.com {
        reverse_proxy localhost:3000
    }

    reverse_proxy detects the upgrade and forwards. HTTPS termination, automatic. Done.

  2. Tune the upstream connection lifetime. For long-lived WebSocket connections, Caddy’s read/write timeouts on the upstream connection must allow for idle periods between application-level frames:

    app.example.com {
        reverse_proxy localhost:3000 {
            transport http {
                read_buffer 4KB
                write_buffer 4KB
                dial_timeout 5s
                read_timeout 0
                write_timeout 0
            }
        }
    }

    read_timeout 0 and write_timeout 0 disable per-IO timeouts. WebSocket connections that are idle (no frames in flight) are kept alive by the upstream’s ping policy, not by Caddy.

  3. Handle the Origin header. WebSocket clients send Origin (the originating page URL). The upstream may check it for cross-origin protection — but the upstream sees Caddy as the immediate peer. Forward the original Origin:

    app.example.com {
        reverse_proxy localhost:3000 {
            header_up Origin {>Origin}
            header_up Host {host}
        }
    }

    The {>Origin} is the request’s Origin header, passed through unchanged.

  4. Multiple WebSocket upstreams with sticky-by-IP. A chat backend where each client should stay on the same upstream (for in-memory channel state):

    chat.example.com {
        reverse_proxy ws-1.internal:3000 ws-2.internal:3000 ws-3.internal:3000 {
            lb_policy ip_hash
            health_uri /health
            health_interval 5s
            health_timeout 1s
        }
    }

    ip_hash picks the upstream by hashing the client’s source IP — the same client always hits the same upstream as long as the upstream is healthy. For a chat application with channel-local state, this avoids cross-upstream lookups.

  5. WebSocket plus HTTP on the same route prefix. Some apps mix WebSocket and HTTP under /api/:

    app.example.com {
        @websocket {
            header Connection *Upgrade*
            header Upgrade websocket
        }
    
        handle /api/* {
            reverse_proxy localhost:3000 {
                transport http {
                    read_timeout 0
                    write_timeout 0
                }
            }
        }
    }

    The @websocket matcher is informational here; reverse_proxy handles the upgrade automatically. The per-handler timeout tuning applies to both HTTP and WebSocket on the same route.

  6. Backend pings to keep NAT alive. This is application-level, not Caddy — but it is the operational fix for “disconnects after exactly five minutes” reports. Configure your WebSocket server to send a ping every 30-60 seconds:

    // Node.js example with ws
    const wss = new WebSocket.Server({ port: 3000 });
    wss.on('connection', (ws) => {
      const interval = setInterval(() => {
        if (ws.readyState === WebSocket.OPEN) ws.ping();
      }, 30000);
      ws.on('close', () => clearInterval(interval));
    });

    The browser’s WebSocket implementation responds to pings automatically. Mid-path NAT and load balancer idle timeouts are reset on every frame, including pings.

Operational notes

  • Caddy’s metric caddy_http_requests_in_flight includes WebSocket connections. A WebSocket connection that has been open for an hour shows as one in-flight request — useful for capacity planning, but do not alert on absolute counts unless you expect short-lived requests only.
  • The Sec-WebSocket-Protocol header negotiates subprotocols (e.g., MQTT-over-WebSocket uses mqtt here). Caddy passes this through unchanged.
  • Closing Caddy with systemctl restart caddy drops every WebSocket connection. Use systemctl reload caddy (which sends SIGUSR1 — graceful reload) for config changes. Full restarts should be scheduled.
  • A read_timeout 0 on the upstream side means an idle WebSocket connection stays open forever from Caddy’s view. If the upstream goes away silently (kernel panic, network partition), Caddy may hold the connection for many minutes before TCP keepalive triggers a close. Set tcp_keepalive at the system level (net.ipv4.tcp_keepalive_time = 60 in sysctl.conf) to bound this.
  • WebSocket-over-HTTP/2 is supported in Caddy via the WebSocket extensions in RFC 8441. Most browsers do not yet send WebSocket upgrades over HTTP/2 — they fall back to HTTP/1.1 on the same connection. Plan accordingly.

Stack Harbor runs WebSocket fleets for clients building chat, dashboards, and realtime APIs — health checks tuned for long-lived connections, upstream affinity policies under config management, and the metric pipeline alerting on disconnect rate, not just request rate. If you have a realtime workload on Caddy that needs the timeout and load-balancing policies set right for the traffic shape, this is the kind of work covered by our Managed Operations practice.