FULL AI ANALYSIS

NGINX returns 502 on WebSocket upgrade when TLS session resumption and upstream keepalive enabled

Generated Oct 24, 2026, 9:21:01 AM

Analysis summary

502 occurs when NGINX attempts to reuse an upstream keepalive connection that the upstream has already closed; with TLS session resumption enabled, clients attempt fast reconnects and NGINX reuses backend sockets for Upgrade requests. If a backend has closed the socket (silent idle timeout, or backend closed on TLS session mismatch), NGINX observes a premature close during header read and returns 502. Reduced keepalive lowered frequency, but root cause is mismatch between backend idle timeouts and NGINX keepalive reuse for Upgrade handshakes.

Possible causes

Upstream (Node.js) silently closed idle keepalive sockets earlier than NGINX expects (idle timeout mismatch)

90%

Upstream process closes connections when TLS session-resumed requests cause different connection handling (edge case in app code resetting sockets on resumed connections)

30%

OS-level ephemeral port reuse or TCP TIME_WAIT boundary causing transient socket reuse issues between NGINX and upstream

20%

NGINX bug in handling Upgrade when reusing a keepalive backend that recently closed (older NGINX build regression)

10%

Suggested fixes

1

Diagnostic step 1

Check and align timeouts: inspect Node.js server keepAliveTimeout and NGINX keepalive_timeouts. Set Node.js server.keepAliveTimeout > NGINX proxy_read_timeout + a margin.

2

Diagnostic step 2

Disable NGINX reuse for WebSocket Upgrade requests by adding proxy_set_header Connection $connection_upgrade and set proxy_http_version to 1.1 and add: map $http_upgrade $connection_upgrade { default 'upgrade'; '' 'close'; } to force new backend TCP handshake on Upgrade.

3

Diagnostic step 3

If keepalive reuse is required, enable proxy_next_upstream to retry on error and lower keepalive connections to reduce stale sockets.

4

Diagnostic step 4

Upgrade NGINX and Node.js to latest stable if on older minor versions; test with a controlled load.

5

Diagnostic step 5

Collect tcpdump on client<->NGINX and NGINX<->upstream for failed Upgrade to confirm backend FIN before NGINX send.