httpx proxy: setup, auth, SOCKS5, async pools and rotation

Set a proxy in Python httpx after 0.28 removed proxies=: proxy= and mounts, auth, SOCKS5, AsyncClient pool limits, rotation and the errors each mistake raises.

An httpx AsyncClient pool with four connection slots, all taken. One CONNECT site:443 tunnel per slot runs into a proxy reading http://HOST:PORT and on to the HTTPS site, TLS end to end. Queued requests wait; the last is red: PoolTimeout
Quick summary · TL;DR
  1. httpx takes one proxy= argument now. httpx.Client(proxy="http://USERNAME:PASSWORD@HOST:PORT") routes HTTP and HTTPS. The old proxies= argument was removed in 0.28.0 and raises a TypeError; per-scheme or per-host routing moved to mounts=.
  2. The proxy URL stays http:// for HTTPS sites. httpx sends CONNECT through the proxy and TLS runs end to end with the site. An https:// proxy URL means TLS to the proxy itself and usually ends in a handshake timeout.
  3. An explicit proxy beats the environment. With proxy= set, httpx ignores HTTP_PROXY and HTTPS_PROXY. Passing a custom transport= switches environment proxies off without any error.
  4. Each concurrent HTTPS request is its own tunnel. An AsyncClient opens up to 100 connections by default, each a separate CONNECT to the proxy port. PoolTimeout means the client's own pool ran out, not that the proxy failed.
  5. There is no per-request proxy in httpx. Rotation happens behind one gateway URL or across one client per endpoint, and keep-alive can hold one exit on a reused tunnel.

To use an httpx proxy, pass the proxy URL to the client: httpx.Client(proxy="http://USERNAME:PASSWORD@HOST:PORT"). That one argument routes HTTP and HTTPS requests, and the URL keeps the http:// scheme even for HTTPS sites. The old proxies= argument was removed in httpx 0.28.0, so code copied from older tutorials fails with a TypeError. For per-host routing, use mounts=.

That covers the first five minutes of an httpx proxy setup. Failures come later, and most of them do not look like proxy problems: an async job that throws PoolTimeout at a few hundred tasks, an exit IP that never changes although the order says “new IP every request”, a 407 check that never fires, a custom transport that silently drops the proxy from the environment. Each one has a cause in how httpx builds connections, and a fix below.

Every snippet is written for httpx 0.28.1 and works the same on httpx2, the maintained continuation of the project. Placeholders stand in for real credentials: HOST, PORT, USERNAME, PASSWORD.

httpx proxy setup in five lines

Read the proxy URL from the environment, set a timeout that allows for the extra hop, and check the exit IP before anything else runs:

import os
import httpx

PROXY = os.environ["PROXY_URL"]  # http://USERNAME:PASSWORD@HOST:PORT

with httpx.Client(proxy=PROXY, timeout=httpx.Timeout(30.0, connect=10.0)) as client:
    print(client.get("https://httpbingo.org/ip").json())

proxy= maps to the all:// pattern, so every request from this client goes through the proxy. The top-level helpers take the same argument (httpx.get(url, proxy=PROXY)), but each call builds and closes its own client, so nothing is reused between calls. For more than a handful of requests, keep one client open.

Set the timeout on purpose. The httpx timeouts docs (release 0.28.1, December 2024) set a 5-second default on connect, read, write and pool. A proxied HTTPS request spends part of that on the CONNECT to the proxy and a TLS handshake that runs through the exit, so a slow exit can raise ReadTimeout on a page that loads fine without the proxy.

The proxies argument is gone

The httpx changelog dates the change: 0.26.0 (2023-12-20) added proxy and deprecated proxies, and 0.28.0 (2024-11-28) removed it. Code written before then now stops at construction:

TypeError: Client.__init__() got an unexpected keyword argument 'proxies'

Migrating is mechanical:

Old callCurrent call
proxies="http://HOST:PORT"proxy="http://HOST:PORT"
proxies={"all://": URL}proxy=URL
proxies={"http://": A, "https://": B}mounts={"http://": httpx.HTTPTransport(proxy=A), "https://": httpx.HTTPTransport(proxy=B)}
Same on AsyncClienthttpx.AsyncHTTPTransport(proxy=...) inside mounts

