ProxyError Max retries exceeded: read the Caused by part

ProxyError Max retries exceeded often means no retry ran at all. See what each cause prints in requests and urllib3, tested, and which failures to retry.

Terminal session beside the takeaway: Max retries exceeded doesn't mean anything was retried. What each cause prints in requests 2.34.2 and urllib3 2.8.0. Tested 2026-11-05.
Quick summary · TL;DR
  1. Skip the first half of the message and read what follows Caused by. Seeing Tunnel connection failed: 407 means fix your login, and Connection refused means a dead host or port. A 502 is easier to misread, since it can point past the proxy at the target.
  2. Max retries exceeded doesn't mean anything was retried. requests defaults to zero retries, so the test proxy saw one connection. Raising the count won't rescue a wrong password either.
  3. If you only catch ProxyError, you're missing failures. A proxy that closes after CONNECT raised ConnectionError on urllib3 2.8.0, and a silent one raised ReadTimeout. SOCKS5 goes further, with no failure in the test raising ProxyError at all.
  4. Setting connect=0 won't stop a 407 being resent. A refused CONNECT spends the other counter, and Retry with total=3 sent it four times with no pause between them.

ProxyError Max retries exceeded means a request failed somewhere on the proxy path, and the part worth reading is the text after Caused by. With default settings requests made one attempt, so nothing was retried. Connection refused points at a dead host or port, Tunnel connection failed: 407 at your login, and a 502 or 500 can mean the target behind the proxy is the one that failed.

Raising the retry count or swapping the proxy won’t help with a bad password, and raising retries also changes which exception you catch. Every string below is true output from tests on 2026-11-05 and 2026-11-06, and this was the setup:

  • requests 2.34.2, urllib3 2.8.0 and Python 3.13.14 on macOS
  • Scripted test servers on 127.0.0.1 as the failing proxies
  • Real tinyproxy 1.11.3, proxy.py 2.4.10 and mitmproxy 12.3.1 for the rows that name them

Errno numbers are macOS ones. Going by the system error tables, not a run here, the refusal shown as 61 is [Errno 111] on Linux and [WinError 10061] on Windows, and the reset shown as 54 is 104 and 10054.

What ProxyError Max retries exceeded says

Here is the full message for a wrong password on an HTTPS site, with the port swapped for a placeholder:

requests.exceptions.ProxyError: HTTPSConnectionPool(host='127.0.0.1', port=PORT):
Max retries exceeded with url: / (Caused by ProxyError('Unable to connect to proxy',
OSError('Tunnel connection failed: 407 Proxy Authentication Required')))

Three parts of it mislead people.

  • host= names the site on an HTTPS request. It’s the target, and the proxy’s address may not appear in the outer text at all. On a plain http:// request the same field shows the proxy, which is easy to miss when you compare two tracebacks.
  • Max retries exceeded doesn’t mean retries ran. The test proxy counted one connection. requests builds its default adapter with zero retries, as its API docs (checked 2026-11-05) state, and urllib3 reports running out of a budget of zero in these same words.
  • Unable to connect to proxy can be false. In the message above the proxy answered with a clean 407. Python’s http.client closes the connection before it raises the tunnel error, and urllib3’s close() resets the flag that records a proxy was reached, so urllib3 treats it as never connected. A trace on 2.8.0 showed that flag go from true to false just before the wrap.

Older installs print Cannot connect to proxy. instead. That wording was on urllib3 1.25.11 and 1.26.20, and Unable to connect to proxy was on 2.0.7 onward.

Going straight to urllib3 changes the count. The urllib3 user guide (checked 2026-11-05) gives 3 retries as the default, so a ProxyManager hit the same 407 proxy with four connections and raised MaxRetryError. With retries=False it made one connection and raised the bare ProxyError.

Pull out the inner error

String-matching the outer message gets old fast. This helper returned the inner exception for every failure class in the test:

from urllib3.exceptions import MaxRetryError, ProtocolError

