---
title: "502 Bad Gateway and 504 Gateway Timeout: who failed, and fixes"
description: "502 Bad Gateway and 504 Gateway Timeout mean a server in the middle failed: the site, your proxy or your scraper API. How to tell which, and how to fix it."
url: "https://scrapenews.com/errors/502-504-bad-gateway-timeout"
updated: "2026-11-26T00:00:00Z"
---

# 502 Bad Gateway and 504 Gateway Timeout: who failed, and fixes

HTTP status codes · 502

Published 26 Nov 2026

What you see

- `502 Bad Gateway`
- `504 Gateway Timeout`
- `504 Gateway Time-out`
- `HTTP Error 502: Bad Gateway`

**More error strings (4)**

- `502 Server Error: Bad Gateway for url`
- `504 Server Error: Gateway Timeout for url`
- `Request failed with status code 504`
- `Destination host connect timeout`

## What it means

502 Bad Gateway and 504 Gateway Timeout come from a server in the middle, not from the page you want. 502: that server got a broken answer from the next one. 504: it got no answer in time. The server in the middle can be the site’s own front door, a CDN, your proxy or your scraper API. Find out which one first.

## What we measured: no bot wall sent us 502 or 504

We asked 100 well-known sites for one page each from a datacenter IP, and some of them again through two residential proxies (probe runs `2353`, `0129-oxy-resi` and `0129-bd-resi`, 25 Nov 2026 to 26 Nov 2026).

- Sites that blocked our requests with 403: 35. With 429: 5.
- Sites that answered 502 or 504: 0.
- Sites that answered Cloudflare’s 520 through 524: 0.
- A server error sent as a wall: a 500 from search.yahoo.com.

**On these sites, 502 and 504 were never how a wall said no.** So when you get one, suspect a broken or slow hop before you blame a block.

How we tested: one plain request per site, the kind a script sends, with no browser. First from a datacenter IP (an address in a server farm, the cheapest kind), then through residential proxies (IPs borrowed from home internet connections). The datacenter pass started at 23:53 UTC.

A 403 says “I won’t serve you”. A 429 says “too many from you”. Both are a choice the site made about you. A 502 or 504 is no choice at all: a hop broke or ran out of time.

That gap shapes how you retry. A block won’t clear if you send the same request again, but a broken hop often will.

Two limits. Each site got very few requests from us, and Cloudflare lists heavy server load as a cause of 504, so a fast crawl can still trigger one. And scraper APIs blur the line: Bright Data’s Web Unlocker reports a CAPTCHA or protection page it ran into as its own 502.

## Why it happens

Your request often passes several servers, starting with your proxy or scraper API, then a CDN (a network of servers in front of the site), then the site’s web server, and then the app behind it. Any of them can send 502 or 504.

The usual causes, most common first:

1. **The site’s own machines are slow or down.** Overload, a crash or a network failure behind the front door. Cloudflare says most 502/504s it shows come from the site’s own server, not from Cloudflare.
2. **Your proxy couldn’t reach the site.** Oxylabs datacenter proxies send 504 when the site doesn’t answer, “usually about 60s”. Bright Data sends 502 with `Destination host connect timeout` when the link to the site times out.
3. **Your proxy had its own problem.** Bright Data also uses 502 for things that have nothing to do with the site: your zone hit its usage limit, the IP of your sticky session is gone, or it has no IPs in the city you asked for.
4. **Your scraper API gave up.** Each one has its own code. ZenRows sends 504 when a request runs past its time limit. Oxylabs Web Scraper API sends 524 “Timeout”. Zyte sends 500 with `/server/timed-out`. ScraperAPI retries for up to 70 seconds, then sends 500.
5. **The scraper API hit a block and calls it 502.** Bright Data’s Web Unlocker returns 502 when the unlock failed, for example “captcha or protection page found”. Here a 502 does mean a block. It is just not the site’s.
6. **A CDN in front failed.** Cloudflare can send its own 502 or 504, for example when the site serves broken gzip compression. It may also send a short 502 as it moves traffic between data centers.