Which httpx package you have

On PyPI (checked 2026-10-14), httpx 0.28.1 of 2024-12-06 is still the latest stable release, and the 1.0 line ships as pre-releases only. httpx2, maintained by Pydantic and at 2.13.1 since 2026-09-23, carries the project on under a new import name. Its proxy API matches: proxy=, mounts=, the same four schemes and the same error classes. Swap import httpx for import httpx2 as httpx and the code here runs as written.

If the proxy is set but an SDK still connects directly, the SDK built its own client. Check whether it accepts a client object and pass one that carries the proxy.

Proxy URL scheme and authentication

http:// for HTTPS targets

For an HTTPS site, httpx connects to the proxy in plain TCP and sends CONNECT site:443. The proxy opens a tunnel and TLS runs end to end between the script and the site, so the proxy relays encrypted bytes it cannot read. That is why the proxy URL stays http:// for HTTPS traffic. The httpx proxies docs put it as a gotcha: the proxy URL for the https:// key “should use the http:// scheme (that’s not a typo!)”.

An https:// proxy URL means something else. It asks httpx to open TLS to the proxy itself, a mode added in 0.25.0 (2023-09-11). Against a proxy port that speaks plain HTTP, the troubleshooting page shows the result: httpx.ProxyError: _ssl.c:1091: The handshake operation timed out. Changing one word in the URL fixes it.

httpx accepts four schemes: http, https, socks5 and socks5h. Anything else, including a URL with no scheme at all such as HOST:8080, raises ValueError: Unknown scheme for proxy URL when the client is built.

Plain http:// targets have a catch of their own. proxymint’s per-GB gateway answers every plain-HTTP request with a 301 to the https:// address (proxymint Lab, measured 2026-09-28), and httpx does not follow redirects unless follow_redirects=True is set. A health check against an http:// URL then reads 301 and looks broken. Point checks at https:// URLs.

Credentials and special characters

Credentials go in the userinfo part of the URL. httpx moves them into a Proxy-Authorization header and strips them from the proxy URL it stores. An @ or : inside the password happens to parse, because httpx splits at the last @. A /, # or ? does not: the URL breaks at that character and the client raises httpx.InvalidURL: Invalid port. Percent-encode both parts, or keep the URL clean and pass the pair:

import os
from urllib.parse import quote
import httpx

user = quote(os.environ["PROXY_USER"], safe="")
password = quote(os.environ["PROXY_PASS"], safe="")
proxy_url = f"http://{user}:{password}@HOST:PORT"

# or, without encoding:
proxy = httpx.Proxy("http://HOST:PORT", auth=(os.environ["PROXY_USER"], os.environ["PROXY_PASS"]))
client = httpx.Client(proxy=proxy)

httpx.Proxy also takes headers=, which httpx sends to the proxy itself, on the CONNECT for HTTPS targets. Reading headers back from the proxy’s CONNECT reply is a different matter: httpx hands the script only the target’s response, so that needs an add-on such as python-proxy-headers.

407 is an exception on HTTPS

When the proxy rejects the credentials, what httpx returns depends on the target’s scheme. For an HTTPS site the proxy refuses the CONNECT, no response from the site exists, and httpx raises httpx.ProxyError: 407 Proxy Authentication Required. Only a plain http:// target, which the proxy forwards, comes back as a response with status_code == 407. A status_code check on HTTPS traffic never fires:

try:
    r = client.get("https://httpbingo.org/ip")
except httpx.ProxyError as exc:
    print("proxy refused the tunnel:", exc)  # 407, bad encoding, lapsed plan

Causes of a 407 with known-good credentials, from encoding to a used-up package, are covered in 407 Proxy Authentication Required.

Routing with mounts and environment

Mounts per scheme and host

