Skip to content
Proxy fundamentals

502 vs 504: Bad Gateway vs Gateway Timeout

502 means the next server answered badly. 504 means it never answered in time. We tested which hop sends each through Squid 6.13 and Go 1.24.4.

On this page 8 sections
  1. 502 vs 504 at a glance
  2. What the standard actually says
  3. How we tested it
  4. Results: one failure, two answers
  5. The differences that bite in practice
  6. The code names the software as much as the failure
  7. Go answers every timeout with a 502
  8. In a chain, the shortest timeout decides the code
  9. Once headers are sent, a timeout cannot become a 504
  10. Through an HTTPS tunnel there is no error page at all
  11. Timeouts fire late, and not always by the same amount
  12. The 502 that only appears sometimes
  13. Telling which hop sent it
  14. When each code is the right one to send
  15. What to do when one comes back through your proxy

A 502 Bad Gateway means a proxy or gateway reached the next server and got back something it could not use: a refused connection, a reset, an empty reply, headers it could not parse. A 504 Gateway Timeout means the gateway waited and gave up before any answer arrived. Neither code is written by the server that failed. Both come from the hop in front of it, and that hop’s software decides which code a given failure gets.

That last point is the one most explanations skip. We pushed the same six failures through Squid 6.13 and through the reverse proxy in Go 1.24.4’s standard library. They returned the same status for two of the six. Go never sent a 504 at all until we wrote code to make it.

502 vs 504 at a glance

502 Bad Gateway 504 Gateway Timeout
Defined in RFC 9110 §15.6.3 RFC 9110 §15.6.5
Written by A proxy, load balancer or CDN, about the server behind it The same kind of hop
What that hop saw A bad answer: refused, reset, empty or unparseable No answer before its own deadline
How fast it arrives Usually at once. A median of about 1 ms in our lab After a fixed wait that matches some hop’s timeout
Usual causes Upstream process stopped or crashed, wrong port, connection reset, broken response headers, a keep-alive race Slow query or job, overloaded upstream, packets dropped by a firewall, a timeout shorter than the work
Did the request run? Not if it failed at connect. Possibly, if the reply broke Unknown. The upstream may still finish it
Retry? Once, quickly, for a GET. Repeated 502s mean it is down Back off first. Repeating a slow request adds load
First thing to check Is the upstream listening, and what does its error log say? Upstream latency against every timeout on the path

The cheapest clue is time. A 502 that comes back in milliseconds is a refusal or a crash. A 504 that arrives after a round number of seconds is a timer, and you can usually find that number in somebody’s configuration: 60 seconds is the default proxy_read_timeout in nginx and the default idle timeout on an AWS Application Load Balancer, and 125 seconds is Cloudflare’s proxy read timeout.

What the standard actually says

RFC 9110 assigns both codes to a server acting as a gateway or proxy, never to the server doing the work. A 502 says the gateway got an invalid response from the server behind it. A 504 says it did not get a timely one. That is the whole definition.

Everything else is implementation. The RFC does not say what a gateway should send when the TCP connection is refused outright, when DNS fails, or when the handshake itself hangs. Those are the most common failures in practice, and each piece of software fills the gap its own way. Neither code is on the RFC’s list of heuristically cacheable statuses, so a cache should not keep one without explicit instructions.

If you are new to the vocabulary, a forward proxy is the one you configure in your client, and a reverse proxy is the one a website puts in front of its own servers. Both can emit either code. Our proxy server explainer covers how the hops fit together.

How we tested it

On 21 October 2026 we built a lab on one Mac (Apple silicon, macOS with Darwin 25.6) and produced each failure on purpose. Every process listened on 127.0.0.1, so no network sat between the hops and the timings reflect the software alone.

  • Origin: a Python 3.15.0 http.server script with one path per failure. It can answer at once, sleep for N seconds, close the socket without replying, reply with an SSH banner instead of HTTP, or send headers and half the body and then stall.
  • Squid 6.13 as a forward proxy, the position a proxy provider’s gateway takes in front of a scraper. connect_timeout 3 seconds, read_timeout 5 seconds, caching off.
  • Go 1.24.4 net/http/httputil.ReverseProxy, the position a site’s load balancer takes in front of its application. Response-header timeout 3 s, dial timeout 3 s, error handling left at the default.
  • curl 8.7.1 as the client. Each scenario ran once with -v to capture headers and body, then five more times in sequence. Times are curl’s time_total.

