Bad Gateway Error 502: HTTP 502 vs 504 for Troubleshooting Server Gateway Errors

Treat a 502 as a bad upstream response and a 504 as an upstream response that never arrived in time. That single distinction saves the most time when troubleshooting gateway errors. Both codes come from a proxy, load balancer, CDN, API gateway, or web server acting as a middle layer, but they point to different failure patterns: HTTP 502 Bad Gateway means the gateway received an invalid response, while HTTP 504 Gateway Timeout means it waited too long for one [source: MDN].

TLDR: A 502 usually means something upstream answered with garbage, crashed mid response, closed the connection, or failed TLS. A 504 usually means the upstream server was too slow, overloaded, blocked on a database, or unreachable until the gateway timeout expired. For example, if an ecommerce checkout API normally responds in 240 ms but suddenly takes 31 seconds, an Nginx or CDN timeout can turn that delay into a 504 for users. In one realistic support case, a checkout error rate rising from 0.3% to 6.5% during a traffic spike points more toward timeout pressure than malformed responses.

What a 502 Bad Gateway really means

A 502 Bad Gateway is returned by an intermediary server. The user’s browser did not usually talk directly to the broken application. It talked to a gateway. That gateway tried to contact another server and received a response it could not use.

Common 502 causes include:

  • Application process crashed while the gateway was waiting.
  • Upstream returned malformed HTTP, such as broken headers or an invalid status line.
  • TLS handshake failed between the proxy and backend service.
  • Connection reset occurred before the response finished.
  • Wrong upstream port or protocol, such as sending HTTP traffic to an HTTPS-only service.
  • Bad deploy introduced a server exception that kills workers under load.

Honestly, it feels like 502 errors are built to waste your first 15 minutes. The browser shows one blunt message, while the actual fault sits one layer deeper. The fix is to stop staring at the browser and check the gateway logs first.

Image not found in postmeta

What a 504 Gateway Timeout really means

A 504 Gateway Timeout means the gateway asked an upstream server for a response, then gave up. The upstream might still be working. It may even finish the request later. But the gateway’s patience ran out first.

Typical 504 causes include:

  • Slow database queries holding the request open.
  • Thread pool or worker exhaustion in the application server.
  • Network routing issues between gateway and backend.
  • External API calls blocking the request path.
  • High CPU or memory pressure causing long pauses.
  • Timeout settings that are too short for known long operations.

A 504 is often a speed and capacity problem. It can also be a dependency problem. If your app waits on a payment provider, search cluster, storage service, or internal API, that wait can surface as a gateway timeout.

HTTP 502 vs 504: the practical difference

The shortest version is this:

  • 502: the gateway received a bad, incomplete, or invalid response.
  • 504: the gateway did not receive a response soon enough.

That difference changes your first checks. With 502, inspect response validity, service crashes, TLS, protocol mismatch, and backend logs. With 504, inspect latency, resource saturation, slow dependencies, and timeout limits.

Error Main signal First place to check Likely fix
502 Invalid upstream response Gateway error log Fix backend crash, protocol, TLS, or bad headers
504 Upstream timeout Latency metrics Reduce response time, scale workers, fix slow dependency

Fast troubleshooting checklist for 502 errors

Start with the service path. Identify every layer between the user and the app. That may include browser, CDN, WAF, load balancer, reverse proxy, container ingress, service mesh, and backend service.

  1. Check the gateway log timestamp. Match it to the exact user request.
  2. Read the upstream error. Nginx may show messages such as upstream prematurely closed connection or bad gateway.
  3. Confirm the backend is alive. Check process status, container restarts, pod events, or service health.
  4. Test the upstream directly. Use curl from the gateway host, not your laptop.
  5. Verify port and protocol. HTTP to HTTPS mismatch is a classic cause.
  6. Review recent deployments. A 502 right after release is rarely a coincidence.
  7. Inspect response headers. Oversized or malformed headers can trigger gateway rejection.

The annoying part is that a backend can look “up” while still producing 502s. A health check may pass on /health, while real traffic crashes on /checkout. Make your health checks meaningful, or expect false comfort.

Fast troubleshooting checklist for 504 errors

For 504s, treat time as the main clue. Find where the seconds disappear.

  1. Check gateway timeout values. Look at proxy read timeout, connect timeout, idle timeout, and CDN limits.
  2. Compare normal and failed latency. If p95 jumps from 400 ms to 12 seconds, the gateway is not the root cause.
  3. Inspect database performance. Look for locks, missing indexes, slow queries, and connection pool exhaustion.
  4. Check application workers. Saturated PHP FPM, Node.js, Java, Python, or Ruby workers can stall all traffic.
  5. Review external calls. Payment, email, CRM, and analytics APIs often add hidden delay.
  6. Check network reachability. Test from gateway to backend with timing output.
  7. Use request IDs. Trace one failed request across all layers.

Why users often see the same message for different failures

Many platforms replace technical errors with a branded error page. A CDN may show “Bad Gateway” for several upstream problems. A hosting panel may hide whether the issue was a reset, refused connection, or timeout. That is bad for users and worse for engineers.

This is why server logs matter more than browser text. Browser messages are symptoms. Gateway logs are evidence. Application logs are motive.

Key log messages to search for

For 502, search for:

  • connection reset by peer
  • upstream prematurely closed connection
  • invalid header
  • SSL handshake failed
  • no live upstreams

For 504, search for:

  • upstream timed out
  • context deadline exceeded
  • request timeout
  • read timeout
  • gateway timeout

These phrases help split response quality problems from response delay problems. That split is the heart of 502 vs 504 troubleshooting.

Common fixes that actually work

For 502 Bad Gateway, fix the upstream response path. Restarting the app may restore service, but it is not a root cause fix. Check crash reports. Validate config. Confirm that the gateway talks to the correct host, port, and scheme. If oversized headers are involved, reduce cookie size or adjust proxy header limits with care.

For 504 Gateway Timeout, reduce waiting. Optimize slow queries. Add indexes. Move long jobs to a queue. Increase worker capacity. Cache expensive responses. Set sane timeouts for external APIs. If a request takes 45 seconds by design, it probably should not be a normal web request.

Prevention: catch gateway errors before customers do

Prevention starts with visibility. Track 5xx rate, upstream latency, gateway latency, connection errors, worker saturation, and dependency timing. Alert on ratios, not only raw counts. Ten errors during ten requests is an outage. Ten errors during one million requests may be noise.

Use synthetic checks from more than one region. Add request IDs to every response. Keep deploy markers in your monitoring charts. Test rollback steps before you need them. Set separate alerts for 502 and 504 if your platform allows it, because they usually require different responders.

One final rule for incident response

Do not troubleshoot 502 and 504 the same way. A 502 asks, “Why was the upstream response unusable?” A 504 asks, “Why did the upstream take too long?” Answer that first, and the rest of the incident becomes much less messy.