Intermittent Nginx HTTP 502 Bad Gateway from Upstream Keep-Alive Race
Eliminate sporadic Nginx 502 Bad Gateway errors caused by reusing a half-closed TCP keepalive socket that Uvicorn, Go, or Node.js just closed.
Under steady low-to-medium load, 0.3% of requests return HTTP 502 Bad Gateway within 1-2ms. Nginx error.log prints "upstream prematurely closed connection while reading response header from upstream" while upstream app logs show zero errors.
rate(nginx_http_requests_total{status="502"}[5m]) > 0.002 AND histogram_quantile(0.5, nginx_upstream_response_time_seconds) < 0.005When Nginx maintains an upstream keepalive pool with keepalive_timeout (default 60s or 75s) greater than or equal to the application server idle keepalive timeout (for example Node.js 5s, Uvicorn 5s, or Gunicorn 60s), both peers race at the timeout boundary.
The backend sends a TCP FIN to close an idle socket at the exact millisecond Nginx writes a new HTTP request into that socket. The kernel replies with TCP RST, Nginx never sees an HTTP response, and immediately emits HTTP 502.
If proxy_http_version 1.1 and proxy_set_header Connection "" are omitted, Nginx falls back to HTTP/1.0 close per request, trading 502 races for ephemeral port exhaustion (TIME_WAIT buildup).
Your FastAPI/Uvicorn cluster runs with --timeout-keep-alive 60. Nginx upstream keepalive_timeout is 60s. Sporadic 502s hit /v1/orders POST requests. Which change eliminates the race safely?
- Confirm backend server idle keepalive timeout is explicitly set >= 10s higher than Nginx upstream keepalive_timeout (e.g., Uvicorn --timeout-keep-alive 65 vs Nginx 50s).
- Reload Nginx with nginx -t && nginx -s reload and verify zero "prematurely closed connection" log lines over 15 minutes of load.
- Ensure proxy_next_upstream does NOT retry non-idempotent POST/PATCH mutations on http_502 unless idempotency keys are enforced.
Why must Nginx keepalive_timeout be shorter than the upstream timeout?
Because Nginx initiates requests. If Nginx retires an idle socket at 50s while the backend waits until 65s, Nginx will never attempt to write a new HTTP request onto a socket that the backend just closed.
Why did my upstream app logs show zero errors during the 502s?
Because the backend closed the idle socket cleanly before the request arrived; the OS kernel returned a TCP RST before the application worker ever accepted or parsed the HTTP request.
Does the same race happen between AWS ALB and Nginx?
Yes. Every hop in a reverse-proxy chain must follow monotonic idle timeouts: downstream proxy idle timeout < upstream server keepalive timeout (e.g., ALB 60s < Nginx 65s; Nginx upstream 50s < App 65s).