**The trap: the same code means different things at each hop.** A 502 from Bright Data can mean “your zone is out of budget”. A 502 from nginx (a common web server) means the app behind it broke. Read who sent it before deciding to change anything.

502 versus 504, in one picture: a receptionist phones the back office for you. A dead line or a garbled answer, and you hear 502. Nobody picks up before the receptionist gives up, and you hear 504.

MDN says the same in tech terms. Like 500, a 502 is a catch-all, yet it marks the link in the chain that broke. If the site sends a proper error, the hop should pass that on instead of a 502.

Each hop has its own time limit:

- nginx: 60 seconds by default, counted between two reads, not for the whole page.
- Oxylabs datacenter proxies: about 60 seconds.
- ScraperAPI: up to 70 seconds of retrying.
- Cloudflare waits 125 seconds, then sends a 524.

So the hop with the shortest wait sends the error. Often, that is not the slow hop.

## Fix it

1. **Find who sent it.** Check the headers and the body:
   - `x-brd-error` or `x-brd-err-code` header: Bright Data sent it. Bright Data says its headers cover most failures from its proxy layer, so no such header usually means another hop sent it.
   - A JSON body with a `code` (ZenRows) or a `type` like `/download/temporary-error` (Zyte): the API sent the error.
   - A Cloudflare-branded page: the site’s server failed behind Cloudflare. A blank, unbranded 502/504: Cloudflare itself.
   - A plain page titled `502 Bad Gateway` or `504 Gateway Time-out` with “nginx” under it: the site’s front server.
2. **Open the URL in a normal browser, without your proxy.** Broken there too? The site is having a bad moment. Give it time and try again.
3. **Retry a couple of times, with growing waits.** 1 second, then 2, then 4, then stop. ZenRows tells you to retry its 500, 502, 503 and 504 with backoff and jitter (a small random extra wait). Scrapy already retries 502 and 504 by default.
4. **Proxy error? Change the IP, not the code.** Bright Data’s own advice on its 502s: retry with a new session ID or IP, change the country if the site is blocked there, and use an IPv4 proxy when the site has no IPv6 address.
5. **Scraper API timing out? Raise your client timeout above the API’s.** ScraperAPI asks for 70 seconds. Bright Data’s Web Unlocker says at least 180 seconds. ZenRows advises no less than 3 minutes. Cut it shorter and you may pay for nothing (table below).
6. **Don’t hammer it.** ZenRows can block your IP for “exceeding the maximum error rate allowed”. A tight retry loop on a broken page will get you there quickly.
7. **Own the site?** Cloudflare says that a branded 502/504 came from your server, so check its load, crashes and timeouts. Behind nginx, the app has 60 seconds by default to answer (`proxy_read_timeout`).

Are you charged for a request that fails? Each API’s own docs:

| service | what a timeout or failure looks like | charged? |
| --- | --- | --- |
| Bright Data Web Unlocker | 502, reason in `x-brd-error-code` | no: “only charges for successful requests”. With custom headers and cookies on, you pay for all requests, failed too |
| Oxylabs Web Scraper API | 524 Timeout · 612, 613 faulted job | no: Oxylabs doesn’t bill its own 5xx and 6xx errors |
| Oxylabs Web Unblocker | 408 Timeout · 550 too many retries | 550: no. 408: yes, Oxylabs counts every 2xx and 4xx as a success and bills it |
| ScraperAPI | 500 after up to 70 seconds of retries | no. But yes if you cancel before 70 seconds |
| Zyte API | 500 `/server/timed-out` · 520 ban | no, for any unsuccessful response |
| ZenRows | 504 `CTX0002` · 499 `CTX0001` (you hung up) | no. But after a read timeout on your side, ZenRows may still finish the request and charge it |

**Your own timeout is the costly one.** ScraperAPI bills requests you cancel before 70 seconds. ZenRows may bill a request your client gave up on, so a blind retry can pay twice. Check your dashboard before you send it again.

