Skip to main content
Interactive nginx-config Configurator →Open Architecture Blueprint ↗
P1 INCIDENTL6 BARM05 · 5 MIN READ

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.

PRODUCTION SYMPTOM & ALERT SIGNATURE

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.005
01 · ROOT-CAUSE MECHANICS (WHY IT HAPPENS)

When 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).

02 · LIVE TRIAGE COMMANDS (COPY & RUN)
Correlate Nginx premature close logs with millisecond upstream times
$ grep -i 'prematurely closed connection' /var/log/nginx/error.log | tail -n 15
Smoking gun: Spikes of "upstream prematurely closed connection" with upstream_response_time=0.000 or 0.001.
Inspect live TCP socket states and ephemeral port pressure
$ ss -tan state established state time-wait state close-wait | awk '{print $1}' | sort | uniq -c
Smoking gun: Elevated CLOSE-WAIT or TIME-WAIT count to upstream port (e.g., 8000/8080).
Verify effective keepalive_timeout on Nginx vs upstream server
$ nginx -T 2>/dev/null | grep -E "keepalive|proxy_http_version|Connection"
Smoking gun: Missing keepalive_timeout or value >= upstream server idle keepalive timeout.
03 · PRODUCTION DIFF (BROKEN VS HARDENED)
BROKEN · Broken Nginx Upstream (keepalive timeout longer than backend idle close)
upstream api_backend {
    server 10.0.2.15:8000;
    keepalive 64;
    keepalive_timeout 75s;   # DANGER: Uvicorn/Node closes idle sockets at 60s (or 5s)!
}

location /api/ {
    proxy_pass http://api_backend;
    # Missing HTTP/1.1 + Connection "" breaks keepalive reuse
}
HARDENED · Production Nginx Upstream (strictly shorter edge timeout + HTTP/1.1)
upstream api_backend {
    server 10.0.2.15:8000;
    keepalive 64;
    keepalive_requests 10000;
    keepalive_timeout 50s;   # Strictly 10-15s BELOW backend --timeout-keep-alive 65s
}

location /api/ {
    proxy_pass http://api_backend;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_connect_timeout 2s;
    proxy_read_timeout 15s;
    proxy_next_upstream error timeout http_502 non_idempotent; # Remove non_idempotent for POST!
}
04 · MINUTE-24 BAR-RAISER CHECKPOINT (L6 · M05)TEST YOUR INSTINCT · ZERO SIGNUP

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?

05 · POST-FIX VERIFICATION CHECKLIST
  • 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.
06 · FREQUENTLY ASKED ENGINEERING QUESTIONS

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).