FULL AI ANALYSIS

Nginx returns 502 for long-lived GraphQL subscription requests only when upstream keepalive is enabled

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

Analysis summary

502s for long-lived websocket connections with upstream keepalive usually indicate connection reuse being applied to upgrade-capable endpoints that expect dedicated long-lived sockets. NGINX may hand a kept-alive socket to a new client or reuse a socket that the app closed, causing 'upstream closed' errors during upgrade. Proper settings: ensure proxy_http_version 1.1, add 'proxy_set_header Connection "Upgrade"' and 'proxy_set_header Upgrade $http_upgrade' for websocket paths, set 'proxy_buffering off' and raise 'proxy_read_timeout' sufficiently. For upstream keepalive with websockets, use a dedicated upstream block for ws paths without keepalive or configure NGINX stream module for raw TCP if appropriate.

Possible causes

NGINX reuses keepalive sockets for new requests while the backend expects a dedicated connection for websocket upgrade, causing the upgrade to fail.

75%

Backend closes idle keepalive sockets; NGINX hands a closed socket to client leading to 502.

55%

proxy_read_timeout too low for long-lived subscriptions causing NGINX to drop connection.

40%

Mismatch in HTTP version or missing Upgrade/Connection headers for websocket handshake when proxying.

30%

Suggested fixes

1

Diagnostic step 1

Separate routes: create an upstream (or location) dedicated for websocket/subscription paths without 'keepalive' set, and keep keepalive for short API requests.

2

Diagnostic step 2

Ensure websocket proxy settings in subscription location: 'proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade;' and define 'map $http_upgrade $connection_upgrade { default upgrade; '' close; }'.

3

Diagnostic step 3

Set 'proxy_buffering off' and increase 'proxy_read_timeout' to match expected subscription lifetime (e.g., 3600s).

4

Diagnostic step 4

Monitor NGINX and backend logs after change; run load tests to ensure connection utilization acceptable.

5

Diagnostic step 5

If upstream keepalive must remain for performance, consider deploying a separate lightweight TCP/stream proxy for websocket paths.