Skip to content
Blog

Rotating Residential Proxies in Python: requests, httpx and aiohttp

Use rotating residential proxies in Python with requests, httpx and aiohttp: proxy URLs, country targeting, timeouts, retries, exit IP checks and error codes.

Exitway team··7 min read

Every mainstream Python HTTP client accepts a proxy URL. For Exitway residential proxies that URL is http://USERNAME:PASSWORD@gw.exitway.net:7777. Without a session parameter, each new TCP connection leaves from a different residential IP. Add -country-us to the username to choose the exit country.

The proxy URL is the easy part. The parts that decide whether a scraper survives a week in production are connection reuse (which quietly turns off rotation), timeouts, and telling a proxy error from a target error. This guide covers all three for requests, httpx (sync and async) and aiohttp.

Keep credentials in environment variables

Your proxy username and proxy password are on the Proxies page of the dashboard. The proxy password is not your account password, and you can regenerate it at any time.

export EXITWAY_USER="USERNAME"   # looks like ex + 10 characters
export EXITWAY_PASS="PASSWORD"   # the proxy password from the dashboard

Proxy passwords contain only letters and digits, so they never need URL-encoding.

Build the proxy URL in one place

Options are appended to the username with dashes. The port selects the product: 7777 is residential and 8888 is datacenter.

Username Behavior
USERNAME Any country, new IP per connection
USERNAME-country-de Germany, new IP per connection
USERNAME-country-de-session-a1b2c3-lifetime-30 Germany, same IP for up to 30 minutes

A small helper keeps this out of the rest of your code:

# exitway.py
import os

HOST = "gw.exitway.net"
RESIDENTIAL, DATACENTER = 7777, 8888


def proxy_url(country=None, session=None, lifetime=None, port=RESIDENTIAL, scheme="http"):
    user = os.environ["EXITWAY_USER"]
    password = os.environ["EXITWAY_PASS"]
    if country:
        user += f"-country-{country.lower()}"
    if session:
        user += f"-session-{session}"
        if lifetime:
            user += f"-lifetime-{lifetime}"
    return f"{scheme}://{user}:{password}@{HOST}:{port}"

The gateway rejects unknown parameters and malformed values with an explicit 400 instead of ignoring them. A misspelled option fails loudly rather than quietly giving you an IP from the wrong place.

requests: check your exit IP first

Before you point a scraper at a real target, confirm what the target will see:

import requests
from exitway import proxy_url

proxy = proxy_url(country="us")
proxies = {"http": proxy, "https": proxy}

r = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=(10, 30))
r.raise_for_status()
info = r.json()
print(info["ip"], info["country"], info.get("org"))

timeout=(10, 30) means 10 seconds to connect and 30 seconds between bytes. Always set both, because a residential exit is someone’s home connection and some of them are slow. Through a proxy, the connect budget also covers opening the tunnel and the TLS handshake with the target. Most exits do that in under a second, a few take 10 seconds or more: retry on a timeout, as the fetch() helper below does, instead of raising the limit indefinitely.

If the proxy refuses the request, requests raises ProxyError, and the gateway’s status code is buried in the message:

requests.exceptions.ProxyError: ... (Caused by ProxyError('Unable to connect to proxy',
OSError('Tunnel connection failed: 402 Payment Required')))

A 402 at least confirms your setup: the URL, credentials and parameters are all valid, and that product simply has no bandwidth left.

Rotation only happens on new connections

Exitway rotates per TCP connection, not per request. HTTP keep-alive reuses the open tunnel, and with it the IP. We checked each client’s default behavior by counting tunnels for three requests to the same host:

Client Default New IP per request
requests.get() New connection each call Already the case
requests.Session() Reuses the tunnel One Session per request
httpx.Client / AsyncClient Reuses the tunnel limits=httpx.Limits(max_keepalive_connections=0)
aiohttp.ClientSession Reuses the tunnel aiohttp.TCPConnector(force_close=True)

Reuse isn’t wrong. It is faster and costs less bandwidth, because you skip a TLS handshake on every request. Just make the choice deliberately. If you need the same IP across several requests, use a sticky session instead of relying on keep-alive (see rotating vs sticky sessions).

Tell proxy errors from target errors

Proxy-side failures come from the gateway, with an X-Exitway-Error header on HTTP responses:

Status X-Exitway-Error Retry?
400 invalid_parameters No, fix the username
402 insufficient_balance No, top up this product
403 account_suspended, destination_blocked No
407 auth_required No, check credentials
429 too_many_connections, rate_limited Yes, slower (Retry-After: 5)
502 network_error, host_unreachable Yes, a rotating retry gets a new IP
503 no_exit_available, network_busy Later (Retry-After: 5), or another country
504 timeout Yes

For https:// URLs the client sees the status in the failed CONNECT. For plain http:// URLs it gets an ordinary response carrying the header.

requests with retries and backoff

This version retries transient failures on a fresh connection, and therefore a fresh IP. It stops immediately on errors that retrying cannot fix:

import random
import re
import time

import requests
from exitway import proxy_url

