Skip to content

Handling 403 and 429 errors in web scrapers

A 429 Too Many Requests or 403 Forbidden in the middle of a scraping job means something different depending on who sent it. Here is how to tell the proxy gateway from the target site, which errors are worth retrying, and how to retry without making things worse.

Updated 9 November 2026

First: who sent the error?

When you scrape through a proxy, two servers can answer with an error: the proxy gateway and the site you are fetching. They need opposite fixes. A gateway 407 means your login is wrong. A site 403 means the site does not want to serve you that page.

For HTTPS targets, the difference is visible in your client. The client first sends CONNECT to the proxy to open a tunnel. If the gateway refuses, the error is the reply to CONNECT, and most libraries raise an exception instead of returning a response. In Python requests, that is ProxyError. If the tunnel opens, everything after it, including any 403 or 429, comes from the site:

python
import requests

proxy = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"

try:
    r = requests.get("https://example.com/", proxies={"http": proxy, "https": proxy}, timeout=30)
    print("site answered", r.status_code)   # a 403 or 429 here came from example.com
except requests.exceptions.ProxyError as e:
    print("gateway refused the tunnel:", e)  # e.g. "Tunnel connection failed: 407 ..."

With SOCKS5, gateway errors arrive as SOCKS reply codes and also surface as connection errors. Only plain http:// targets are ambiguous, because the gateway forwards the request and returns the response directly.

Errors from the hyperproxy gateway

These are the codes the gateway itself can return, from our errors reference:

Gateway statusMeaningRetry?
407Wrong credentials, invalid option, no balance or disabled loginNo. Fix the login or top up.
400Malformed request, or an https:// URL sent without CONNECTNo. Let the client tunnel HTTPS.
403Target not allowedNo. The destination is not available through the network.
404No exit matches your targetingNo. Widen targeting or add strict-false.
429Too many requestsYes, slower and with backoff.
502The exit could not reach the targetYes. A retry gets a new exit.
504The exit did not answer in timeYes. A retry gets a new exit.

A 404 often comes from very narrow targeting, such as a small city combined with an ASN. The targeting rules explain how strict-false drops the ASN, then the city, then the region, while keeping the country.

429 from the site: you are going too fast

429 Too Many Requests is defined in RFC 6585. It means you sent more requests than the site allows in some window. The window might be per IP, per session cookie, per API key or per whole client. The response may include a Retry-After header, either a number of seconds or an HTTP date (RFC 9110, section 10.2.3).

The right reaction:

  1. Wait as long as Retry-After says. If the wait is very long, reschedule the URL rather than holding a worker.
  2. Without Retry-After, back off exponentially with jitter. Doubling the wait each attempt and randomising it stops all your workers retrying at the same instant.
  3. Lower concurrency for that host. One 429 is a signal for the whole job, not one URL. A simple rule is to halve concurrency on a 429 and add one slot back after a run of clean responses.

Switching to a new IP after a 429 does not help if the limit is per session or per account, and it does nothing about the load you put on the site. Treat 429 as feedback to slow down. Our web scraping best practices cover sensible per-host rates.

403 from the site: the server said no

403 Forbidden means the server understood the request and refuses to serve it. Common reasons in scraping:

  • The path is not meant for automated clients. Check robots.txt and the site’s terms.
  • The content needs a login or is limited to some regions.
  • Your request is malformed or inconsistent, for example a missing Accept header, a cookie from one session sent with another, or a multi-step flow whose IP changes halfway.
  • Your traffic pattern tripped the site’s protection, usually because of rate.

Retrying a 403 straight away rarely changes anything and adds load. Log it, look at the response body, and fix the cause. If the site does not want automated access to that content, respect that and look for an API, a feed, or permission.

Consistency fixes many errors in multi-step flows. If page two depends on a cookie set by page one, keep the same exit for both with a sticky session: add session and ttl to the username, as in USER-cc-us-session-a81f-ttl-30. See Sessions.

A retry loop that behaves

This loop separates gateway errors from site errors, honours Retry-After, uses full-jitter backoff and gives up after a fixed number of attempts:

python
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

import requests

PROXY = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"
PROXIES = {"http": PROXY, "https": PROXY}

