Skip to main content
Legia

Apps & Software

Internal Application Keeps Throwing 500 or 502 Errors: How IT Teams Trace the Cause

Errors 500 and 502 look alike on the user's screen, but they come from different layers. This guide traces the cause through proxy logs, application capacity, and the release flow, then covers how to stop them from coming back.

SEO and Content Specialist

9 min read

A hand sketching an app screen flow on paper

Short answer: the causes of application 500 and 502 errors sit in different layers. 500 means the application itself failed to process the request, for example because of a code error or a database refusing connections. 502 and 504 come from a proxy such as nginx: 502 when the proxy receives an invalid response or cannot select an application server, 504 when the application does not answer in time. Trace in order: which layer answered, when it started compared with the last release, and whether worker capacity ran out.

The complaint “the application is erroring again” often arrives with nothing more than a screenshot showing 500 or 502. The IT team then guesses: restart the server, raise the timeout, or blame the network. Guesses like these sometimes work, but the error returns the following week. This guide sets out how to trace the cause of 500 and 502 errors in a company’s internal application step by step, from the logs to the release flow, using nginx and PHP-FPM as a common setup. The principles apply to other setups as well.

What 500, 502, 503, and 504 mean

RFC 9110, the current HTTP standard, defines these four codes. What matters for tracing is who sends them.

CodeRFC 9110 definition (summarized)Sent byFirst place to check
500 Internal Server ErrorThe server encountered an unexpected condition that prevented it from fulfilling the requestThe application or server processing the requestApplication error log
502 Bad GatewayThe server, acting as a gateway or proxy, received an invalid response from the server behind itProxy or gatewayProxy error log, application process status
503 Service UnavailableThe server is temporarily unable to handle the request due to overload or scheduled maintenanceApplication, proxy, or load balancerCapacity and maintenance schedule
504 Gateway TimeoutThe gateway or proxy did not receive a timely response from the server behind itProxy or gatewayProcessing time in the application and database

One thing is clear from this table: 502 and 504 can almost never be solved from the proxy side alone. The proxy only reports that the application behind it has a problem.

Illustration: web application

Step 1: find out which layer answered

In a common setup, a user’s request enters nginx, is forwarded to the application server (PHP-FPM, Node.js, or another), which accesses the database. Tracing starts by confirming in which layer the error was born.

The nginx access log can record the response from the application server separately through upstream module variables:

  • $upstream_status keeps the status code received from the application server. According to the nginx documentation, if no server can be selected, this variable holds 502.
  • $upstream_connect_time records the time spent opening a connection to the application server.
  • $upstream_response_time records the time spent receiving the response from the application server.
  • $request_time from the log module records the time of the whole request, from the first bytes read until the log is written.

An example log format that includes all four:

log_format telusur '$remote_addr [$time_local] "$request" $status '
                   'up=$upstream_status uct=$upstream_connect_time '
                   'urt=$upstream_response_time rt=$request_time';

How to read it:

  1. Status 500 and up=500: the application itself failed. Open the application error log at the same second.
  2. Status 502 and up empty or 502: nginx did not get a valid response from the application. Check whether the application process is running, listening on the right address and port, and not in the middle of a restart.
  3. Status 504 with urt close to the proxy timeout: the application was still working when nginx stopped waiting. The cause lies in a slow process, not in nginx.

Google’s Site Reliability Engineering book gives a frequent example: the symptom “serving HTTP 500s” with the cause “database servers are refusing connections”. The same book notes that a 500 caused by a lost database connection can be served very quickly. In other words, a short response time does not prove the application is healthy.

Step 2: match the timing with the last release

Once the layer is known, ask when the error started. An error that appears right after a release is almost always traced faster from that change than from the server.

  1. Draw a timeline: when the first error was logged, and when the last release or configuration change was run.
  2. Compare the changes: code, configuration files, environment variables, database migrations, and library versions.
  3. Roll back if the impact is wide, then trace in the test environment. Fixing in production while users wait is rarely faster.
  4. Record the failed release. The DORA change fail rate metric counts the percentage of releases that need immediate remediation, and a 500 error after a release is its data. How to calculate it is in Four DORA Metrics.

A special note for applications that use long-lived processes, such as queue workers. The Laravel documentation, for example, states that queue workers do not notice code changes until they are restarted, so a release that forgets to restart the workers leaves old code running next to the new code. The symptom can be an error that only appears in the features handled by those workers.

Step 3: check worker capacity and timeouts

If the error is not tied to a release and appears at peak hours, suspect capacity. An application server can only serve a certain number of requests at the same time.