mounts= maps URL patterns to transports. Patterns can name a scheme (https://), a host (all://api.example.com), a wildcard domain (all://*.example.com) or everything (all://). Most specific match wins, and None sends that pattern direct:

proxied = httpx.HTTPTransport(proxy=PROXY, limits=httpx.Limits(max_connections=50))

mounts = {
    "all://": proxied,
    "all://*.internal.example.com": None,  # your own APIs go direct
}
client = httpx.Client(mounts=mounts)

A mounted transport keeps its own pool settings. Client(limits=...) applies to the client’s default transport and to the one proxy= creates, but a mounted HTTPTransport uses the defaults unless limits is passed to it, as above.

Environment variables and trust_env

With no proxy= and trust_env=True (the default), httpx reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY, plus the system proxy settings on Windows and macOS. Three rules decide which proxy a request uses:

  • An explicit proxy= wins. With an httpx proxy set in code, the client ignores the environment proxies entirely. requests works the other way round, where an environment proxy can overwrite session.proxies, so code ported from requests behaves differently on a CI runner.
  • A custom transport= turns environment proxies off. The client code only reads them when trust_env is on and no transport is given. A script that adds transport=httpx.HTTPTransport(retries=3) behind a corporate proxy stops using that proxy without an error.
  • NO_PROXY only filters environment proxies. Entries become suffix patterns, so example.com also bypasses api.example.com, and a bare * turns every environment proxy off.

trust_env=False on the client ignores all of it, together with .netrc and SSL_CERT_FILE. For a job that must leave through one known exit, set the proxy explicitly and turn the environment off.

SOCKS5 and socks5h in httpx

SOCKS support is an extra: pip install "httpx[socks]" pulls in socksio. Without it, building the client raises ImportError: Using SOCKS proxy, but the 'socksio' package is not installed. Then use the same proxy= argument:

client = httpx.Client(proxy="socks5h://USERNAME:PASSWORD@HOST:PORT")

httpx treats socks5:// and socks5h:// the same way: both send the hostname to the proxy inside the SOCKS CONNECT request, so the proxy resolves the name and no lookup reaches the local resolver. socks5h://, accepted since 0.28.0, is an alias that keeps the URL meaningful for tools such as curl and requests, where plain socks5:// resolves locally. On proxymint’s gateway socks5h:// works and names resolve on the proxy side, as the Lab page above measured. Mechanics and a test are in DNS leak through a proxy. Core httpx does not speak SOCKS4; the third-party httpx-socks package adds it as a transport.

AsyncClient pools and limits

AsyncClient takes the same proxy= and mounts= arguments; mounted transports become httpx.AsyncHTTPTransport. Concurrency is the hard part of an httpx proxy job. A typical one looks like this:

import asyncio
import os
import httpx

PROXY = os.environ["PROXY_URL"]
LIMIT = 20  # concurrent tunnels this job opens

async def fetch(client, sem, url):
    async with sem:
        r = await client.get(url)
        r.raise_for_status()
        return r.text

async def main(urls):
    limits = httpx.Limits(max_connections=LIMIT, max_keepalive_connections=LIMIT)
    timeout = httpx.Timeout(30.0, connect=10.0)
    sem = asyncio.Semaphore(LIMIT)
    async with httpx.AsyncClient(proxy=PROXY, limits=limits, timeout=timeout) as client:
        return await asyncio.gather(*(fetch(client, sem, u) for u in urls), return_exceptions=True)

Connection limits per proxy port

HTTP/1.1 sends one request at a time per connection. Through an HTTP proxy, every HTTPS connection is its own CONNECT tunnel, so 50 requests in flight means 50 tunnels to the proxy port. httpx’s resource limits docs set the defaults: 100 connections, 20 kept alive, and 5 seconds before an idle one closes. An unbounded asyncio.gather over 1,000 URLs therefore opens up to 100 tunnels at once against one port.

Two settings follow from that. Set max_connections to the concurrency the target tolerates and the proxy plan allows, because providers set connection limits per port or per account in different ways. And raise max_keepalive_connections to match it for steady load. With the defaults, 80 of 100 tunnels close after every burst and the next burst pays for new CONNECTs and new TLS handshakes.

HTTP/2 changes the count. With http2=True (and pip install "httpx[http2]") and a target that speaks HTTP/2, httpx can multiplex concurrent requests over one connection, which means one tunnel and one exit for all of them. That suits a sticky job and works against a job that wants a spread of addresses.

PoolTimeout is not a proxy error

httpx.PoolTimeout means a request waited longer than the pool timeout for a free connection in the client’s own pool. It happens before the proxy is involved. Slow exits hold connections longer, the queue behind them grows, and requests at the back give up after 5 seconds. A semaphore, as in the snippet above, fixes it: requests wait in your code, and only LIMIT of them ever reach the pool. Setting pool=None in the timeout works too, but a semaphore also gives the job one obvious number to tune.

Rotating proxies with httpx

An httpx client has no per-request proxy. client.get() and client.send() take no proxy argument, and the transport is chosen when the client is built. Rotation therefore happens either behind one URL or across several clients.

A rotating gateway. One proxy URL, and the provider changes the exit behind it. On proxymint’s rotating residential proxies, rotation is set on the order: a new IP on every request, a timer from 5 to 60 minutes, or sticky for as long as the device stays online, and it can be changed later without new credentials. Your httpx code stays the same. What changes is how the job uses clients: one client per sticky identity, and fresh connections when the gateway should pick again.

An endpoint list. Several fixed proxies, such as a set of datacenter IPv4 addresses, each with its own username and password. Build one client per endpoint and route work across them with itertools.cycle or a queue per client. Cookies and connection pools then stay with their exit.

Keep-alive can pin the exit. A client reuses an open tunnel for the next request to the same host. If a gateway picks the exit when a connection opens, every call on that tunnel leaves from the same address, even on an order set to a new IP per request. After 5 idle seconds the tunnel closes, and the next request opens a new one, so a job that pauses between calls can rotate where a busy one does not. Whether a gateway rotates per HTTP request or per new connection is a property of the provider, and a test settles it.

Verify the exit IP

Run this before a job and on a sample during it. It compares the direct IP with the proxied ones, and one reused client with fresh clients:

import asyncio
import os
import httpx

PROXY = os.environ["PROXY_URL"]
ECHO = "https://httpbingo.org/ip"

async def origin(client):
    return (await client.get(ECHO)).json()["origin"]

async def main():
    async with httpx.AsyncClient(trust_env=False, timeout=15) as direct:
        home = await origin(direct)
    async with httpx.AsyncClient(proxy=PROXY, trust_env=False, timeout=30) as client:
        reused = [await origin(client) for _ in range(5)]
    fresh = []
    for _ in range(5):
        async with httpx.AsyncClient(proxy=PROXY, trust_env=False, timeout=30) as client:
            fresh.append(await origin(client))
    assert home not in reused + fresh, "a request left from the local IP"
    print("reused:", reused)
    print("fresh: ", fresh)

asyncio.run(main())

That assertion catches a silent bypass. If reused repeats one address while fresh changes, rotation follows new connections. If both change, the gateway rotates per request. On a sticky order both lists should show one address.

httpx proxy errors and retries

Most httpx proxy problems announce themselves with a specific exception. Silent ones do the most damage, so the table ends with them:

What you seeCauseFix
TypeError: ... unexpected keyword argument 'proxies'httpx 0.28.0 or later, or httpx2proxy= or mounts=
ValueError: Unknown scheme for proxy URLNo scheme, or one outside http, https, socks5, socks5hWrite the full http:// or socks5h:// URL
ImportError: ... 'socksio' package is not installedSOCKS URL without the extrapip install "httpx[socks]"
httpx.InvalidURL: Invalid port/, # or ? in an unencoded passwordquote(..., safe="") or httpx.Proxy(auth=...)
httpx.ProxyError: 407 Proxy Authentication RequiredRejected credentials on an HTTPS targetCheck the encoding and the plan’s status
httpx.ProxyError: ... handshake operation timed outhttps:// proxy URL on a plain-HTTP proxy portChange the proxy scheme to http://
httpx.ConnectTimeout or ConnectErrorProxy host or port unreachable, or egress blockedTest the port from the same machine
httpx.PoolTimeoutThe client’s own pool ran out of connectionsSemaphore sized to max_connections
httpx.ReadTimeoutSlow exit or target inside the 5 s defaultRaise the read timeout
A 301 response with an https:// LocationPlain http:// URL through a gateway that redirectsUse https:// URLs or follow_redirects=True
No error, wrong exit IPEnvironment proxy ignored, transport= given, or NO_PROXY matchSet proxy= explicitly and check the exit IP

retries= does not cover proxied connections. HTTPTransport(retries=3) retries failed connection attempts, but in the 0.28.1 transport source the value reaches only the direct connection pool, not the HTTP or SOCKS proxy pools. httpx2 2.13.1 has the same code. With a proxy, retries belong in the job:

import asyncio
import random
import httpx

RETRY_STATUS = {429, 500, 502, 503, 504}
RETRY_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadTimeout)

