NGINX returns 502 only for long-running Node.js API endpoints while short requests succeed
Environment
Nginx 1.18 reverse-proxy on Ubuntu 20.04 in front of a Node.js 16 Express app (PM2 cluster with 4 workers). Problem observed on endpoints that perform CPU-bound image processing and stream large responses (~10–100s response time).
Symptoms
Clients see HTTP 502 Bad Gateway after a gap of 30–90s on long requests; Nginx access log shows 502 for those URIs while short endpoints return 200. The Node.js process handling the request does not log a proper error; sometimes it logs 'write EPIPE' or the worker exits.
Observations
Nginx error.log shows 'upstream prematurely closed connection while reading response header from upstream'. PM2 reports worker restarts around the same time for high CPU tasks. Increasing proxy_read_timeout temporarily delays the 502 but it still appears for heavier tasks. No OOMKilled on host; CPU is saturated on a single core when processing images.
Already attempted
Increased proxy_read_timeout to 300s, enabled proxy_buffering off for the endpoint, and set keepalive to upstream with higher timeout. Reworked Node handler to stream in smaller chunks; still observed intermittent 502s. PM2 max memory and cluster settings reviewed.
Question
Is this Nginx timing/buffering config, Node event-loop blocking causing upstream close, or OS-level resource limit? How to reliably prevent 502 on long-running processing endpoints without exposing DoS risk?
Verified community troubleshooting
No answers yet..
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags
- Web Development35% match
Nginx returns 504 Gateway Timeout only for backend requests over ~45s to my Node API
Open1 answer - Web Development31% match
NGINX returns 504 Gateway Timeout for long-running uploads through a Node backend — how to diagnose?
Open1 answer - Web Development29% match
NGINX reverse proxy returns 413 for Transfer-Encoding: chunked uploads to Next.js API while direct Node accepts them
Open0 answers - Web Development28% match
NGINX returns 413 Request Entity Too Large for chunked uploads only when client uses Transfer-Encoding: chunked
Open1 answer - Web Development27% match
Nginx returns 502 for long-lived GraphQL subscription requests only when upstream keepalive is enabled
Solved1 answer