TidyURLs
Go to Tools
BLOG
The TidyURLsJournal

Practical guides, tutorials, and insights about URLs, SEO, web development, and online marketing. Learn, troubleshoot, and get the most of the web.

Back to the Journal
TidyURLs Journal

The Mysterious 502 Error: How I’d Debug a Failing Web App

Practical insights, clear explanations, and useful ideas for understanding the web.

October 25, 20269 min read6 topics
The Mysterious 502 Error: How I’d Debug a Failing Web App
Explore the details
#HTTP#502 Bad Gateway#Reverse Proxy#Troubleshooting#Backend Development#Web Operations
October 25, 20269 min read

A 502 Bad Gateway error can look like a problem with your application, your proxy, your hosting provider—or all three. The key is to trace the request across the boundary between the gateway and the application server instead of guessing from the browser error page. This guide walks through how I would investigate a 502, what evidence to collect, and how to distinguish it from related HTTP errors.

Key takeaways

  • A 502 means a gateway or proxy received an invalid response from an upstream server while handling a request.
  • Start by identifying which component returned the 502, then correlate its logs with application and network evidence.
  • Check upstream availability, connection behavior, response validity, recent changes, and health-check results.
  • A 502 is different from a 500, 503, or 504, although infrastructure and applications can sometimes transform errors.
  • A public status check can confirm what a client sees, but it cannot reveal the full state of the upstream service.

First, understand the request path

In a typical web deployment, a browser does not connect directly to the application process. A load balancer, reverse proxy, CDN, or ingress controller may accept the client connection and forward the request to an upstream service. The upstream is the server or application that the gateway contacts to fulfill the request.

For example:

Browser → reverse proxy → application server → database

The gateway may handle TLS, route requests, balance traffic, or cache responses. If it cannot obtain a usable response from the upstream, it may return an error to the client. That is why a 502 page does not, by itself, identify which component failed.

HTTP defines 502 Bad Gateway for a server acting as a gateway or proxy that receives an invalid response from an inbound server while attempting to fulfill a request. The standard describes the status meaning; the exact diagnostic page and the level of detail in logs depend on the software and hosting setup.

Start debugging at the edge

Before changing application code, establish what is failing and where.

  1. Reproduce the issue. Record the full URL, approximate time, request method, and whether the problem affects every request or only a particular route. Avoid including credentials or private query-string values in shared notes.
  2. Compare paths. Check whether the error occurs for one hostname, one region, one endpoint, or all traffic. Try a known lightweight endpoint if your application has one.
  3. Identify the responder. Inspect response headers and the error page for clues about a CDN, load balancer, web server, or application. Headers can be modified or removed, so treat them as clues rather than proof.
  4. Check for a recent change. Review deployments, configuration updates, certificate changes, scaling events, DNS changes, and infrastructure maintenance around the time the error began.
  5. Confirm what clients receive. A HTTP status checker can help inspect the public response. It shows the result visible from its request path; it cannot establish whether an internal upstream is healthy or explain why a proxy returned a status.

Trace the gateway-to-upstream connection

Once you know which proxy or load balancer is involved, inspect its logs for the affected request and time window. Useful fields often include the requested path, selected upstream address, upstream status, connection time, response time, and an error message. Field names vary by product and configuration.

Then compare those records with application logs. Use a request ID or trace ID if your system propagates one. If it does not, correlate carefully by timestamp, route, and other non-sensitive request metadata. Make sure clocks are synchronized well enough for cross-service comparisons.

Check these failure modes

  • No healthy upstream targets: The application may be stopped, restarting, out of capacity, or failing its health check. A gateway with no eligible target may be unable to serve the request.
  • Connection refused or reset: The proxy may be reaching the wrong port, an application may not be listening on the expected interface, or a process may be terminating connections.
  • Invalid or incomplete response: The upstream might close the connection early, send malformed protocol data, or fail while constructing a response.
  • Network or name-resolution problems: The proxy may be unable to resolve or reach the configured upstream. Check the actual destination and routing from the proxy's network context.
  • Resource pressure: Exhausted worker processes, file descriptors, memory, or connection pools can prevent reliable responses. Look for correlated saturation and restarts rather than assuming a single metric explains the incident.
  • Configuration mismatch: Incorrect upstream protocol, port, TLS settings, or routing rules can break communication even while both services appear to be running.

A proxy's error log can make these cases easier to separate. For example, a connection failure is different evidence from a connection that succeeds but yields a response the gateway cannot use. Read the message in context and consult the documentation for the specific proxy or hosting platform; similar wording can have product-specific details.

Distinguish 502 from 500, 503, and 504