For an unreachable host we used 192.0.2.1, a block reserved for documentation by RFC 5737; from our network a SYN to it is never answered. A refused connection used a local port with nothing listening.

# squid.conf for Squid 6.13, the lines that matter here
http_port 127.0.0.1:3138
acl lab src 127.0.0.1/32
http_access allow lab
http_access deny all
cache deny all
connect_timeout 3 seconds
read_timeout 5 seconds
// Go 1.24.4: a reverse proxy with the default error handler
rp := httputil.NewSingleHostReverseProxy(upstream)
rp.Transport = &http.Transport{
    DialContext:           (&net.Dialer{Timeout: 3 * time.Second}).DialContext,
    ResponseHeaderTimeout: 3 * time.Second,
}
log.Fatal(http.ListenAndServe("127.0.0.1:8080", rp))

Results: one failure, two answers

Medians of five runs. The detail column is what each proxy recorded about the failure: the X-Squid-Error response header for Squid, the error log line for Go.

Failure we caused Squid 6.13 sent Go 1.24.4 sent Squid detail Go detail Time to error (Squid / Go)
Port closed, connection refused 503 502 ERR_CONNECT_FAIL 61 connect: connection refused 0.6 ms / 0.7 ms
Host never answers the SYN 503 502 ERR_CONNECT_FAIL 60 dial tcp 192.0.2.1:80: i/o timeout 3.69 s / 3.00 s
Connected, no response headers 504 502 ERR_READ_TIMEOUT 0 net/http: timeout awaiting response headers 5.20 s / 3.00 s
Connection closed, no reply 502 502 ERR_ZERO_SIZE_OBJECT 0 EOF 1.2 ms / 0.9 ms
Reply is not HTTP at all 200 502 X-Transformed-From: HTTP/0.9 malformed HTTP response "SSH-2.0-OpenSSH_9.6" 1.1 ms / 0.9 ms
Headers sent, body stalls 8 s 200, body cut short 200, full body curl exit 18 no body timeout set 5.78 s / 8.01 s
Host name does not resolve 503 — ERR_DNS_FAIL 0 not tested 7.9 ms / —

The numbers 61 and 60 after ERR_CONNECT_FAIL are macOS errno values, ECONNREFUSED and ETIMEDOUT. On Linux the same two errors are numbered 111 and 110 in the kernel’s errno.h, so expect those on a Linux proxy. Squid’s error page spells them out as (61) Connection refused and (60) Operation timed out.

The two proxies agreed only on the closed connection and on the stalled body, and in the second case they still handed the client different bodies. Both connect failures got a 503 from Squid and a 502 from Go.

The differences that bite in practice

The code names the software as much as the failure

Squid answers a failed connection with 503. Go answers every transport error with 502. Other gateways split the same failures differently again. We did not run the three on the right below; their columns come from nginx’s source and from the vendors’ own documentation, linked in the sources.

Failure Squid 6.13 (ran) Go 1.24.4 (ran) nginx 1.31.8 (source) AWS ALB (docs) Cloudflare (docs)
Connection refused 503 502 502 502 521
TCP connect times out 503 502 504 504 522
Connected, no reply in time 504 502 504 504 524
Closed with no reply 502 502 502 502 520
Reply has no valid status line 200 502 200 502 520

In nginx the mapping sits in one switch inside ngx_http_upstream_next(): a timeout becomes 504, a few named upstream statuses map to themselves, and anything without its own case falls through to 502. The last row surprised us. Squid fell back to HTTP/0.9 when the reply had no valid status line and handed the client a 200 wrapped around whatever bytes arrived, and nginx’s proxy module has the same fallback in its source. Our client received SSH-2.0-OpenSSH_9.6 as a successful response body.

For the failures in this table Cloudflare uses its own 52x range rather than 502 or 504: 521 when the origin refuses the connection, 522 after 19 seconds without a completed TCP handshake, 524 after 125 seconds without a response. Its 502 and 504 pages mean something narrower. Per its documentation, a branded 502 or 504 page is the origin’s own error relayed, while a blank unbranded one is Cloudflare’s.

