Nginx 504 Gateway Timeout — Slow Upstream Response and Timeout Configuration
Errorweb server
Overview
Fix Nginx 504 Gateway Timeout errors when upstream applications take too long to respond, requiring timeout adjustments and performance optimization.
Key Details
- 504 Gateway Timeout occurs when the upstream server does not respond within Nginx's configured timeout
- Default proxy_read_timeout is 60 seconds — long-running requests will fail with 504
- The issue is often the upstream application being slow, not an Nginx configuration problem
- Database queries, external API calls, and heavy processing commonly cause slow upstream responses
- Keep-alive connections between Nginx and upstream can reduce connection overhead
Common Causes
- Upstream application taking longer than proxy_read_timeout (default 60s) to respond
- Slow database queries blocking the application's request processing
- External API calls from the upstream application timing out or being slow
- Application resource exhaustion (all workers busy, memory full, CPU maxed)
Steps
- 1Increase timeout: 'proxy_read_timeout 300s;' in the location block for slow endpoints
- 2Identify slow requests: check upstream application logs for long-running requests
- 3Optimize the upstream: add database indexes, implement caching, optimize queries
- 4Set up keep-alive to upstream: 'upstream backend { server 127.0.0.1:3000; keepalive 32; }' with 'proxy_http_version 1.1; proxy_set_header Connection "";'
- 5For long-running operations: implement async processing — return 202 Accepted and process in background
Tags
nginx504gateway-timeoutupstreamperformance
Related Items
More in Web Server
linux-nginx-error-codesLinux Nginx Error Codes — 502, 504, 413 & Upstream Failures
Errorlinux-apache-error-codesLinux Apache Error Codes — AH01630, AH00558 & Module Errors
Warninglinux-nginx-common-errorsNginx Common Errors — Configuration Test Failed and Upstream Timeout
Errorlinux-nginx-502-bad-gatewayNginx 502 Bad Gateway — Upstream Server Connection and Proxy Errors
Errorlinux-apache-mod-rewrite-errorsApache mod_rewrite Errors — URL Rewriting, .htaccess, and Redirect Loop Issues
Warninglinux-reverse-proxy-errorsReverse Proxy Errors — SSL Termination, Header Forwarding, and Backend Connection Issues
WarningFrequently Asked Questions
Increasing timeout is a quick fix but not a solution. The root cause is a slow upstream. Optimize database queries, add caching, or implement async processing. Only increase timeout for genuinely long-running operations.