FATAL = {
    400: "invalid proxy parameters (check the username suffix)",
    402: "no bandwidth left on this product, top up in the dashboard",
    403: "account suspended or destination port blocked",
    407: "wrong proxy username or password",
}
RETRY = {429, 500, 502, 503, 504}
_TUNNEL = re.compile(r"Tunnel connection failed: (\d{3})")


class ProxyFatal(RuntimeError):
    pass


def fetch(url, *, country=None, attempts=4):
    proxy = proxy_url(country=country)
    for attempt in range(1, attempts + 1):
        try:
            r = requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=(10, 30))
        except requests.exceptions.ProxyError as exc:
            # HTTPS: the gateway refused the CONNECT, the status is only in the message
            m = _TUNNEL.search(str(exc))
            status = int(m.group(1)) if m else None
            if status in FATAL:
                raise ProxyFatal(f"{status}: {FATAL[status]}") from None
        except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
            pass  # retry: a new connection gets a new IP
        else:
            # plain HTTP: gateway errors are normal responses tagged with a header
            if r.headers.get("X-Exitway-Error") and r.status_code in FATAL:
                raise ProxyFatal(f"{r.status_code}: {FATAL[r.status_code]}")
            if r.status_code not in RETRY:
                return r
        time.sleep(min(2 ** attempt, 20) + random.random())
    raise RuntimeError(f"{url}: still failing after {attempts} attempts")

ProxyError must be caught before ConnectionError, because it is a subclass of it. The same RETRY set covers 429 and 5xx responses from the target itself.

httpx (sync)

httpx 0.28 takes a single proxy= argument. The older proxies= argument was removed.

import httpx
from exitway import proxy_url

timeout = httpx.Timeout(30.0, connect=10.0)

with httpx.Client(proxy=proxy_url(country="gb"), timeout=timeout) as client:
    try:
        r = client.get("https://ipinfo.io/json")
        r.raise_for_status()
        print(r.json())
    except httpx.ProxyError as exc:
        # str(exc) is the gateway's status line, e.g. "402 Payment Required"
        if str(exc).startswith("402"):
            raise SystemExit("Out of bandwidth on this product, top up and retry.")
        raise

httpx async with bounded concurrency

A semaphore caps the number of requests in flight. With keep-alive disabled, every request opens its own tunnel and gets its own IP:

import asyncio

import httpx
from exitway import proxy_url


async def exit_ip(client, sem):
    async with sem:
        r = await client.get("https://ipinfo.io/json")
        return r.json()["ip"]


async def main(n=5):
    sem = asyncio.Semaphore(10)  # cap in-flight requests
    limits = httpx.Limits(max_keepalive_connections=0)  # no reuse: new connection, new IP
    async with httpx.AsyncClient(
        proxy=proxy_url(country="us"),
        timeout=httpx.Timeout(30.0, connect=10.0),
        limits=limits,
    ) as client:
        ips = await asyncio.gather(*(exit_ip(client, sem) for _ in range(n)))
    print(ips)


try:
    asyncio.run(main())
except httpx.ProxyError as exc:
    raise SystemExit(f"Proxy refused the request: {exc}")

Keep the semaphore modest. Concurrent connections are capped per account, and going over the cap returns 429 too_many_connections.

aiohttp

Put the credentials in the proxy URL. In aiohttp 3.14, proxy_auth= and BasicAuth both emit deprecation warnings.

import asyncio

import aiohttp
from exitway import proxy_url

PROXY = proxy_url(country="de")  # credentials inside the URL


async def main():
    timeout = aiohttp.ClientTimeout(total=45, sock_connect=10)
    connector = aiohttp.TCPConnector(limit=20, force_close=True)  # new IP per request
    async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:
        try:
            async with session.get("https://ipinfo.io/json", proxy=PROXY) as r:
                print(await r.json())
        except aiohttp.ClientHttpProxyError as exc:
            if exc.status == 402:
                raise SystemExit("Out of bandwidth on this product, top up and retry.")
            if exc.status == 407:
                raise SystemExit("Proxy credentials rejected.")
            raise


asyncio.run(main())

ClientHttpProxyError.status holds the gateway’s code, which makes aiohttp the easiest of the three to classify.

SOCKS5 and the HTTPS_PROXY variable

The same port also speaks SOCKS5. With pip install "requests[socks]", use proxy_url(scheme="socks5h"). The h makes DNS resolve at the exit, not on your machine. SOCKS5 has no status line, so a refusal arrives as a bare reply code. Out of bandwidth looks like 0x02: Connection not allowed by ruleset. For scraping, HTTP gives you clearer errors.

To proxy code you can’t edit, set HTTPS_PROXY="http://USERNAME-country-us:PASSWORD@gw.exitway.net:7777". requests and httpx read it by default. aiohttp reads it only with ClientSession(trust_env=True).

Going further

Use residential IPs on public data, at a request rate the site can absorb, and within our Acceptable Use Policy.

Exitway residential proxies start at $0.70/GB with no subscription, and bandwidth never expires. Create an account, or read the docs for every parameter.

More guides