In PHP-FPM, for example, the PHP documentation states that pm.max_children sets the limit on the number of simultaneous requests served. Connections not yet served wait in the listen.backlog queue, which defaults to 511 on Linux. When all workers are busy with slow requests, the next requests slow down too, and on the nginx side the result can be a 504. The request_terminate_timeout option kills a worker serving a single request past a set time, so that request is never fully answered.

On the nginx side, three proxy timeouts default to 60 seconds:

DirectiveWhat it measuresNote from the nginx documentation
proxy_connect_timeoutOpening a connection to the application serverUsually cannot exceed 75 seconds
proxy_send_timeoutSending the request to the application serverCounted between two write operations, not the whole request
proxy_read_timeoutReading the response from the application serverCounted between two read operations, not the whole response

Raising proxy_read_timeout often makes the 504 disappear, but it only moves the problem: users wait longer, and workers are held longer, so capacity runs out sooner. It is better to find out why the request is slow, for example a database query without an index or a large report that should run in the background. The CPU, memory, and disk usage to watch alongside it is covered in Server Monitoring: Metrics and Alert Thresholds.

Step 4: understand proxy behavior with more than one server

When the application runs on several servers behind nginx, the default behavior also shapes what users see:

  • proxy_next_upstream defaults to error timeout: the request is passed to the next server if an error or timeout occurs while connecting, sending the request, or reading the response header.
  • Requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server once sent to one server, unless enabled with non_idempotent. So a form that fails still shows up as an error to the user.
  • max_fails defaults to 1 and fail_timeout to 10 seconds: one failure makes the server considered unavailable for 10 seconds. If there is only one server in the group, these parameters are ignored.

As a result, one broken server among several can produce errors that appear now and then and are hard to reproduce. The $upstream_addr field in the log helps show which server answered.

Common causes of 500, 502, and 504 errors

SymptomLikely causeWhat to check
500 appears since a particular releaseCode, configuration, or migration errorRelease differences, application error log
500 fast and simultaneous on all pagesDatabase or another service unreachableDatabase status, connection limits
502 after a server restartApplication process not yet running or failed to startService status, application start log
502 now and then on several serversOne application server has a problem$upstream_addr in the access log
504 only on report or export featuresA slow process exceeds the proxy timeoutSlow queries, response time per URL
504 and 502 at peak hoursWorkers run outNumber of workers, queue, memory usage

This table is a starting point, not a diagnosis. Certainty still comes from the logs at the second it happened.

Stopping it from happening again

Good tracing ends with a change so the same error is caught earlier:

  1. Monitor the error rate, not only server status. Google’s SRE book includes errors, HTTP 500s among them, in the four golden signals to monitor, alongside latency, traffic, and saturation.
  2. Bring logs together from the proxy, application, and database in one place on the same clock, so one incident can be read across layers.
  3. Test releases in an environment equivalent to production, including database migrations.
  4. Prepare a rollback that anyone on the team can run, not only the person who wrote the code.
  5. Move heavy work to the background, such as reports and data imports, so it does not hold the workers serving users.

How Legia handles it

In the DevOps & CI/CD service, Legia sets up centralized logging, performance monitoring, and early alerts before users are the ones reporting, as well as staged deployment with a rollback mechanism tested through failure simulation. Four numbers are measured before and after the work, including the release failure rate and the recovery time after a problematic release. The whole process from mapping the flow to handover takes about 9-15 weeks, and the release flow is handed over to your team complete with training. Other services in this pillar are in Applications & Software.

Frequently asked questions

Does a 502 error mean the server is down?

Not always. According to RFC 9110, 502 means the proxy received an invalid response from the server behind it. The server may be running, but its application process is down, restarting, or listening on the wrong address.

Is raising the nginx timeout enough to get rid of 504?

Usually not. The error goes away, but users wait longer and workers are held longer, so capacity runs out faster at peak hours. Find the slow requests from the response time log, then fix the process.

Why does a 500 error only appear occasionally and cannot be reproduced?

The common cause lies outside the code being tested: one of several servers has a problem, database connections run out at peak hours, or an old worker is still running the previous code version. Record $upstream_addr and the time of the incident to narrow it down.

Who should handle it: the network team or the application team?

The status code already gives a hint. A 500 is almost always the application team’s job. 502 and 504 are reported by the proxy, but the cause usually lies in the application or database behind it, so both teams need to read the same logs.

Sources

Category Apps & Software

Keep reading

Related articles

All Articles