Go answers every timeout with a 502

The ErrorHandler field on httputil.ReverseProxy is documented as optional, and when it is nil the proxy logs the error and writes a 502. A timeout included. Our Go proxy logged http: proxy error: net/http: timeout awaiting response headers and answered 502 at 3.00 seconds, every run. Anyone reading that 502 would go looking for a crash that never happened.

The fix is a few lines. With this handler both the header timeout and the dial timeout returned 504 at 3.00 seconds, five runs each:

rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
    log.Printf("http: proxy error: %v", err)
    var ne net.Error
    if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &ne) && ne.Timeout()) {
        w.WriteHeader(http.StatusGatewayTimeout)
        return
    }
    w.WriteHeader(http.StatusBadGateway)
}

In a chain, the shortest timeout decides the code

Real requests cross several gateways. A scraper talks to its proxy provider, which talks to the site’s CDN or load balancer, which talks to the application. We rebuilt that with curl → Squid (5 s read timeout) → Go (3 s or 10 s header timeout) → an origin that takes 8 seconds.

With Go’s 3-second timeout firing first, the client got Go’s 502 at 3.00 seconds, relayed through Squid. With Go set to 10 seconds, Squid’s timer fired first and the client got Squid’s own 504, between 5.00 and 5.96 seconds. The second case is the one that misleads people, because each hop wrote a different status into its log for the same request:

Hop Status in its log Why
Client (curl) 504 Squid’s read timeout fired
Squid 6.13 TCP_MISS_TIMEDOUT/504 err=ERR_READ_TIMEOUT
Go reverse proxy 502 Squid hung up; Go logged http: proxy error: context canceled
Origin 200 It finished the work 8.0 s after the request started

The origin completed every one of those requests about two to three seconds after the client had been told it timed out. If the request had been a POST that charged a card or wrote a row, it would have happened anyway. nginx in the middle position would show yet another value: it logs 499, its own code for a client that closed the connection first.

Once headers are sent, a timeout cannot become a 504

A status line goes out before the body. If the upstream stalls after its headers, the gateway has already relayed a 200 and has no way to take it back. Through Squid, our stalled response arrived as a 200 with 1,000 of its 2,000 bytes, and curl exited with code 18: transfer closed with 1000 bytes remaining to read. Go has no body timeout unless you set one, so it waited the full 8 seconds and delivered everything.

nginx’s documentation makes the same point about proxy_next_upstream: once part of a response has gone to the client, there is no next server to try. A scraper that checks only the status code will record a truncated page as a success. Compare the bytes you received with Content-Length, or treat curl exit 18 as a gateway failure.

Through an HTTPS tunnel there is no error page at all

For an https:// URL your client asks the proxy to open a tunnel with HTTP CONNECT. When the proxy cannot reach the target, the error answers the CONNECT, and most clients never show you that response as a page. curl reports it like this, and %{http_code} prints 000:

$ curl -s -o /dev/null -x http://127.0.0.1:3138 -w 'http_code=%{http_code} http_connect=%{http_connect}\n' https://127.0.0.1:9099/
http_code=000 http_connect=503
$ echo $?
56
$ curl -sS -o /dev/null -x http://127.0.0.1:3138 https://127.0.0.1:9099/
curl: (56) CONNECT tunnel failed, response 503

Squid sent that 503 for the refused port and, after 3.13 to 3.97 seconds, for the silent host. Read %{http_connect} whenever you debug through a proxy; our curl proxy guide lists the other write-out variables worth printing.

Timeouts fire late, and not always by the same amount

Go’s timers were exact to within 5 ms. Squid’s were not. Set to 3 and 5 seconds, they fired anywhere in a window up to a second wide:

Configured timeout against the fastest and slowest of 5 observed errors, seconds Drawn from the table below.
Configured timeout against the fastest and slowest of 5 observed errors, seconds. Bar chart of Configured, Fastest of 5, Slowest of 5 by Timer.5 rows, drawn from the table that follows this chart.Go 1.24.4 header timeoutGo 1.24.4 header timeout · Configured: 3Go 1.24.4 header timeout · Fastest of 5: 3.001Go 1.24.4 header timeout · Slowest of 5: 3.005Go 1.24.4 dial timeoutGo 1.24.4 dial timeout · Configured: 3Go 1.24.4 dial timeout · Fastest of 5: 3.001Go 1.24.4 dial timeout · Slowest of 5: 3.002Squid 6.13 connect_timeoutSquid 6.13 connect_timeout · Configured: 3Squid 6.13 connect_timeout · Fastest of 5: 3.228Squid 6.13 connect_timeout · Slowest of 5: 3.971Squid 6.13 read_timeoutSquid 6.13 read_timeout · Configured: 5Squid 6.13 read_timeout · Fastest of 5: 4.950Squid 6.13 read_timeout · Slowest of 5: 5.499Squid read_timeout, in the chainSquid read_timeout, in the chain · Configured: 5Squid read_timeout, in the chain · Fastest of 5: 5.000Squid read_timeout, in the chain · Slowest of 5: 5.9610246 sConfigured timeout against the fastest and slowest of 5 observed errors, seconds. Bar chart of Configured, Fastest of 5, Slowest of 5 by Timer.5 rows, drawn from the table that follows this chart.Go 1.24.4 header timeoutGo 1.24.4 header timeout · Configured: 3Go 1.24.4 header timeout · Fastest of 5: 3.001Go 1.24.4 header timeout · Slowest of 5: 3.005Go 1.24.4 dial timeoutGo 1.24.4 dial timeout · Configured: 3Go 1.24.4 dial timeout · Fastest of 5: 3.001Go 1.24.4 dial timeout · Slowest of 5: 3.002Squid 6.13connect_timeoutSquid 6.13 connect_timeout · Configured: 3Squid 6.13 connect_timeout · Fastest of 5: 3.228Squid 6.13 connect_timeout · Slowest of 5: 3.971Squid 6.13 read_timeoutSquid 6.13 read_timeout · Configured: 5Squid 6.13 read_timeout · Fastest of 5: 4.950Squid 6.13 read_timeout · Slowest of 5: 5.499Squid read_timeout, inthe chainSquid read_timeout, in the chain · Configured: 5Squid read_timeout, in the chain · Fastest of 5: 5.000Squid read_timeout, in the chain · Slowest of 5: 5.9610246 s
Timer Configured Fastest of 5 Slowest of 5
Go 1.24.4 header timeout 3 3.001 3.005
Go 1.24.4 dial timeout 3 3.001 3.002
Squid 6.13 connect_timeout 3 3.228 3.971
Squid 6.13 read_timeout 5 4.950 5.499
Squid read_timeout, in the chain 5 5.000 5.961

One Squid read timeout fired 50 ms before its configured 5 seconds. A sixth run, made later for the script output below, fired at 6.16 seconds. Cloudflare’s 524 documentation warns of a one-second difference on its side too. When you match an elapsed time against a known timeout to find the hop that fired, allow a little over a second either way.

The 502 that only appears sometimes

Intermittent 502s under steady traffic often come from keep-alive. If the application closes idle connections sooner than the proxy in front of it expects, the proxy can send a request down a connection that is already closing, and the reply is a reset. AWS documents exactly this for its load balancers and recommends an application idle timeout longer than the balancer’s 60-second default. We did not reproduce it in this lab.

Telling which hop sent it

The body and headers of the error usually identify its author. These are the fingerprints from our captures and from Cloudflare’s documentation:

Evidence in the response What it points to
X-Squid-Error and Server: squid/6.13, an HTML page of 3,466 to 3,740 bytes in our captures Squid wrote the error itself
Via header present, no error header of the proxy’s own The proxy relayed it; a hop further in wrote it
No Server header, Content-Length: 0 Go’s ReverseProxy with its default handler
Cloudflare-branded 502 or 504 page The origin’s error, relayed by Cloudflare
Blank 502 or 504 with no branding Cloudflare’s own error
520 to 524 Cloudflare describing a problem with the origin
Elapsed time equal to a known timeout The hop whose timer that is

The Via header is the most useful line here, because a proxy that relays an error adds itself to it. This script prints the evidence for a plain HTTP URL, optionally through a forward proxy. It uses only the Python standard library and ran on Python 3.15.0:

#!/usr/bin/env python3
"""Show which hop generated a 502 or 504. usage: hopcheck.py URL [PROXY]"""
import http.client, sys, time
from urllib.parse import urlsplit

def probe(url, proxy=None, timeout=30):
    u = urlsplit(url)
    if proxy:
        p = urlsplit(proxy)
        conn = http.client.HTTPConnection(p.hostname, p.port or 8080, timeout=timeout)
        target = url  # absolute-form request line, what a forward proxy expects
    else:
        conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=timeout)
        target = (u.path or "/") + ("?" + u.query if u.query else "")
    t0 = time.monotonic()
    conn.request("GET", target, headers={"Host": u.netloc})
    r = conn.getresponse()
    body = r.read()
    h = {k.lower(): v for k, v in r.getheaders()}
    print(f"status        {r.status} {r.reason}")
    print(f"elapsed       {time.monotonic() - t0:.3f}s")
    for name in ("server", "via", "x-squid-error", "cf-ray"):
        print(f"{name:<13} {h.get(name, '-')}")
    print(f"body bytes    {len(body)}")
    if "x-squid-error" in h:
        verdict = "the proxy you connected to wrote this error itself"
    elif "via" in h:
        verdict = "relayed through " + h["via"] + ", so a hop further in wrote it"
    else:
        verdict = "the server you connected to wrote it"
    print(f"verdict       {verdict}")

if __name__ == "__main__":
    probe(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)

Run against both chain cases, it separates the two errors that a status-only check would lump together:

$ python3 hopcheck.py "http://127.0.0.1:8080/slow?s=8" http://127.0.0.1:3138
status        502 Bad Gateway
elapsed       3.009s
server        -
via           1.1 squid-lab (squid/6.13)
x-squid-error -
cf-ray        -
body bytes    0
verdict       relayed through 1.1 squid-lab (squid/6.13), so a hop further in wrote it

$ python3 hopcheck.py "http://127.0.0.1:8083/slow?s=8" http://127.0.0.1:3138
status        504 Gateway Timeout
elapsed       6.158s
server        squid/6.13
via           1.1 squid-lab (squid/6.13)
x-squid-error ERR_READ_TIMEOUT 0
cf-ray        -
body bytes    3542
verdict       the proxy you connected to wrote this error itself

Your provider’s gateway may not be Squid, so the header names will differ. The method carries over: look for a header only the proxy adds, compare the body to that proxy’s known error page, and check the elapsed time against its documented timeout.

When each code is the right one to send

If you write or configure a gateway, the choice is mechanical.

  • Send 502 when the upstream refused or reset the connection, closed it without replying, failed the TLS handshake, or sent something you cannot parse. The upstream answered, badly.
  • Send 504 when a deadline you set ran out: the TCP connect, the TLS handshake, or the wait for response headers. The upstream did not answer in time.
  • Send 503 when the problem is yours: no healthy upstream to try, or you are shedding load. RFC 9110 lets you add Retry-After to a 503, and you should.

Squid’s choice of 503 for connect failures is defensible under that last rule, since from Squid’s side no path to the server exists, but it costs the reader information. Whatever you choose, mark the errors your gateway generates with a header of its own, the way Squid does with X-Squid-Error, so the next person can tell your errors from the ones you relayed.

What to do when one comes back through your proxy

First decide whose error it is. If your proxy wrote it, the target may never have seen your request. If the target’s gateway wrote it, your proxy did its job and the site is having trouble. The 403, 407 and 429 guide uses the same first step for blocks.

  1. A fast 502 means the next hop refused or dropped you. Retry a GET once, ideally on a fresh exit or session. If the 502s follow you across exits, the target or its gateway is down, and more retries only add noise.
  2. A 504 means someone gave up waiting. Compare the elapsed time with your client’s timeout, your provider’s documented timeout and the site’s CDN limit. If the target is simply slow, raise your read timeout or ask for less per request, then retry with exponential backoff rather than at once.
  3. A POST, PUT or anything that changes state needs care. RFC 9110 forbids a proxy from retrying a non-idempotent request automatically, and our chain shows why: the origin finished the work after the client saw 504. Check whether the action happened before you send it again.