RETRY_STATUS = {429, 500, 502, 503, 504}   # from the site
FATAL_TUNNEL = ("407", "403", "404", "400")  # from the gateway: fix config, don't retry


def retry_after(resp: requests.Response) -> float | None:
    value = resp.headers.get("Retry-After")
    if not value:
        return None
    if value.isdigit():
        return float(value)
    try:
        when = parsedate_to_datetime(value)
        return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
    except (TypeError, ValueError):
        return None


def backoff(attempt: int, base: float = 1.0, cap: float = 60.0) -> float:
    return random.uniform(0, min(cap, base * 2 ** attempt))  # full jitter


def fetch(url: str, attempts: int = 5, max_wait: float = 300.0) -> requests.Response:
    for attempt in range(attempts):
        try:
            resp = requests.get(url, proxies=PROXIES, timeout=30)
        except requests.exceptions.ProxyError as e:
            if any(code in str(e) for code in FATAL_TUNNEL):
                raise  # wrong login, no balance, target not allowed, no matching exit
            wait = backoff(attempt)  # gateway 429 / 502 / 504: try again later
        except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
            wait = backoff(attempt)
        else:
            if resp.status_code not in RETRY_STATUS:
                return resp  # success, or a 4xx the site meant: don't retry it
            wait = retry_after(resp) or backoff(attempt)
            if wait > max_wait:
                raise RuntimeError(f"{url}: asked to wait {wait:.0f}s, reschedule instead")
        time.sleep(wait)
    raise RuntimeError(f"{url}: gave up after {attempts} attempts")

Without a session, every retry opens a new connection and gets a fresh exit from the rotating pool, which is what you want after a 502 or 504.

The shorter version with urllib3 Retry

If you only need to retry site responses, urllib3’s Retry does the backoff and Retry-After handling for you. Handle ProxyError yourself on top of it, as above. The Python requests proxy guide shows the full setup.

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

proxy = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"

retry = Retry(
    total=5,
    backoff_factor=1,            # 0s, 2s, 4s, 8s ... between attempts
    backoff_jitter=0.5,          # urllib3 2.x
    status_forcelist=[429, 500, 502, 503, 504],
    allowed_methods=["GET", "HEAD"],
    respect_retry_after_header=True,
)

session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
session.mount("http://", HTTPAdapter(max_retries=retry))
session.proxies = {"http": proxy, "https": proxy}

print(session.get("https://example.com/", timeout=30).status_code)

Scrapy and browsers

Scrapy’s retry middleware already retries 429 and 5xx responses, and AutoThrottle adjusts the delay to the server’s latency. Turn both on and set CONCURRENT_REQUESTS_PER_DOMAIN low. In Playwright, check response.status() after page.goto() and back off in your own loop. See the Scrapy and Playwright guides.

Set a retry budget

Retries are not free. Each one costs time, puts load on the target and, on residential proxies, uses bandwidth billed per GB. A job that retries five times against a site that is down for an afternoon pays for all of that traffic. Set limits:

  • A maximum number of attempts per URL, usually three to five.
  • A job-wide error budget. If more than a few percent of requests fail, pause the job and investigate instead of retrying harder.
  • Metrics by status code and by source (gateway or site), so you see a rising 429 rate before it becomes an outage.

Our article on how much bandwidth web scraping uses shows how retries add to the total.

FAQ

Why do I get 407 Proxy Authentication Required?

The gateway rejected your login. Check the username and password, that every targeting option is spelled correctly and used once, that you have balance, and that the login is enabled. Retrying will not help.

Should I retry 403 errors?

Generally not straight away. A 403 from the site is a deliberate refusal. Find the cause first: robots rules, a login wall, an inconsistent session, or too high a rate.

How long should I wait after a 429?

Use Retry-After if it is present. Otherwise back off exponentially, starting around one second and capping at a minute or so, with random jitter, and reduce concurrency for that host.

Does rotating IPs fix 429 errors?

Only when the limit is strictly per IP, and even then it keeps the same load on the server. Slowing down is the fix that works whatever the site counts.

Try it on your own workload

Sign up with GitHub or Google, create a proxy login and send your first request in a minute.

More blog