504 Gateway Timeout: Causes & Fixes

504 Gateway Timeout: Causes & Fixes

A 504 Gateway Timeout error means a server acting as a gateway or proxy did not receive a timely response from an upstream server. The gateway was waiting for the upstream to respond, but it took too long and the connection timed out. Here is how to diagnose and fix 504 errors.

What Does 504 Mean?

A 504 is similar to a 502, but instead of receiving a bad response, the gateway received no response at all within its configured timeout period. The upstream server may still be processing the request — it just did not finish fast enough.

Common Causes

CauseDescription
Slow backend processingComplex queries or heavy computation
Database bottleneckSlow or locked database queries
Network latencyHigh latency between gateway and upstream
Low timeout settingsGateway timeout set too short
Upstream server overloadedServer too busy to respond in time
DNS issuesSlow DNS resolution for upstream
Large response payloadServer generating a massive response

How to Diagnose

# Check response time

curl -w "Total time: %{time_total}s\nConnect: %{time_connect}s\nTTFB: %{time_starttransfer}s\n" \

-o /dev/null -s https://example.com

Verbose output to see where it hangs

curl -v --max-time 30 https://example.com

Test with extended timeout

curl --max-time 120 https://example.com

import requests

try:

response = requests.get("https://example.com", timeout=60)

print(f"Status: {response.status_code}")

print(f"Time: {response.elapsed.total_seconds()}s")

except requests.exceptions.Timeout:

print("Request timed out")

Fixes for Users

  1. Refresh the page — The upstream may have recovered
  2. Wait a few minutes — Backend may be processing a heavy load
  3. Try a different network — The issue could be routing-related
  4. Use a proxy — Route traffic through a different path
curl -x http://user:pass@proxy.example.com:8080 --max-time 60 https://example.com

Fixes for Server Administrators

Increase Gateway Timeouts

Nginx:

location / {

proxy_pass http://backend;

proxy_connect_timeout 300s;

proxy_send_timeout 300s;

proxy_read_timeout 300s;

send_timeout 300s;

}

Apache:

ProxyTimeout 300

ProxyPass / http://localhost:8080/ timeout=300

Optimize Backend Performance

# Identify slow queries (MySQL)

mysql -e "SHOW FULL PROCESSLIST;"

Check for long-running processes

ps aux --sort=-pcpu | head -10

Monitor real-time server performance

vmstat 1 10

iostat -x 1 10

Add Caching

# Nginx proxy cache to reduce backend load

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;

location / {

proxy_cache my_cache;

proxy_cache_valid 200 10m;

proxy_cache_use_stale error timeout http_502 http_503 http_504;

proxy_pass http://backend;

}

Implement Health Checks

upstream backend {

server 127.0.0.1:8080 max_fails=2 fail_timeout=10s;

server 127.0.0.1:8081 max_fails=2 fail_timeout=10s backup;

}

Handling 504 in Code

import requests

import time

def request_with_timeout_retry(url, max_retries=3, timeout=30):

for attempt in range(max_retries):

try:

response = requests.get(url, timeout=timeout)

if response.status_code == 504:

wait = 5 * (attempt + 1)

print(f"504 Gateway Timeout. Waiting {wait}s...")

time.sleep(wait)

continue

return response

except requests.exceptions.Timeout:

wait = 5 * (attempt + 1)

print(f"Client timeout. Waiting {wait}s...")

time.sleep(wait)

raise Exception("Max retries exceeded")

# cURL with retry on timeout

curl --retry 3 --retry-delay 10 --max-time 60 https://example.com

504 vs 408 vs 502

CodeWho Timed OutMeaning
408ClientServer waited too long for the client to send data
502N/AGateway got a bad response from upstream
504GatewayGateway waited too long for upstream response



FAQ

Is a 504 error the same as a timeout?

A 504 is a specific type of timeout — the gateway timed out waiting for the upstream server. A generic client-side timeout (like requests.exceptions.Timeout) is different; that is your own client giving up.

Can CDNs cause 504 errors?

Yes. CDNs like Cloudflare act as reverse proxies. If your origin server does not respond within Cloudflare’s timeout (100 seconds on the free plan), Cloudflare returns a 504.

How do I prevent 504 errors on my site?

Optimize slow database queries, add caching layers, increase server timeout settings, and use asynchronous processing for long-running tasks. Consider moving heavy operations to background workers.

Should I increase timeout to fix 504?

Increasing the timeout is a quick fix but not a long-term solution. It masks the underlying performance issue. Optimize the backend process that is taking too long.

Scroll to Top