FULL AI ANALYSIS

NGINX returns 502 only for long-running Node.js API endpoints while short requests succeed

Generated Oct 20, 2026, 9:41:02 AM

Analysis summary

The 502 and 'upstream prematurely closed connection' message indicate the upstream process closed the TCP connection before Nginx received a valid response header; the Node worker crashing (EPIPE and restarts) during CPU-bound work suggests the event loop is blocked or the process is being terminated. Increasing timeouts only masks the symptom. Likely causes: synchronous CPU-bound work blocking event loop (most likely), hitting PM2 or Node process crash (e.g., unhandled exception or signal), or hitting per-process file/socket limits causing abort. Nginx buffer/timeout settings can aggravate but are not root.

Possible causes

Node.js worker blocks event loop with synchronous CPU-bound processing, causing upstream to close or crash under load

85%

Upstream process crashes (unhandled exception) during heavy processing and closes connection; Nginx sees abrupt EOF

60%

Nginx upstream timeouts or buffer exhaustion misconfigured for streaming large responses; proxy_read_timeout or proxy_buffering causing aborts under certain timing

40%

OS-level limits (ulimit, open files, ephemeral ports) exhausted under high concurrency causing socket failures

25%

Suggested fixes

1

Diagnostic step 1

Instrument the Node handler: replace synchronous processing with asynchronous or offload to worker pool (worker_threads or separate service). Add try/catch to log exceptions and ensure the worker does not crash silently.

2

Diagnostic step 2

Run a repro locally with the same payload and monitor process (strace, node --trace-uncaught) to catch crashes; check PM2 logs for reasons of restart.

3

Diagnostic step 3

Temporarily enable proxy_buffering off and raise proxy_read_timeout to confirm Nginx isn't dropping due to timeout; do not leave infinite timeouts in production.

4

Diagnostic step 4

Monitor ulimit -n, ephemeral ports (ss -s), and dmesg for OOM/killed-by-signal entries; scale workers or use a job queue for heavy processing.

5

Diagnostic step 5

If offload not possible, front the API with a request queue (Redis/sidecar) and return a 202 with progress endpoint to avoid long-lived HTTP connections.