No KYC — no ID, no selfie, no documents. Pay in crypto: BTC, USDT, USDC, ETH, SOL, LTC
Language: English
Get started

Docs · Python 3.9+ · requests · httpx · aiohttp · checked 13 November 2026

How do I use rotating residential proxies in Python?

Retries that respect Retry-After, a new IP per request or one IP per flow, per-host limits in asyncio, and the bytes each page costs.

Last updated: · 7 min read

Quick answer

How do I use rotating residential proxies in Python?

CrawlRelay works in Python with one proxy URL built from gw.crawlrelay.com:7777 and your username and password, given to requests, httpx 0.26+ or aiohttp. Each new connection usually gets a new residential IP; a session ID in the username keeps one IP for up to 30 minutes. Ten gigabytes cost $5.94.

In brief
  • requests: the same http:// proxy URL in the http and https keys, retries through urllib3 Retry.
  • httpx: proxy= since 0.26; the old proxies= argument was removed in 0.28 (November 2024).
  • aiohttp: credentials inside the proxy URL; BasicAuth and proxy_auth are deprecated since 3.14.
  • New IP per request: turn keep-alive off; one IP per flow: session and ttl from 1 to 30 minutes.
  • Cost: $5.94 for 10 GB, $0.50/GB from 50 GB, traffic that never expires.

What does the Python setup look like at a glance?

What does the Python setup look like at a glance?
requestsproxies={"http": url, "https": url}; retries through urllib3 Retry
httpxhttpx.Client(proxy=url); the old proxies= argument was removed in httpx 0.28
aiohttpsession.get(url, proxy="http://USER:PASS@host:port"), credentials in the proxy URL
SOCKS5pip install "requests[socks]" or httpx[socks], then socks5h:// on port 7778
New IP per requestDisable keep-alive: Connection: close, max_keepalive_connections=0 or force_close=True
Same IP for a flow-session-<id>-ttl-<minutes> in the username, up to 30 minutes
Proxy URL schemeAlways http:// for the HTTP port, even for HTTPS websites

How do I use a proxy with requests, with retries that respect Retry-After?

Mount an HTTPAdapter with urllib3 Retry on a Session, and requests retries 429 and 5xx with backoff while honouring Retry-After. The adapter retries connection errors and the statuses you list, waits with exponential backoff, and reads the Retry-After header that sites send with 429 and 503. Set trust_env = False so a leftover HTTPS_PROXY variable cannot override your proxy.

requests + urllib3 Retry
import os

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

USER = os.environ.get("CRAWLRELAY_USER", "USERNAME-country-us")
PASSWORD = os.environ.get("CRAWLRELAY_PASSWORD", "PASSWORD")
PROXY = "http://%s:%[email protected]:7777" % (USER, PASSWORD)

retry = Retry(
    total=4,
    connect=2,
    backoff_factor=1.0,  # waits of 0 s, 2 s, 4 s, 8 s (Retry-After wins on 429/503)
    status_forcelist=(429, 502, 503, 504),
    allowed_methods=frozenset({"GET", "HEAD"}),
    respect_retry_after_header=True,
)

session = requests.Session()
session.trust_env = False  # ignore HTTP(S)_PROXY from the environment
session.mount("http://", HTTPAdapter(max_retries=retry))
session.mount("https://", HTTPAdapter(max_retries=retry))
session.proxies = {"http": PROXY, "https": PROXY}
session.headers["User-Agent"] = "ExampleCrawler/1.0 (+https://example.com/crawler-info)"
session.headers["Connection"] = "close"  # new connection per request, so usually a new exit IP

r = session.get("https://api.ipify.org", timeout=(10, 30))
print(r.status_code, r.text)

How do I build targeted proxy URLs safely?

Build the username in one function that validates every value and URL-encodes the credentials. A typo in a country code or an unencoded character in the password produces a 407 that looks like a credentials problem. The helper below keeps the documented order (USERNAME-country-{cc}-state-{state}-city-{city}-zip-{zip}-asn-{asn}-session-{id}-ttl-{minutes}), refuses unknown keys, checks that ttl stays between 1 and 30 minutes, and encodes both credentials.

Username builder and proxy URL
import re
from urllib.parse import quote

