HTTP Error Codes
504 Gateway Timeout
HTTP 504
The gateway or proxy server didn't receive a response from the upstream server within the timeout period.
What It Means
A 504 error means your request made it to a proxy (like Nginx or a CDN), but the proxy gave up waiting for your application server to respond. The request took too long.
What happens:
User → Proxy → App Server (still processing...) → Proxy times out → 504
Common Causes
- Slow database queries — Query takes longer than the proxy timeout
- External API calls — Waiting on a third-party API that's slow or down
- CPU-intensive operations — Heavy computation blocking the response
- Network issues — Latency between proxy and app server
- Insufficient resources — Server struggling under load
- Proxy timeout too low — Timeout configured lower than typical request time
How to Debug
- Reproduce the slow request — Which endpoints are timing out?
- Profile the endpoint — What's taking so long?
- Check database queries — Are there slow queries? Missing indexes?
- Check external calls — Are third-party APIs responding slowly?
- Check server resources — CPU, memory, I/O
Nginx Timeout Configuration
# Increase timeouts in nginx.conf or site config
location / {
proxy_pass http://app;
# Time to establish connection
proxy_connect_timeout 60s;
# Time to send request
proxy_send_timeout 60s;
# Time to receive response (most relevant for 504)
proxy_read_timeout 60s;
}
Finding Slow Queries
# PostgreSQL - find slow queries
SELECT query, calls, mean_time, total_time
FROM pg_stat_statements
ORDER BY mean_time DESC
LIMIT 10;
# MySQL - enable slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
504 vs 408
- 504 Gateway Timeout — Proxy gave up waiting for the app server
- 408 Request Timeout — Server gave up waiting for the client to finish sending the request
Solutions
- Optimize slow operations — Add indexes, cache results, optimize queries
- Add timeouts to external calls — Don't let slow APIs block indefinitely
- Move to background jobs — Long operations should be async
- Increase proxy timeout — If the operation genuinely needs more time
- Add caching — Reduce repeat expensive operations
- Scale up/out — More resources to handle load