async def get_with_retry(client, url, attempts=4):
    for attempt in range(attempts):
        last = attempt == attempts - 1
        try:
            r = await client.get(url)
            if r.status_code not in RETRY_STATUS or last:
                return r
        except RETRY_ERRORS:
            if last:
                raise
        await asyncio.sleep(2 ** attempt + random.random())

ProxyError is left out on purpose. A 407 does not fix itself on retry, and a 403 means the site refused the request, which a job should respect. On a per-GB plan every retry also downloads the page again, so a 30% retry rate adds 30% to the traffic.

Choosing the proxy type

The httpx proxy code is the same for every category; the target and the job decide which one goes behind it:

  • The job polls APIs or collects from targets without anti-bot scoring, at high concurrency. Datacenter proxies are built for that volume: IPv4 ports billed monthly with no bandwidth cap under normal use, each IP with its own username and password and an HTTP and a SOCKS5 port. Use the endpoint-list model, one AsyncClient per port, and tune max_connections per port.
  • The target scores hosting networks or shows home users different content. Rotating residential proxies serve consumer-origin coverage, with country, region and city chosen on the order and rotation set to every request, a 5-60 minute timer or sticky. Use one gateway URL and decide per job whether connection reuse should pin the exit.
  • One login has to hold for days. Static ISP proxies keep one ISP-registered address for the billing term; pin the job to one client.
  • The platform expects a phone. Mobile proxies on carrier networks cover app-first platforms and mobile ad checks.