curl’s --retry already treats 502 and 504 as transient. The manual that ships with curl 8.7.1 lists 408, 429, 500, 502, 503 and 504; the current online manual adds Cloudflare’s 522 and 524. curl waits one second, then doubles the wait each time. Against our Go proxy pointed at a closed port, two retries took three requests and 3.05 seconds of wall time:

$ curl --no-progress-meter --retry 2 -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8081/
Warning: Problem : HTTP error. Will retry in 1 seconds. 2 retries left.
Warning: Problem : HTTP error. Will retry in 2 seconds. 1 retries left.
502

In Python, the same policy belongs in your session’s retry adapter, limited to idempotent methods. The Python proxy guide shows where those settings live in requests, httpx and aiohttp. Whatever the client, log the elapsed time next to the status code. A 504 at 5.9 seconds and a 504 at 125 seconds are different problems with the same number.

Frequently asked questions

Is a 502 or 504 error my fault or the website's?
Usually neither your client nor the site's application wrote it. Both codes come from a gateway in between: your proxy, the site's CDN or its load balancer. Read the response headers and the elapsed time to find which one, then look at the hop behind it.
Can my own proxy return a 504?
Yes. A forward proxy times out like any other gateway. In our test Squid 6.13 returned its own 504, carrying an X-Squid-Error: ERR_READ_TIMEOUT header, after its 5-second read timeout, while the site behind it was still working on the request.
Should I retry a 502 or a 504?
Retry a GET once after a 502, quickly, ideally on a different exit. Back off before retrying a 504, because the upstream is slow and a repeat adds load. Do not automatically retry a POST or any other state-changing request after either code until you know whether it ran.
Why does my Go reverse proxy return 502 when the backend times out?
Because httputil.ReverseProxy writes a 502 for every error when its ErrorHandler field is nil, timeouts included. Set an ErrorHandler that checks for a timeout and writes 504. In our test that changed the answer from 502 to 504 with no change in timing.
What is the difference between a 504 and Cloudflare's 524?
A 524 is Cloudflare saying it connected to the origin but got no response within its proxy read timeout, 125 seconds by default. A 504 seen through Cloudflare is either the origin's own 504 on a Cloudflare-branded page, or Cloudflare's own error on a blank page.
What does "CONNECT tunnel failed, response 502" mean in curl?
Your proxy could not open the HTTPS tunnel to the target and answered the CONNECT request with that status. curl exits with code 56, %{http_code} prints 000, and %{http_connect} prints the proxy's status. Squid 6.13 sent 503 in this situation in our tests, where other proxies send 502.

Sources

  1. RFC 9110 §15.6.3: 502 Bad Gateway
  2. RFC 9110 §15.6.5: 504 Gateway Timeout
  3. RFC 9110 §15.6.4: 503 Service Unavailable and Retry-After
  4. RFC 9110 §9.2.2: Idempotent methods and automatic retries
  5. RFC 9110 §15.1: Heuristically cacheable status codes
  6. RFC 5737: IPv4 address blocks reserved for documentation
  7. Squid configuration directive: read_timeout
  8. Squid configuration directive: connect_timeout
  9. Go net/http/httputil: ReverseProxy and ErrorHandler
  10. Go 1.24.4 source: reverseproxy.go default error handler
  11. nginx 1.31.8 source: ngx_http_upstream_next() status mapping
  12. nginx 1.31.8 source: HTTP/0.9 fallback in the proxy module
  13. nginx 1.31.8 source: status 499, client closed request
  14. nginx documentation: proxy timeouts and proxy_next_upstream
  15. AWS: Troubleshoot your Application Load Balancer (HTTP 502 and 504)
  16. AWS: Application Load Balancer attributes, connection idle timeout
  17. Cloudflare: Error 502 or 504
  18. Cloudflare: Error 520
  19. Cloudflare: Error 521
  20. Cloudflare: Error 522
  21. Cloudflare: Error 524
  22. Cloudflare: Connection limits
  23. curl manual: --retry and --write-out variables
  24. Linux kernel: errno.h (ETIMEDOUT 110, ECONNREFUSED 111)

Read this page as Markdown · Quote it freely under CC BY 4.0 with a link back.