def inner_cause(exc):
    cause = exc.args[0] if exc.args else exc
    if isinstance(cause, MaxRetryError):
        cause = cause.reason
    cause = getattr(cause, "original_error", cause)
    if isinstance(cause, ProtocolError) and len(cause.args) > 1:
        cause = cause.args[1]
    return cause

Call it from except requests.exceptions.RequestException as e and log both type(cause).__name__ and cause. A 407 comes back as OSError with the tunnel text, and a dead port as NewConnectionError.

Match the Caused by text

All of these were raised as ProxyError on an HTTPS target, with Max retries exceeded in the message. A dead proxy gives you one of the first three rows:

Text inside Caused byWhat happenedLook at
NewConnectionError ... [Errno 61] Connection refusedNothing is listening on that host and portThe port number, then whether the proxy is up
NameResolutionError ... Failed to resolveThe proxy’s hostname didn’t resolveA typo in the host, or DNS inside your container
ConnectTimeoutError ... connect timeout=1The connection never completedFirewall rules and routing to the proxy
Tunnel connection failed: 407 Proxy Authentication RequiredThe proxy refused your loginUsername, password and their encoding
Tunnel connection failed: 403 ForbiddenThe proxy answered and refused this requestIts policy for that target or port
Tunnel connection failed: 429 Too Many RequestsThe proxy is limiting youYour rate and concurrency
Tunnel connection failed: 502 Bad GatewayThe proxy couldn’t complete the tunnelThe target first, then the proxy
Tunnel connection failed: 501 Unsupported method ('CONNECT')It’s a web server, not a proxyThe port number
RemoteDisconnected, after the tunnel openedThe tunnel died while you waited for the siteThe proxy’s stability, then the target

The status rows need one warning, because the code comes from whatever wrote it. With a good login and a closed target port, proxy.py and mitmproxy both sent 502 Bad Gateway, while tinyproxy sent 500 Unable to connect. So a 500 or 502 here can mean the proxy is fine and the target isn’t reachable from it, and swapping proxies won’t fix a target that’s down. The 501 row came from Python’s own http.server.

The ERR_TUNNEL_CONNECTION_FAILED guide goes deeper on tunnel refusals, and the wider proxy error codes list covers the same statuses in other clients.

Separate the proxy from your code

Run the same proxy through curl before you edit any Python. Against all three real proxies with no login, this printed 000 407 and curl: (56) CONNECT tunnel failed, response 407:

curl -sS -o /dev/null -w '%{http_code} %{http_connect}\n' -x http://HOST:PORT https://example.com/

The test pointed at a loopback target, so nothing left the machine. The second number is the proxy’s answer to CONNECT, and the curl proxy guide has the rest of the flags. If curl tunnels and Python doesn’t, stop looking at the proxy and look at your environment.

Bad login and password characters

Three test proxies gave the same 407 for a missing login and a wrong one. The string is reliable, and the 407 Proxy Authentication Required guide has the fix per client.

Fewer password characters break the URL than you’d guess. On requests 2.34.2, 2.31.0 and 2.25.1, a raw @, :, space or + in the password still logged in, and the proxy received the exact password. These didn’t:

  • A raw /, # or ? raised InvalidURL with Failed to parse, before any connection.
  • A raw ab%cd raised UnicodeEncodeError, also before any connection, and that isn’t a requests exception at all.
  • A raw ab%41 raised nothing locally. requests decoded it, the proxy received abA, and you get a 407.

Percent-encoding fixed all of them, so keep urllib.parse.quote(password, safe="") as the habit. A trailing newline in the password, raw or as %0A, reached the proxy and came back as a plain 407, which looks exactly like a wrong password.

Non-ASCII passwords are the exception, because encoding didn’t help. requests sends the login as latin-1, so пароль raised UnicodeEncodeError raw and encoded, and é went out as the single byte 0xE9, which got a 407 from a test proxy expecting UTF-8. Changing the password is the simple way out.

Failures that skip ProxyError