ORDER = ("country", "state", "city", "zip", "asn", "session", "ttl")
VALUE = re.compile(r"^[a-z0-9_]+$")


def build_username(base, **params):
    """build_username("USERNAME", country="us", city="new_york", session="job1", ttl=30)"""
    parts = [base]
    for key in ORDER:
        value = params.pop(key, None)
        if value is None:
            continue
        value = str(value).lower()
        if not VALUE.match(value):
            raise ValueError("bad value for %s: %r" % (key, value))
        if key == "ttl" and not 1 <= int(value) <= 30:
            raise ValueError("ttl must be 1 to 30 minutes")
        parts.append("%s-%s" % (key, value))
    if params:
        raise ValueError("unknown parameters: %s" % ", ".join(sorted(params)))
    return "-".join(parts)


def proxy_url(username, password, socks=False):
    scheme, port = ("socks5h", 7778) if socks else ("http", 7777)
    return "%s://%s:%[email protected]:%d" % (
        scheme, quote(username, safe=""), quote(password, safe=""), port)


print(proxy_url(build_username("USERNAME", country="us", state="ny", city="new_york", session="job1", ttl=20), "p@ss:word"))

How do I get a new IP on every request with httpx?

Turn off keep-alive with max_keepalive_connections=0, so every httpx request opens a new connection and usually a new exit. httpx pools connections by default, and a reused connection keeps its exit IP. num_bytes_downloaded gives the bytes received on the wire, which is what traffic billing is closest to.

httpx: rotating client
import httpx

PROXY = "http://USERNAME-country-gb:[email protected]:7777"

# No keep-alive: every request opens a new connection, so it usually gets a new exit IP
with httpx.Client(
    proxy=PROXY,
    timeout=httpx.Timeout(30.0, connect=10.0),
    limits=httpx.Limits(max_keepalive_connections=0),
    follow_redirects=True,
) as client:
    for _ in range(3):
        r = client.get("https://api.ipify.org")
        print(r.text, r.num_bytes_downloaded, "bytes on the wire")

How do I scrape concurrently with asyncio without hammering one site?

Cap concurrency per host with one semaphore per hostname, not only with a global limit. A global limit of 50 lets all 50 requests hit the same site when your URL list is sorted by domain. A semaphore per hostname keeps each site at a polite level while the crawl as a whole stays fast. Start at 2 to 4 per host and read the concurrency guide before you raise it.

httpx.AsyncClient with a semaphore per host
import asyncio
from collections import defaultdict
from urllib.parse import urlsplit

import httpx

PROXY = "http://USERNAME-country-us:[email protected]:7777"
PER_HOST = 4  # parallel requests per target host
host_slots = defaultdict(lambda: asyncio.Semaphore(PER_HOST))


async def fetch(client, url):
    async with host_slots[urlsplit(url).hostname]:
        try:
            r = await client.get(url)
            return url, r.status_code, r.num_bytes_downloaded
        except httpx.HTTPError as exc:
            return url, type(exc).__name__, 0


async def main(urls):
    limits = httpx.Limits(max_connections=50, max_keepalive_connections=0)
    timeout = httpx.Timeout(30.0, connect=10.0)
    async with httpx.AsyncClient(proxy=PROXY, limits=limits, timeout=timeout) as client:
        for result in await asyncio.gather(*(fetch(client, u) for u in urls)):
            print(*result)


asyncio.run(main(["https://example.com/", "https://example.org/", "https://example.net/"]))

How do I use a proxy with aiohttp?

Pass the gateway as proxy= on each aiohttp request, with the credentials inside the proxy URL. That works on every aiohttp 3.x release without warnings; BasicAuth and the proxy_auth= parameter are deprecated since aiohttp 3.14 and will be removed in 4.0. A TCPConnector(force_close=True) closes every connection after its response, so each request usually gets a new exit. Without it, aiohttp reuses connections and you keep the same IP for a while.

aiohttp with credentials in the proxy URL
import asyncio

import aiohttp

# Credentials go in the proxy URL; percent-encode a password that contains @ or :
PROXY = "http://USERNAME-country-fr:[email protected]:7777"