Getting 503 instead? See [503 Service Unavailable](https://scrapenews.com/errors/503-service-unavailable.md): it can be a bot wall. Getting 429? That’s a rate limit: see [429 Too Many Requests](https://scrapenews.com/errors/429-too-many-requests.md).

Cloudflare’s own codes, for when the page says “cloudflare” and a 52x number (pages for each are in Cloudflare’s docs):

- **520:** the site’s own server returned an unknown error.
- **521:** the site’s machine is down.
- **522:** the connection timed out.
- **523:** the site’s machine is unreachable.
- **524:** a timeout occurred. By default, Cloudflare waited 125 seconds for an answer.

Why the sender comes first: each hop needs its own fix. A zone limit at Bright Data needs a setting changed. A dead session needs a new IP. A slow site needs patience. A blind retry treats all three the same.

ZenRows’ docs make a useful split between two timeout types:

- Connect timeout, refused connection or DNS failure: the request never reached the API. Retry without worry.
- Read timeout after the request went out: the API could still be working on it. It keeps its slot in your concurrency limit until it ends, so a quick retry can pay twice and run into 429.

Bright Data explains the billing switch: with your own headers and cookies, it no longer controls the full unlock, so it bills every request.

Oxylabs bills by the status code. Any 2xx or 4xx counts as a success, even when the page lacks what you wanted. Failures from its own systems (5xx, and 6xx on Web Scraper API) are free. A failure caused by an error on your side is billed. So on Web Unblocker, a 408 timeout costs you, but a 5xx does not.

Our advice: log the provider’s error code and request ID with every failure. Support teams ask for them. Cloudflare asks site owners for the time, the time zone and the URL.

Scraper and unblocker APIs: price for 100k requests a month, cheapest first

| Vendor, plan it picks | Total a month | $/1k req | Total a year | Free trial · note · source |
| --- | --- | --- | --- | --- |
| [Zyte API](https://scrapenews.com/compare/zyte-api.md) (Pay as you go) | $13 | $0.13 | $156 | $5, 30 days credit ([zyte.com · 25 Nov 2026](https://www.zyte.com/pricing/)) |
| [ScrapeBadger](https://scrapenews.com/compare/scrapebadger.md) (Pay as you go) | $15 | $0.15 | $180 | ([scrapebadger.com · 25 Nov 2026](https://scrapebadger.com/pricing)) |
| [ScrapeOps](https://scrapenews.com/compare/scrapeops.md) (Monthly: $19) | $19 | $0.19 | $228 | ([scrapeops.io · 29 Nov 2026](https://scrapeops.io/proxy-api-aggregator/)) |
| [ScrapingAnt](https://scrapenews.com/compare/scrapingant.md) (Enthusiast) | $19 | $0.19 | $228 | ([scrapingant.com · 29 Nov 2026](https://scrapingant.com)) |

List prices from each vendor’s pricing page, US dollars before tax, live from our price data. Your own size, in the price calculator: [Scraper and unblocker APIs](https://scrapenews.com/compare/scraper-apis.md).

Paste this into your AI

```
My scraper gets "<502 Bad Gateway or 504 Gateway Timeout>".
Response headers: <paste them, e.g. Server, x-brd-error, x-brd-err-code, cf-ray>.
First lines of the body: <paste them>.
Tell me in plain words which hop most likely sent it: the site's own server, a CDN in front of it,
my proxy, or my scraper API. Then list the likely causes in order, most likely first.
For each cause, give one way to test it and one fix.
My setup: <language + library>, <the URL pattern>, <direct, proxy (which provider and type) or scraper API (which one)>,
<my client timeout in seconds>, <requests in parallel>.
Does the URL load in a normal browser on the same network? <yes/no>
```

## Dev details

The two status lines, as RFC 9110 defines them:

```http
HTTP/1.1 502 Bad Gateway
HTTP/1.1 504 Gateway Timeout
```

MDN adds a rule for gateways. If the site sends a proper error, the gateway should pass that error on instead of a 502. No answer at all from the site means 504.

nginx’s built-in error pages use these titles (note the hyphen in “Time-out”):

```text
502 Bad Gateway
504 Gateway Time-out
```

How the error appears in common libraries:

```text
requests (raise_for_status):  502 Server Error: Bad Gateway for url: https://…
Python urllib:                HTTP Error 502: Bad Gateway
axios:                        Request failed with status code 504
```

requests and urllib show the reason the server sent. nginx’s status line says `504 Gateway Time-out`, so behind nginx the message reads `Gateway Time-out`.

Through a proxy on an `https://` URL, the failure can come before your request ever reaches the site. Your client first asks the proxy to open a tunnel (a `CONNECT` request). If the proxy answers with 502 or 504, Python and curl print this (wording from their source code):

```text
Python (http.client, inside requests):  Tunnel connection failed: 502 Bad Gateway
curl:                                    curl: (7) CONNECT tunnel failed, response 502
```

So the proxy sent the error, not the site. Python prints whatever reason the proxy wrote after the code. For more on these: [Tunnel connection failed](https://scrapenews.com/errors/err-tunnel-connection-failed.md) and [Python requests ProxyError](https://scrapenews.com/errors/python-requests-proxyerror.md).

### Bright Data: two places for one status

Web Unlocker’s Direct API answers 200 and puts the real result in a header. The native proxy puts it in the status line. Bright Data’s docs show the same failure both ways:

```http
HTTP/1.1 200 OK
x-brd-error: Navigation failed: The SSL/TLS certificate presented by the server is not valid for the current date
x-brd-error-code: net_err_cert_date_invalid
x-brd-status-code: 502
```

```http
HTTP/1.1 502 Navigation failed
x-brd-error: Navigation failed: The SSL/TLS certificate presented by the server is not valid for the current date
x-brd-error-code: net_err_cert_date_invalid
```

So a check on `res.status` alone misses Direct API failures. Read `x-brd-status-code` too.

Bright Data proxy 502 codes (in `x-brd-err-code`) worth knowing:

| code | means | fix |
| --- | --- | --- |
| `client_10100` | zone has reached usage limit | raise or remove the limit |
| `client_10064` | the IP of your sticky session is gone | retry with the same session ID, or a new one for a new IP |
| `peer_30060` | the peer (exit IP) could not connect to the site | retry with a different session ID |
| `policy_20070` | site blocked in the requested country | change country |
| `target_40020`, `target_40021` | `Destination host connect timeout` | check the URL and port, retry |
| `internal_50010` | Bright Data internal error | retry, then contact support |

A timeout on the way to the target can also come back as 408 (`peer_30040`, “Peer did not connect to destination due timeout”). The old `X-Luminati-Error` header is now `x-brd-error`.

### Zyte and ZenRows

Zyte answers with JSON. Its 520 and 521 aren’t Cloudflare’s:

```json
{"status": 520, "type": "/download/temporary-error"}
{"status": 521, "type": "/download/internal-error"}
{"status": 500, "type": "/server/timed-out"}
```

520 is usually a ban: retry it. 521 is permanent, but Zyte says some bans get flagged as 521 by mistake, so retry a 521 that only shows up sometimes. When the site sends its own error and it isn’t a ban, Zyte passes it on in a successful response, in its `statusCode` field.

ZenRows puts a `code` in every failure body. Record it alongside the URL:

- `CTX0002` (504): the request ran past ZenRows’ maximum time.
- `CTX0001` (499): your client shut the connection first.
- `RESP003` (502): the `autoparse` option could not parse the page, so drop `autoparse` and parse the HTML yourself.

### Retry 502 and 504 in Python

urllib3’s `Retry` only retries a status you list. By default it skips POST: its `allowed_methods` are DELETE, GET, HEAD, OPTIONS, PUT and TRACE.

```python
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry

retry = Retry(total=4, status_forcelist=[502, 504], backoff_factor=1)
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
resp = session.get("https://example.com/page", timeout=180)
```

Set `timeout` above your scraper API’s own limit, otherwise you cut it off mid-job.

### Scrapy

`RETRY_HTTP_CODES` defaults to `[408, 429, 500, 502, 503, 504, 522, 524]`. DNS failures and dropped connections are always retried.

### Edge cases

- **Oxylabs’ 524** is its Web Scraper API timeout, not Cloudflare’s.
- **Oxylabs Web Unblocker** lumps 500, 502 and 503 together as “issues on our side”.
- **Cloudflare 524:** Enterprise customers can raise the 125-second wait up to 6,000 seconds.
- **Cloudflare 504 in logs** can also stem from cache misses on Early Hints or the Workers Cache API, with no visitor ever seeing it.
- **Bright Data’s `expect_element`** errors come after waits of 30 to 150 seconds, and a shorter client timeout hides the actual error.
- **A VPN or local proxy** can cause it too. MDN says to check your network, firewall, proxy and DNS settings if the site works for everyone else.

How to retry, provider by provider:

- **Zyte:** its Python and Scrapy libraries already retry ban responses up to 3 times. Our advice: don’t stack your own loop on top without a cap.
- **Bright Data `reject_block`:** each retry uses a different peer, and Bright Data has seen the same URL work on a later try.
- **Bright Data `http_status`:** the site answered with a blocking code, 429 included. One retry is worth it. Past that point, the site is blocking your setup.
- **Bright Data `expect_element`:** a URL that fails this way keeps failing, so report it with the `req_id` instead of retrying.
- **Bright Data Direct API:** an outer status other than 200 means the unlock never started: 401 for API key problems, 400 for an unknown zone or a bad URL.

Owners behind Cloudflare can change the 125-second read wait with a Cache Rule or the zone setting API. The 30-second write wait can’t be changed. If you tune urllib3, its backoff waits are capped at 120 seconds.

## Related

- [Why am I blocked? How to avoid getting blocked while scraping](https://scrapenews.com/guides/how-to-avoid-getting-blocked-scraping.md)  (Guide)
- [Rotating proxies](https://scrapenews.com/guides/rotating-proxies.md)  (Guide)
- [Scraper and unblocker APIs](https://scrapenews.com/compare/scraper-apis.md)  (Compare)
- [503 Service Unavailable](https://scrapenews.com/errors/503-service-unavailable.md)  (Error)
- [ECONNRESET and ERR_CONNECTION_RESET](https://scrapenews.com/errors/econnreset-connection-reset.md)  (Error)
- [ERR_HTTP2_PROTOCOL_ERROR when scraping](https://scrapenews.com/errors/err-http2-protocol-error.md)  (Error)

## Tools that get past it

| Tool | Price |
| --- | --- |
| [ScraperAPI](https://scrapenews.com/compare/scraperapi.md): Scraping API that rotates proxies and can render JavaScript. Monthly credit plans; harder pages cost more credits. | $0.49/1k req |
| [Scrapy](https://scrapenews.com/compare/scrapy.md): Python framework for crawling sites and extracting data: request queue, retries, pipelines, exports. Large plugin ecosystem. | Free |
| [Zyte API](https://scrapenews.com/compare/zyte-api.md): Zyte's scraping API: prices each site by difficulty tier, with or without browser rendering. Pay as you go or monthly commitment. | $0.13/1k req |

## Sources

1. [RFC 9110 §15.6.3: 502 Bad Gateway](https://www.rfc-editor.org/rfc/rfc9110#name-502-bad-gateway) rfc-editor.org
2. [RFC 9110 §15.6.5: 504 Gateway Timeout](https://www.rfc-editor.org/rfc/rfc9110#name-504-gateway-timeout) rfc-editor.org
3. [MDN: 502 Bad Gateway](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/502) developer.mozilla.org
4. [MDN: 504 Gateway Timeout](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/504) developer.mozilla.org
5. [Cloudflare docs: Error 502 or 504](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-5xx-errors/error-502-504/) developers.cloudflare.com
6. [Cloudflare docs: Cloudflare 5xx errors (520 to 524)](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-5xx-errors/) developers.cloudflare.com
7. [Cloudflare docs: Error 524](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-5xx-errors/error-524/) developers.cloudflare.com
8. [Bright Data docs: Proxy errors troubleshooting](https://docs.brightdata.com/proxy-networks/errorCatalog) docs.brightdata.com
9. [Bright Data docs: Web Unlocker API error codes](https://docs.brightdata.com/products/web-unlocker/error-codes) docs.brightdata.com
10. [Bright Data docs: Web Unlocker API features (billing with custom features)](https://docs.brightdata.com/products/web-unlocker/features) docs.brightdata.com
11. [Oxylabs docs: Datacenter Proxies response codes](https://developers.oxylabs.io/products/proxies/datacenter-proxies/response-codes) developers.oxylabs.io
12. [Oxylabs docs: Web Unblocker response codes](https://developers.oxylabs.io/products/web-unblocker/response-codes) developers.oxylabs.io
13. [Oxylabs docs: Web Scraper API response codes](https://developers.oxylabs.io/products/web-scraper-api/response-codes) developers.oxylabs.io
14. [Oxylabs docs: Web Scraper API traffic and billing](https://developers.oxylabs.io/products/web-scraper-api/usage-and-billing/billing-information) developers.oxylabs.io
15. [Oxylabs docs: Web Unblocker billing information](https://developers.oxylabs.io/products/web-unblocker/billing-information) developers.oxylabs.io
16. [CPython source: http/client.py ('Tunnel connection failed')](https://github.com/python/cpython/blob/main/Lib/http/client.py) github.com
17. [curl source: cf-h1-proxy.c ('CONNECT tunnel failed, response')](https://github.com/curl/curl/blob/master/lib/cf-h1-proxy.c) github.com
18. [ScraperAPI docs: API Status Codes](https://docs.scraperapi.com/responses-and-formats/api-status-codes) docs.scraperapi.com
19. [ScraperAPI docs: Credits and Requests costs](https://docs.scraperapi.com/getting-started/quick-start/credits-and-requests-costs) docs.scraperapi.com
20. [Zyte docs: Zyte API error handling](https://docs.zyte.com/zyte-api/usage/errors.html) docs.zyte.com
21. [ZenRows docs: API Error Codes](https://docs.zenrows.com/api-error-codes) docs.zenrows.com
22. [ZenRows docs: Retry failed requests](https://docs.zenrows.com/academy/retry-failed-requests) docs.zenrows.com
23. [nginx docs: ngx_http_proxy_module (proxy_read_timeout)](https://nginx.org/en/docs/http/ngx_http_proxy_module.html) nginx.org
24. [nginx source: built-in 502 and 504 error pages](https://github.com/nginx/nginx/blob/master/src/http/ngx_http_special_response.c) github.com
25. [nginx source: status lines (504 Gateway Time-out)](https://github.com/nginx/nginx/blob/master/src/http/ngx_http_header_filter_module.c) github.com
26. [Scrapy docs: RETRY_HTTP_CODES](https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#retry-http-codes) docs.scrapy.org
27. [urllib3 docs: Retry](https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html) urllib3.readthedocs.io
28. [requests source: raise_for_status message](https://github.com/psf/requests/blob/main/src/requests/models.py) github.com
29. [CPython source: urllib HTTPError message](https://github.com/python/cpython/blob/main/Lib/urllib/error.py) github.com
30. [axios source: status error message](https://github.com/axios/axios/blob/v1.x/lib/core/settle.js) github.com

## Up

- [Home](https://scrapenews.com/index.md)
- [Errors & CAPTCHAs](https://scrapenews.com/errors.md)
