504 504 Gateway Timeout
The server acting as a gateway did not receive a timely response from an upstream server.
What Is This?
The HTTP 504 Gateway Timeout status code indicates that the server, while acting as a gateway or proxy, did not receive a timely response from the upstream server. Unlike 502 (bad response), 504 means the upstream server did not respond at all within the timeout period. This is common in microservices architectures and applications with slow database queries or third-party API calls.
Common Causes & Solutions
Common Cause
Upstream server processing takes longer than the proxy timeout allows
Common Cause
Slow database queries or external API calls
Common Cause
Upstream server overwhelmed and unable to respond in time
Common Cause
Network latency between proxy and upstream server
Optimize slow queries and operations
Identify and optimize slow database queries, external API calls, or compute-heavy operations that cause timeouts.
-- Identify slow queries in PostgreSQL SELECT query, calls, total_time / calls AS avg_time FROM pg_stat_statements ORDER BY avg_time DESC LIMIT 10 -- Add missing indexes CREATE INDEX idx_users_email ON users(email); -- Use query optimization techniques EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 123;
Configure timeouts for long-running operations
Use background jobs or async processing for operations that take longer than acceptable response times.
# Nginx — longer upstream timeout
location /api/ {
proxy_pass http://backend;
proxy_read_timeout 120s;
proxy_connect_timeout 30s;
}
# Or move long operations to background jobs
// Instead of processing inline:
const result = await processLargeFile(file)
res.json(result)
// Use a job queue:
const job = await queue.add('process-file', { fileId })
res.status(202).json({ jobId: job.id })Related Entries
More from this reference:
500 500 Internal Server Error
The server encountered an unexpected condition that prevented it from fulfilling the request.
502 502 Bad Gateway
The server acting as a gateway received an invalid response from an upstream server.
503 503 Service Unavailable
The server is temporarily unable to handle the request, typically due to maintenance or overload.
Frequently Asked Questions
What is the default proxy timeout in Nginx?
The default proxy_read_timeout in Nginx is 60 seconds. If your upstream server takes longer, you need to increase this value or optimize the upstream response time.
How do 502 and 504 differ?
502 means the upstream server responded with an invalid or empty response. 504 means the upstream server did not respond within the timeout period. Both indicate upstream server issues, but 504 specifically points to a timeout problem.