This is where except ProxyError lets you down, because not every proxy failure prints ProxyError Max retries exceeded. All of these failed on the proxy path and none raised it on urllib3 2.8.0:

What the proxy did (HTTPS target)requests raisedSays Max retries?
Closed right after reading CONNECTConnectionError, RemoteDisconnected, Remote end closed connection without responseNo
Accepted and said nothingReadTimeout, Read timed out, and with no timeout= it just hangsNo
Sent CONNECT 200, then silenceReadTimeoutNo
Sent CONNECT 200, then closedSSLError, UNEXPECTED_EOF_WHILE_READINGYes
Sent CONNECT 200, then a certificate you don’t trustSSLError, CERTIFICATE_VERIFY_FAILEDYes
Was an SSH portConnectionError, BadStatusLine('SSH-2.0-OpenSSH_9.9\r\n')No
Was a TLS or SOCKS5 port behind an http:// URLConnectionError, RemoteDisconnected or ConnectionResetError(54)No
Cut the tunnel mid-bodyChunkedEncodingError, IncompleteRead(10 bytes read, 990 more expected)No

ChunkedEncodingError is the sneaky one, because it isn’t a ConnectionError subclass, so except ConnectionError doesn’t catch it. ReadTimeout isn’t one either. Catch RequestException at the outer layer and branch on inner_cause.

Closed tunnel on a pooled session

A closed tunnel can stay invisible. A proxy that cut an idle tunnel between two calls on one Session caused no error, since urllib3 opened a new connection and the second call returned 200. That’s good for uptime and bad if you assumed one tunnel meant one exit address.

Plain http:// targets

No tunnel exists on a plain http:// request, so a 407, 403 or 502 from the proxy comes back as a normal response with that status code and no exception. That also goes for the wrong port:

SOCKS5 failures skip ProxyError

None of the SOCKS5 failures in the test raised ProxyError. These four came out as a plain ConnectionError, with Max retries exceeded and SOCKSHTTPSConnectionPool in the text and NewConnectionError as the cause:

  • Dead port: Failed to establish a new connection: [Errno 61] Connection refused
  • Wrong password: SOCKS5 authentication failed
  • No login sent: All offered SOCKS5 authentication methods were rejected
  • Target refused by the proxy: 0x05: Connection refused

mitmproxy’s SOCKS5 mode printed the same two login errors and reported a closed target as 0x04: Host unreachable. A socks5h:// URL on a silent port, or on the HTTP ports of tinyproxy, proxy.py and mitmproxy, gave ConnectTimeout instead, which is a ConnectionError subclass. Code written for HTTP proxies with except ProxyError will miss every one of those, so a move to SOCKS5 means revisiting your error handling.

Environment proxy variables you forgot

Getting ProxyError when your code has no proxy in it usually means an environment variable, and CI runners and corporate laptops are the first places to look. With a stale HTTPS_PROXY pointing at a closed port, the test gave these results:

CallResult
requests.get(url)ProxyError
requests.get(url, proxies={})ProxyError, an empty dict doesn’t switch it off
requests.get(url, proxies={"https": None})200
session.proxies = {"https": GOOD}ProxyError, the variable overwrites it
session.proxies = {"https": None}ProxyError
session.get(url, proxies={"https": GOOD})200
Session with trust_env = False200
The host listed in NO_PROXY200

With no variable set, Python’s getproxies falls back to the macOS System Configuration or the Windows registry, so a system proxy setting can do the same thing. The session row is the one that catches people, and the requests docs (checked 2026-11-05) do warn about it. requests.utils.get_environ_proxies(url) shows what requests picked up, and be careful where that output goes, because it includes any password in the variable. Clear https_proxy as well as HTTPS_PROXY, since the lowercase one won when both were set. The Python requests proxy guide covers the rest of the setup, including sessions and the https key.

