Understanding the 502 Bad Gateway Architecture
In high-throughput web applications, a 502 Bad Gateway error indicates that your edge reverse proxy (such as Nginx, Cloudflare, or Traefik) received an invalid response or no response from the upstream application server (such as PHP-FPM, Gunicorn, or Node.js runtime).
Primary Culprits in Production
- PHP-FPM Worker Starvation: The
pm.max_childrenthreshold was exceeded due to slow queries or synchronous external HTTP calls. - Upstream Socket Timeout: The
fastcgi_read_timeoutin Nginx terminated the connection before the worker completed execution. - Memory Exhaustion (OOM Killer): The Linux kernel terminated PHP-FPM master or child processes because the machine ran out of physical memory.
Step 1: Inspect Upstream Error Logs
tail -n 100 /var/log/nginx/error.log
# Look for: "connect() to unix:/var/run/php/php8.1-fpm.sock failed (111: Connection refused)"
Step 2: Tune PHP-FPM Process Pool
Review your pool configuration at /etc/php/8.1/fpm/pool.d/www.conf:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500
Step 3: Enable KeepAlive and Buffer Sizing
Prevent packet fragmentation and buffer overflow by tuning your FastCGI buffers in Nginx configuration:
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
fastcgi_read_timeout 120s;
Conclusion
By implementing proactive telemetry, configuring PM pool ceilings relative to real RAM limits, and catching runaway database locks, you eliminate unannounced 502 outages permanently.