Environment
NGINX (1.22) reverse proxy in front of Node.js GraphQL server (express + websockets for subscriptions). upstream configured with keepalive 16 and proxy_http_version 1.1. Subscriptions use HTTP upgrade to websocket.
Symptoms
Subscription requests succeed briefly then NGINX returns 502 Bad Gateway during the handshake or shortly after; short HTTP queries and mutations are unaffected. Logs show occasional "upstream prematurely closed connection" entries when keepalive is set.
Observations
Node.js logs show the websocket upgrade reaches the app in successful cases. When NGINX keepalive enabled, upstream connections are reused and some connections close unexpectedly; disabling keepalive removes 502s but increases CPU and connection churn. proxy_read_timeout currently low (60s).
Already attempted
Tried disabling proxy buffering and increasing proxy_read_timeout to 300s; toggling proxy_http_version between 1.0/1.1; disabling keepalive removed the error but had performance cost. No TCP-level resets visible in kernel logs.
Question
Why do long-lived websocket/GraphQL subscriptions fail only when using NGINX upstream keepalive, and what NGINX config changes can support persistent subscriptions without 502s or excessive backend connections?
Verified community troubleshooting
Start by treating subscriptions as a different traffic class: put websocket/GraphQL subscription endpoints in their own location and use an upstream without keepalive for that path. In the subscription location add: 'proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade;' (use a small map to set Connection to 'upgrade' when $http_upgrade present), turn off buffering and raise proxy_read_timeout. Restart nginx and exercise a subscription — it should stay open. This preserves keepalive benefits for normal HTTP API routes while avoiding connection reuse issues that cause 502s. Rollback is simple: restore the previous location block.
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags
- Web Development41% match
NGINX returns 502 on WebSocket upgrade when TLS session resumption and upstream keepalive enabled
Open1 answer - Web Development36% match
Nginx returns 504 Gateway Timeout only for backend requests over ~45s to my Node API
Open1 answer - Servers34% match
Nginx returns 502 Bad Gateway when proxying to local Node.js upstream intermittently
Open0 answers - Web Development33% match
NGINX returns 502 only for long-running Node.js API endpoints while short requests succeed
Open0 answers - Web Development33% match
NGINX returns 413 for Transfer-Encoding: chunked uploads only when proxying to Node.js over HTTP/2 TLS offload
Solved1 answer