Whichever it is, keep three lines in every httpx job: an explicit proxy= with trust_env=False, a semaphore that matches max_connections, and an exit-IP check before the run.

Frequently asked questions

Pass the proxy URL to the client with the proxy argument: httpx.Client(proxy="http://USERNAME:PASSWORD@HOST:PORT"). The same argument works on AsyncClient and on top-level calls such as httpx.get. It routes both HTTP and HTTPS requests, and the URL keeps the http:// scheme for HTTPS sites. For different proxies per scheme or host, use mounts with httpx.HTTPTransport(proxy=...).

The proxies argument was deprecated in httpx 0.26.0 and removed in 0.28.0, released on 2024-11-28, and httpx2 does not have it either. Replace a single proxy URL with proxy=URL. Replace a dict of per-scheme proxies with mounts, where each value is an httpx.HTTPTransport, or an httpx.AsyncHTTPTransport for AsyncClient, built with proxy=URL.

Use http:// for almost every provider. httpx then sends a CONNECT request through the proxy and TLS runs end to end between the script and the site. An https:// proxy URL tells httpx to open TLS to the proxy itself, which fails with a handshake timeout when the proxy port only speaks plain HTTP.

Install the extra with pip install httpx[socks], which adds the socksio package, then pass proxy="socks5h://USERNAME:PASSWORD@HOST:PORT". In httpx both socks5 and socks5h, accepted since 0.28.0, send the hostname to the proxy, so names resolve on the proxy side; socks5h keeps the URL portable to curl and requests, where plain socks5 resolves locally. SOCKS4 needs the third-party httpx-socks package.

Create httpx.AsyncClient(proxy=URL) and keep it open for the whole job, then await client.get calls. Limit concurrency with an asyncio.Semaphore sized to httpx.Limits(max_connections=N), because every concurrent HTTPS request opens its own CONNECT tunnel to the proxy. Raise the timeouts above the 5-second default to allow for the extra hop.

httpx has no per-request proxy argument, so rotation needs either a rotating gateway behind one proxy URL or one client per proxy endpoint. With a gateway, a reused keep-alive connection can keep the same exit, so fresh clients or connections are needed when every request should get a new IP. With a list, routing work across clients keeps cookies and pools separate per exit.

The usual causes are a custom transport argument, which turns environment proxies off, a NO_PROXY entry that matches the host, an SDK that builds its own client, and old code that still passes proxies and fails before sending. Setting proxy explicitly with trust_env=False removes the environment from the picture, and an exit-IP check against an echo endpoint confirms the result.

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