HTTP, TLS & Web Performance

502 and 504 Gateway Errors Explained

Learn what bad gateway and gateway timeout errors mean, tell them apart and trace the failing link between two servers.

Key takeaways

  • A 502 or 504 tells you the front server answered but its conversation with a server behind it failed.
  • 502 usually means refused, reset or garbled replies, while 504 means the wait ran out.
  • The proxy's error log names the upstream address and the reason, so read it first.
  • Raising timeouts hides slowness without curing it.
  • A request that timed out may still be running or may already have succeeded, so be careful about repeating it.

Both errors come from a server in the middle. A gateway or proxy received your request and tried to pass it to another server, usually called the upstream or origin. A 502 Bad Gateway means the answer it got back was unusable. A 504 Gateway Timeout means no answer arrived in the time the proxy was willing to wait.

Visitors can mostly wait and retry. Site owners need to look at the link between the proxy and the server behind it: is that server running, reachable, speaking the expected protocol and fast enough?

Where gateways sit

Most websites are a chain. A visitor connects to a content delivery network or load balancer, which forwards to a web server, which forwards to an application process, which talks to a database and other services.

Two ways the upstream conversation fails
Visitor Proxy Application GET /report 1 Forward the request 2 Connection reset or junk reply 3 502 Bad Gateway 4 Retry GET /report 5 Forward, then wait 6 504 Gateway Timeout 7 The application may still be working Visitor Proxy Application GET /report 1 Forward the request 2 Connection reset or junk reply 3 502 Bad Gateway 4 Retry GET /report 5 Forward, then wait 6 504 Gateway Timeout 7 The application may still be working

Each arrow can fail on its own. The error page you see is written by whichever proxy noticed. Reverse proxies and load balancers describe these middle layers.

502 and 504 side by side

502 Bad Gateway 504 Gateway Timeout
What happened Invalid or no usable reply No timely reply
Typical speed Often fails immediately Fails after a fixed delay
Usual suspects Crashed or stopped service, wrong port, protocol mismatch Slow queries, overload, blocked network path, stuck external call
First check Is the upstream process running and listening? What is the request waiting for?

The line is not perfectly sharp. Products differ in which code they use when, for example, a connection attempt gets no response. Trust the log message over the number.

A related code, 503 Service Unavailable, usually means a layer is declaring that it cannot take the request, for instance because no healthy server is available or the site is in maintenance. See 503 and maintenance.

If you are visiting the site

  1. Wait a moment and reload.
  2. Check whether other sites load. If they do, your connection is probably fine.
  3. Try the same page on another network or device to rule out a proxy or VPN of your own.
  4. Look for a status page. Many sites failing together can point to a shared provider; see why big outages happen.
  5. After a timed-out purchase or transfer, check your history before submitting again.

Clearing your DNS cache or restarting your computer rarely helps. The exception is a corporate or school network whose own proxy produces the error, in which case the page often carries that product's branding and your network team can help.

Finding the failing hop

Start with the error page and headers. A page styled by a content delivery network, or a request ID header from a vendor, shows which layer spoke. Many networks report trouble reaching your origin with their own codes in the 520s, documented by each vendor.

Then work inward:

Tracing a gateway error inward
1 Identify the layer Use the error page and headers to see which proxy answered. 2 Read its log Find the upstream address and stated reason. 3 Check the process Confirm the upstream is running and listening. 4 Call it directly Request the upstream from the proxy machine itself. 5 Inspect dependencies Look at databases, APIs and resource limits. Identify the layer Use the error page and headers to see which proxy answered. 1 Read its log Find the upstream address and stated reason. 2 Check the process Confirm the upstream is running and listening. 3 Call it directly Request the upstream from the proxy machine itself. 4 Inspect dependencies Look at databases, APIs and resource limits. 5

What nginx logs tell you

If nginx is your proxy, its error log is quite specific. Typical phrases and meanings:

Log phrase Meaning
connect() failed (111: Connection refused) Nothing is listening at that address and port
upstream prematurely closed connection The application crashed or ended before replying
upstream sent too big header Response headers exceed the proxy's buffer
upstream timed out (110: Connection timed out) The wait expired, giving a 504
no live upstreams Every configured backend is marked failed
(13: Permission denied) on a socket The web server user cannot use the Unix socket

Check from the proxy machine:

sudo ss -ltnp                      # what is listening
curl -i http://127.0.0.1:8080/     # call the upstream directly
sudo systemctl status myapp        # is the service up
sudo journalctl -u myapp -n 100    # its recent messages

Replace the port and service name with yours. If the direct call works but the proxied one fails, compare the address, port, socket path and protocol in the proxy configuration. Sending plain HTTP to a port expecting TLS, or using the HTTP directive for a FastCGI service, produces a 502.

Causes of 502

  • The application service stopped, crashed or is still restarting during a release.
  • The proxy points to the wrong host, port or socket.
  • A firewall or security group blocks or resets the connection.
  • The upstream closes connections early because a worker hit a memory or time limit.
  • TLS between proxy and origin fails because of an expired or mismatched certificate.
  • The proxy resolved a backend's name once and kept an old address.

Causes of 504

  • A slow database query or a lock holding requests in line.
  • All application workers busy, so new requests queue.
  • A call to an outside service with no sensible timeout of its own.
  • A long task, such as building a big export, done inside a web request.
  • Packets to the upstream being silently dropped by a network rule.

Worker exhaustion is easy to misread. The server's processor may look idle while every worker waits on something slow. Look at the number of busy workers and the queue, not only CPU use. Why websites load slowly covers server delays more broadly.

Timeouts: align them, do not just raise them

Every layer has its own limits. In nginx:

proxy_connect_timeout 5s;
proxy_read_timeout    60s;

proxy_read_timeout applies between successive reads from the upstream, not to the whole response. A content delivery network in front may have a shorter limit that you cannot change on your plan.

A sound arrangement gives inner calls shorter timeouts than outer ones: the application gives up on an external API before the proxy gives up on the application. That way the application can return a meaningful error or a cached fallback.

If work truly takes minutes, change the design. Accept the request, answer 202 Accepted, do the work in a background job and let the user check progress or receive a notice.

Intermittent errors

An occasional gateway error among thousands of good responses needs a different approach from a total outage.

Only during releases. The old process stopped before the new one was ready. Add a readiness check and let the old one drain.

After quiet periods. The proxy may reuse an idle connection to the upstream just as the upstream closes it. Set the upstream's keep-alive timeout longer than the proxy's idle timeout, so the proxy is the side that retires connections.

Only for some pages. A particular route is slow or crashes a worker. Compare upstream response times by path.

Only at busy hours. Workers, connection pools or file descriptors are running out. Graph them next to the error count.

Only through one server. One instance behind the balancer has a different version, a full disk or a broken network path.

It helps to log the upstream address, upstream status and upstream response time in your proxy's access log. nginx provides variables for each, such as $upstream_addr and $upstream_response_time. With those recorded, each failure tells you which server was involved and how long it took.

A worked example

Say an online booking page returns 504 every weekday at about nine in the morning. The proxy log shows read timeouts to the application. The application log shows that the same requests eventually finish, after the visitor has gone.

The database log then shows a long report query starting at the same hour and holding up bookings. Raising the proxy timeout would only make people wait longer. Moving the report to a copy of the database, or scheduling it for a quiet hour and improving its indexes, removes the cause. A shorter database timeout on the booking query would also let the page fail quickly with a useful message.

Retries and duplicates

A 504 says the proxy stopped waiting. It does not say the upstream stopped working. A payment or import may complete after the visitor saw the error.

Protect such actions with idempotency keys or a check for existing results, and word your error pages accordingly. Proxies that retry automatically on another server should do so only for requests that are safe to repeat. HTTP methods explains which those are.

Reducing how often they happen

  • Run more than one application instance and use health checks so the proxy skips a failing one.
  • During releases, start new instances before stopping old ones, and let existing requests finish.
  • Restart crashed services automatically, and still investigate why they crashed.
  • Cache pages that can be cached, and consider serving a slightly stale copy when the upstream fails, which several proxies and networks support.
  • Set limits on queue length so overload fails quickly and recovers.
  • Monitor upstream response time, not only whether the home page answers.
  • Give visitors a plain custom error page, served by the proxy itself, that says the problem is on the site's side and when to try again.

When you report a gateway error to a host or network provider, include the time with time zone, the full address, the request ID from the error page and whether a direct request to your origin succeeded. Those four facts usually decide which side of the proxy needs attention.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic