504 Gateway Timeout
The server, while acting as a gateway or proxy, did not receive a timely response.
Usually happens because:
- ☑ Heavy database queries blocking backend
- ☑ Third-party API dependencies taking too
- ☑ Mismatched connection timeouts between load
🔍 Quick Checklist:
Meaning
The HTTP 504 Gateway Timeout server error status code indicates that the server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access.
Root Causes
- Heavy database queries blocking backend execution thread for longer than proxy gateway timeout limits.
- Third-party API dependencies taking too long to respond to server requests.
- Mismatched connection timeouts between load balancers and origin nodes.
| Cause | Frequency |
|---|---|
| Heavy database queries blocking backend | ⭐⭐⭐⭐⭐ |
| Third-party API dependencies taking too | ⭐⭐⭐⭐ |
| Mismatched connection timeouts between load | ⭐⭐⭐ |
Common Mistakes
- Using 408 Request Timeout instead of 504 (use 408 when the *client* is slow; use 504 when the *upstream backend database/service* is slow).
- Failing to implement request cancellation in client libraries during timeouts, wasting server resources.
How to Fix
Framework-Specific Examples
Simulating gateway timeout inside Express middleware.
app.get('/slow-api', (req, res) => {
// Let connection hang until gateway timeouts trigger
});Server Configuration Examples
Increasing upstream timeout parameters in Nginx.
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
send_timeout 300s;Prevention
- Implement aggressive query timeouts in your database configuration.
- Offload reports compilation or file packaging to asynchronous job queues.
Frequently Asked Questions (FAQ)
Q: What is the difference between 502 and 504?
502 Bad Gateway means the upstream server crashed or returned an invalid response immediately. 504 Gateway Timeout means the upstream server accepted the connection but took too long to complete the response, violating gateway time limits.
Q: How do I fix 504 Gateway Timeout in Nginx?
Increase the upstream timeout limits using `proxy_read_timeout 300s;` and `proxy_connect_timeout 300s;` inside your server or location blocks.
Q: Can slow database queries cause 504 errors?
Yes. If a database query blocks the application thread for longer than the Nginx or AWS load balancer timeout limits (typically 60 seconds), the proxy drops the connection and returns 504.
Q: Is 504 Gateway Timeout cacheable?
No. The 504 status code represents a temporary timeout and is never cached.