An https:// proxy URL on a plain port is its own bug. Against tinyproxy and proxy.py, it hung for the full timeout and then raised ProxyError wrapping ReadTimeoutError. A test server that answered the TLS hello with plain HTTP got Your proxy appears to only use HTTP and not HTTPS instead, so check the scheme is http:// before you chase anything on this page.

Why retries rarely fix it

Raising the count does less for ProxyError Max retries exceeded than it looks like. The counters don’t work the way their names suggest either. This shows how many attempts each failure got on urllib3 2.8.0, with every Retry column at total=3:

FailureDefaultmax_retries=3connect=0read=0other=0
Refused port14144
407 on CONNECT14441
502 on CONNECT14441
Closes with no reply14414
Silent, read timeout14414
CONNECT 200, then closes14441

The proxy counted connections, except on the refused port, where nothing was listening and the count comes from Retry.increment calls. Four things follow from that table:

  • A refused CONNECT spends other, not connect or status. So connect=0 doesn’t stop a 407 from being sent four times, and neither does leaving 407 out of status_forcelist. With Retry(total=2, status_forcelist=[407], other=0) the proxy saw one connection. The status list only applied on plain http:// targets, where it gave three connections and a RetryError.
  • max_retries=3 retries more than the docs describe. The API docs say it never applies to “requests where data has made it to the server”. An integer goes through Retry.from_int, which leaves read retries on. A test server that read a whole GET and then stayed silent got that GET four times, and a silent proxy saw four connections too.
  • Turning retries on changes the exception. The silent proxy raises ReadTimeout by default. With max_retries=3 it raised ConnectionError with Max retries exceeded and ReadTimeoutError as the cause, so an except ReadTimeout block stops firing.
  • POST is safer, not safe. Under Retry(total=3) a POST to the closing or silent proxy got one attempt, but a POST to the 407 proxy still made four connections, because that counter ignores the method.

There’s no default backoff either, so on loopback those four 407s arrived inside a hundredth of a second. Repeating a wrong password that fast is a good way to annoy whoever runs the proxy.

A retry setup that fits proxies

Retry the connection failures that can clear on their own, and leave the rest to code that reads the status:

import re
import time

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

session = requests.Session()
adapter = HTTPAdapter(max_retries=Retry(total=3, read=0, other=0, backoff_factor=0.5))
session.mount("http://", adapter)
session.mount("https://", adapter)
PROXIES = {"http": PROXY, "https": PROXY}

def tunnel_status(exc):
    m = re.search(r"Tunnel connection failed: (\d{3})", str(exc))
    return int(m.group(1)) if m else None

def get(session, url, timeout=(5, 30), tries=3):
    for attempt in range(tries):
        try:
            return session.get(url, proxies=PROXIES, timeout=timeout)
        except requests.exceptions.ProxyError as e:
            if tunnel_status(e) not in (429, 500, 502, 503, 504) or attempt == tries - 1:
                raise
            time.sleep(2 ** attempt)

With PROXY set to the proxy’s http:// URL, this block gave these counts:

  • 407 or 403: one connection
  • Closing or silent proxy: one connection
  • 500, 502 or 503: three connections over about 3 seconds
  • Refused port: about 3 seconds too, which is the four attempts under that backoff
  • Proxy that never accepts: 23 seconds with the default timeout=(5, 30), which is four connect timeouts plus that backoff
  • A stale HTTPS_PROXY in the environment: ignored, because proxies= is on the call

The adapter and the wrapper don’t overlap here, because other=0 leaves tunnel statuses to the wrapper and the wrapper re-raises anything without one. On a plain http:// target a 502 comes back as a response, so the wrapper returns it and you still have to check status_code. other needs urllib3 1.26 or later, because 1.25.11 doesn’t accept it.

Version differences that change exceptions

The same failure can raise a different class on an older pin, which matters if your except blocks were written years ago. The urllib3 changelog for 2.0.0 (2023-04-26) records that ProxyError was changed to wrap errors from connecting to the proxy, and that enforce_content_length now defaults to true. These are the differences in the test:

urllib3 2.0.7 and 2.5.0, both with requests 2.32.5, matched 2.8.0 on all five rows. Swapping only urllib3 under requests 2.34.2 gave the same split, on Python 3.11 and 3.13 alike, so urllib3 is the pin that decides this. In practice except ConnectTimeout around a proxy works on a 1.26 pin and silently stops working on 2.x, and except ProxyError loses the silent and closing proxies in the same move. If you still run 1.26, watch the last row, since a truncated page arrives as a success.

ProxyError Max retries exceeded: what next

Stop at the first line that matches your Caused by text:

  1. Connection refused, Failed to resolve or ConnectTimeoutError is a reachability problem, so check the host and port and run the curl line. If no proxy should be involved, check HTTPS_PROXY.
  2. A 407 is your login. Don’t retry, fix the encoding and the credentials.
  3. A 403 is a policy refusal from the proxy, and retrying won’t change that either.
  4. A 429, 500, 502, 503 or 504 can be retried with backoff, but with the 5xx ones test the target from elsewhere before you blame the proxy.
  5. A 501 or an HTML page in the response usually means the port isn’t a proxy.
  6. RemoteDisconnected, ReadTimeout or IncompleteRead with a working login is an unstable path, so log how often it happens before you add retries.
  7. CERTIFICATE_VERIFY_FAILED means the certificate that came back isn’t one you trust. A proxy that decrypts traffic is one way to get there, so ask whoever runs it.

None of this depends on the proxy category. The strings come from requests and urllib3, so rotating residential proxies and datacenter proxies go through the same table. Every proxymint tier logs in with a username and password and includes both HTTP and SOCKS5, which means the 407 rows and the SOCKS5 list are the two to keep handy.

Frequently asked questions

Your request failed on the way through the proxy, and urllib3 had no retries left to try. With default requests settings only one attempt was made, so the useful part is the text after Caused by. Connection refused there points to a dead port, and Tunnel connection failed: 407 to a rejected login.

Because requests starts with a retry budget of zero, and urllib3 words the failure the same way whatever the budget was. A test proxy counted exactly one connection behind that message. Calling urllib3 directly is different, since its default of 3 retries made four connections.

Check the username and password first, then percent-encode them with urllib.parse.quote and safe set to an empty string. Two other causes look just like a wrong password and also give a 407. One is a stray newline from an environment variable, the other a raw % that decodes to something else, as ab%41 became abA in the test. An https:// site delivers this as ProxyError, while a plain http:// site gives you a normal response with status 407.

Only for failures that clear on their own, like a proxy restarting. A wrong password or a bad port fails the same way each time, and max_retries=3 just sent that 407 four times. It also changes the exception, since a silent proxy went from ReadTimeout to ConnectionError in the test.

requests reads HTTP_PROXY, HTTPS_PROXY and ALL_PROXY from the environment, so a stale value on a CI runner or laptop is the first thing to check. Print requests.utils.get_environ_proxies(url) to see what it found. With no variable set, Python also falls back to the macOS or Windows system proxy settings. In the test proxies={} didn't switch it off, and neither did session.proxies, while proxies with https set to None and trust_env = False on a session both did.

ProxyError is a subclass of ConnectionError, so except ConnectionError catches both. Being a ConnectionError says little about the proxy, though. A proxy that closes after CONNECT raised plain ConnectionError on urllib3 2.8.0, and no SOCKS5 failure in the test raised ProxyError. RequestException is the safer outer catch, because ReadTimeout and ChunkedEncodingError aren't subclasses of ConnectionError.

On urllib3 2.x a connect timeout to an HTTP proxy is wrapped in ProxyError, so that block never fires. The same failure raised ConnectTimeout on urllib3 1.26.20, which is why this tends to show up after an upgrade. Catch ProxyError and read the inner ConnectTimeoutError instead.

Researched and drafted with AI tools, then checked against our publishing rules before it went live: 8 outside links, 7 links to other proxymint pages, no prices and a fact-check pass against our product records. How we write.