StatusGeneral meaningTypical debugging focus
500 Internal Server ErrorThe server encountered an unexpected condition that prevented it from fulfilling the request.Application exceptions, dependencies, and server-side error logs.
502 Bad GatewayA gateway or proxy received an invalid response from an upstream server.The gateway-to-upstream connection and the response received.
503 Service UnavailableThe server is currently unable to handle the request, often due to temporary overload or maintenance.Capacity, maintenance state, readiness, and service availability.
504 Gateway TimeoutA gateway or proxy did not receive a timely response from an upstream server.Slow or stalled upstream work, network delay, and timeout configuration.

These definitions are not a complete diagnosis. A proxy may generate a status on behalf of an upstream, and systems can be configured to map or replace errors. A slow upstream may eventually produce a 504, while a connection or protocol failure may produce a 502. Inspect the responding component's logs to understand what happened rather than inferring the cause from the status alone.

A practical investigation workflow

Work from evidence to the narrowest failing boundary:

  1. Record the symptom. Capture the time, route, client region if relevant, and whether the failure is intermittent or consistent. Keep a known-good request for comparison.
  2. Check the public response. Confirm the status and response behavior from outside the service. If only some users are affected, compare their route through the CDN or load balancer where possible.
  3. Inspect gateway logs. Find the matching request and note the selected upstream, connection result, upstream status, and timing fields.
  4. Inspect target health. Check whether the target was registered and considered healthy at that moment. Review health-check results, not only the current state: a target can recover before you investigate.
  5. Check application evidence. Look for matching request logs, process restarts, deployment events, exceptions, and resource saturation. If the request never appears in application logs, investigate the path before the application handler.
  6. Test from the correct network boundary. If authorized, verify the configured upstream from the proxy's environment using approved operational tooling. A test from a developer laptop may follow different DNS, routing, firewall, or TLS paths and can give a misleading result.
  7. Make one controlled change at a time. Restore a known-good configuration or roll back a recent deployment when evidence supports it. Preserve logs and timestamps so the effect can be evaluated.
  8. Verify recovery. Confirm that the gateway receives valid responses, health checks pass, and the affected routes work from the client side. Continue monitoring for recurrence.

Health checks and timeouts: useful, but easy to misread

Health checks help a load balancer decide whether a target should receive traffic. A useful check should reflect whether the service can safely handle requests, but it should not accidentally depend on an unrelated component unless that dependency is intentionally part of readiness. Check the configured path, expected response, interval, timeout, and failure threshold in the hosting platform's documentation.

A passing health check is not proof that every route works. It may exercise only one endpoint, run from a different network location, or miss intermittent failures. Conversely, an overly strict check can remove a functional target from rotation during brief slowdowns.

Timeouts require similar care. Increasing a proxy timeout may help when legitimate requests take longer than the current limit, but it can also keep connections open longer without fixing a stalled service or saturated dependency. Compare the gateway's timeout behavior with application processing time and downstream limits before changing values. If a request is timing out, determine which layer stopped waiting first.

Common mistakes

  • Treating every 502 as an application exception. The request may fail before it reaches application code, or the application may return a response the proxy cannot use.
  • Restarting everything immediately. A restart can erase useful process state and make intermittent evidence harder to collect. Capture relevant logs and metrics first when it is safe to do so.
  • Changing several timeouts at once. This makes it difficult to determine which change mattered and can shift the failure to another layer.
  • Assuming a successful health check proves full service health. Checks cover only the conditions they test.
  • Trusting one status page or response header as the root cause. The status identifies an outcome, not necessarily the component responsible.
  • Testing only from a workstation. The workstation may not share the proxy's DNS, network policies, or trust configuration.

Defensive recommendations

  • Keep gateway, application, and deployment logs with enough request context to correlate failures, while redacting secrets and sensitive data.
  • Monitor upstream health, error rates, latency, restarts, and resource saturation. Alert on sustained symptoms rather than a single transient failure.
  • Make readiness checks meaningful and document what they do—and do not—prove.
  • Validate proxy and upstream configuration during deployment, and make changes reversible.
  • Use request IDs or distributed tracing where appropriate, and propagate them consistently across services.
  • Document the expected request path, ownership of each layer, and the operational steps for checking upstream availability.

Conclusion

Debugging a 502 is a process of locating the failed boundary. Confirm what clients see, identify the gateway that returned the error, then correlate its upstream connection evidence with application logs and health-check history. Distinguishing a 502 from a 500, 503, or 504 helps focus the investigation, but the logs and configuration of the actual components provide the explanation. Make evidence-based changes, verify recovery across the full request path, and keep enough observability to make the next incident easier to diagnose.

References