async def main():
    # force_close=True: one connection per request, so each request usually gets a new exit IP
    connector = aiohttp.TCPConnector(limit=20, force_close=True)
    timeout = aiohttp.ClientTimeout(total=60, sock_connect=10)
    async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
        for _ in range(3):
            async with session.get("https://api.ipify.org", proxy=PROXY) as resp:
                print(resp.status, await resp.text())


asyncio.run(main())

How do I keep one IP for a multi-step flow?

Generate one session ID per flow and put it in the username with a ttl longer than the flow, up to 30 minutes. Keep-alive is fine here: you want the same exit. If the residential device behind the session goes offline, the IP can change before the TTL ends, so make the flow restartable from its last checkpoint.

Sticky session with requests
import uuid

import requests

session_id = uuid.uuid4().hex[:10]  # one ID per flow, lowercase letters and digits
user = "USERNAME-country-us-state-ca-session-%s-ttl-20" % session_id
proxy = "http://%s:[email protected]:7777" % user

with requests.Session() as s:
    s.proxies = {"http": proxy, "https": proxy}
    first = s.get("https://api.ipify.org", timeout=(10, 30)).text
    second = s.get("https://api.ipify.org", timeout=(10, 30)).text
    print(first, second, "same exit" if first == second else "exit changed")

How much traffic does a Python scraper use per page?

Measure 100 real pages before buying volume: HTML-only requests usually cost tens of kilobytes each. Log num_bytes_downloaded in httpx, or the length of the compressed body in your own middleware, and multiply by your page count. The bandwidth guide turns that figure into a cost per 1,000 pages.

According to CrawlRelay's survey of 13 October 2026, the median residential price was $3.50/GB at 10 GB across 14 offers; the CrawlRelay 10 GB plan costs $5.94. The price comparison lists every volume.

Three habits cut traffic without changing your results:

  • Send Accept-Encoding: gzip, br (httpx and requests send gzip by default) so pages travel compressed.
  • Fetch the JSON endpoint that a page loads, when the site documents or allows it, instead of the full HTML.
  • Skip unchanged pages with If-None-Match or If-Modified-Since: a 304 Not Modified costs a few hundred bytes.

Python and proxies: questions

requests, httpx or aiohttp: which should I use with CrawlRelay?

All three work with CrawlRelay through the same proxy URL. Use requests for simple scripts, httpx for one API in sync and async code, and aiohttp for very high concurrency; for scheduling and pipelines, use Scrapy.

Why do I get SSL: WRONG_VERSION_NUMBER with CrawlRelay in Python?

The proxy URL probably starts with https://. CrawlRelay port 7777 speaks plain HTTP and opens a CONNECT tunnel for HTTPS sites, so write http:// in both the http and the https keys.

How do I use CrawlRelay SOCKS5 proxies in Python?

Install the extra with pip install "requests[socks]" or "httpx[socks]", then use socks5h://USERNAME:[email protected]:7778. The h sends hostnames to CrawlRelay, so DNS resolves at the exit.

Why does a CrawlRelay rotating proxy return the same IP twice?

The client reused a kept-alive connection, and CrawlRelay rotates per new connection. Send Connection: close in requests, set max_keepalive_connections=0 in httpx or force_close=True in aiohttp, and check the username has no session part.

Which timeouts suit CrawlRelay residential exits?

About 10 seconds to connect and 30 seconds to read suit HTML pages through CrawlRelay; slow targets and mobile exits need 45 to 60 seconds. requests has no timeout by default, so always set one, and retry a timeout once on a new connection.

Verdict
  • Use httpx for new Python scrapers: one client for sync and async, proxy= since 0.26, and byte counts per response.
  • Keep requests for scripts under a few thousand pages, and move to Scrapy once you need scheduling, deduplication and AutoThrottle.
Sources (3)
  1. httpx changelog: proxy argument added in 0.26.0, proxies removed in 0.28.0 — Encode (read 2026-11-13)
  2. aiohttp changelog: BasicAuth and proxy_auth deprecated in 3.14.0 — aio-libs (read 2026-11-13)
  3. urllib3 Retry reference — urllib3 (read 2026-11-13)

Run your Python scraper through residential IPs

$5.94 for 10 GB, $0.50/GB from 50 GB, paid in crypto with no KYC.

From $0.50/GB · no KYC

Get started