Coronium Mobile Proxies
Developer proxy configuration

aiohttp Proxy Setup: Authentication, Sessions and Timeouts

Build an aiohttp proxy session you can verify, with explicit credentials, bounded connections and useful failure checks.

Coronium Technical TeamSources checked 7 min read
Illustration of queued requests passing through one proxy gateway to destination servers.
Reuse the client inside one session. The request queue, proxy connection and destination response each need their own limit.

The practical answer

  • Pass the proxy to the request and keep proxy credentials separate from the destination Authorization header.
  • Use one session for one account or workflow. A connector pool and a bounded work queue solve different limits.
  • Test the IP response, CONNECT, bad credentials and TLS before adding rotation or retry middleware.

Choose the supported proxy path

For the most straightforward setup, use an HTTP gateway and let aiohttp establish CONNECT when the destination is HTTPS. An http:// gateway URL can therefore carry requests to an https:// website. An HTTPS gateway is a different connection: it adds TLS to the client-to-gateway hop and depends on runtime support.

The current aiohttp proxy documentation describes HTTP forwarding, CONNECT and limitations for HTTPS proxy listeners. The lab below exercises HTTP gateways. For a SOCKS-only endpoint, choose a separate compatible transport or the HTTPX SOCKS configuration; passing a SOCKS URL to an ordinary TCPConnector is not an equivalent setup.

Install the pinned version in a clean environment:

bash
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install 'aiohttp==3.14.5'
python -c 'import aiohttp; print(aiohttp.__version__)'

The pinned package is the version tested below. Run the check in this isolated environment before changing a deployed application's dependencies.

Run an authenticated request and inspect the exit

Replace the three placeholders below with the scheme, host, port and credentials shown for your connection. The gateway URL contains no username or password. These are POSIX-shell commands; use your deployment secret store for a hosted worker.

bash
export PROXY_URL='http://proxy.example:8080'
export PROXY_USER='YOUR_PROXY_USERNAME'
export PROXY_PASSWORD='YOUR_PROXY_PASSWORD'
export TARGET_URL='https://api.ipify.org?format=json'

The default diagnostic destination is ipify, which returns the public address it sees. You can set TARGET_URL to a small endpoint you control instead. A successful transport response alone does not establish a country: use the returned IP in the location checks.

python
"""One diagnostic GET; proxy credentials never become origin Authorization."""
import asyncio
import os
import ipaddress
import json
import ssl
import sys
from urllib.parse import quote, urlsplit, urlunsplit

import aiohttp


async def main():
    endpoint = urlsplit(os.environ["PROXY_URL"])
    if endpoint.scheme not in ("http", "https") or not endpoint.hostname:
        raise ValueError("Use an HTTP or HTTPS proxy endpoint")
    if endpoint.username is not None or endpoint.path not in ("", "/") or endpoint.query or endpoint.fragment:
        raise ValueError("PROXY_URL must contain only the scheme, host and port")
    user = quote(os.environ["PROXY_USER"], safe="")
    password = quote(os.environ["PROXY_PASSWORD"], safe="")
    proxy = urlunsplit((endpoint.scheme, f"{user}:{password}@{endpoint.netloc}", "", "", ""))
    tls = ssl.create_default_context(cafile=os.environ.get("SSL_CERT_FILE"))
    connector = aiohttp.TCPConnector(limit=2, limit_per_host=2, ssl=tls)
    timeout = aiohttp.ClientTimeout(total=30, connect=10, sock_read=20)
    async with aiohttp.ClientSession(
        connector=connector, timeout=timeout, trust_env=False,
        cookie_jar=aiohttp.DummyCookieJar(),
    ) as session:
        async with session.get(
            os.environ.get("TARGET_URL", "https://api.ipify.org?format=json"),
            proxy=proxy, allow_redirects=False,
        ) as response:
            print(f"HTTP {response.status}")
            if response.status >= 300:
                sys.exit(1)
            body = await response.read()
            print(f"Received {len(body)} bytes")
            try:
                address = ipaddress.ip_address(json.loads(body)["ip"])
            except (ValueError, KeyError, TypeError):
                return
            print(f"Observed exit IP: {address}")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as error:
        print(f"Request failed: {type(error).__name__}", file=sys.stderr)
        sys.exit(1)

Save the complete download as aiohttp-proxy.py and run python aiohttp-proxy.py. Expect HTTP 200 and an observed exit IP from the JSON response. A response from a different kind of endpoint can report status and bytes without an IP; inspect that endpoint before interpreting the result.

The gateway URL is assembled from the three separate environment fields. The script percent-encodes the username and password so characters such as @, / and ? do not become URL delimiters. Keep PROXY_URL to scheme, host and port. Copying an already authenticated URL into that field would apply credentials twice, so the example rejects it.

The diagnostic stops on every non-2xx status and does not follow redirects. That makes a 302 visible instead of silently testing another URL. All three downloadable clients now use this same acceptance rule. The certificate context uses SSL_CERT_FILE only when you supply a trusted custom bundle.

Keep the session, queue and account boundaries clear

A bounded batch feeds one reusable aiohttp session and its connection pool.
Limit both the pending work and the open connections. Keep cookie-bearing sessions separate when they represent different accounts.Open full-size diagram

A ClientSession owns a connection pool and, ordinarily, a cookie jar. Reusing it is useful for repeated requests. Sharing it across unrelated accounts can also share state you intended to isolate. The diagnostic uses DummyCookieJar because checking an exit IP needs no cookies; an authenticated workflow may need a real jar scoped to its own account.

The connector reference defines a total connection limit and a per-host limit. Our starting values are both two. They are local test settings, not a supplier's documented capacity or a promise of two simultaneous requests to every host. A queued request can wait for a connection even when the network is healthy.

Inside the existing session, a finite workload can be sent in small batches:

python
async def inspect(url):
    async with session.get(url, proxy=proxy, allow_redirects=False) as response:
        status = response.status
        await response.read()  # Small responses only.
        return status

for offset in range(0, len(urls), 2):
    statuses = await asyncio.gather(*(inspect(url) for url in urls[offset:offset + 2]))
    print(statuses)

This integration sketch assumes the session and authenticated proxy string from the complete example. It creates at most two pending requests per batch. For a continuous stream of jobs, use a bounded queue and fixed consumers. Always read or close responses so pooled connections can be reused.

For a sticky mobile session, finish the account's active work before changing its proxy credential or rotating its exit. Close the old session, create the new one with the appropriate cookie policy, and check the exit again. See mobile IP rotation for the allocation behavior outside aiohttp.

Make proxy environment behavior deliberate

The example passes a proxy for the individual request and uses trust_env=False. aiohttp does not automatically copy HTTPX's environment behavior. According to its environment and proxy documentation, enabling trust_env allows the session to obtain proxy settings from the environment, including bypass rules.

If an operations team owns routing through HTTPS_PROXY and NO_PROXY, test that mode separately with the explicit request proxy removed. A successful direct request to a host in NO_PROXY is expected; it does not prove the proxy was used. Verify the observed exit from the exact container, scheduled worker or AI tool process that will run in production.

Avoid a hybrid configuration whose ownership is unclear. Write down whether the route is selected by an explicit request option, a session default or the deployment environment. That one line often explains why the same source file behaves differently on a laptop and a hosted worker.

Set a deadline and recognize where it expired

The example uses ClientTimeout(total=30, connect=10, sock_read=20). These values serve different purposes. The total timeout covers the request; connect includes waiting to acquire a connection from the pool; sock_read limits the wait between reads. The timeout reference also documents sock_connect for establishing a new socket.

If the job fails only after you increase concurrency, first reduce active work and check for unreleased responses. Raising connect from 10 to 60 seconds may just hide a pool backlog. If the first small request cannot connect, investigate the gateway's DNS, port and authentication before diagnosing the destination's speed.

For downloads or streaming APIs, consume chunks, cap the accepted byte count, and propagate cancellation when the job ends. The diagnostic intentionally reads one small response into memory. It is not a streaming exporter. Add retry behavior only after distinguishing a transient connection failure from credentials, TLS, permissions or a rate limit.

aiohttp failures and the next check
Observed symptomWhat to inspectUseful next action
407 or ClientHttpProxyError on CONNECTProxy authentication or gateway policyMake one HTTPS request using the exact purchased endpoint.
ClientProxyConnectionErrorGateway connectionCheck host, port, scheme and the worker network path.
Certificate verification failureTrusted CA and hostnameFix the certificate chain or correct the endpoint; retain verification.
Timeout only under loadPool wait and response lifecycleReduce task count and consume or close response bodies.
HTTP 302 / 403 / 429Destination responseInspect the response and workflow policy before deciding whether to follow or retry.

Handle the aiohttp 3.14 authentication change

Older examples commonly pass proxy_auth=BasicAuth(...). The 3.14 documentation deprecates proxy_auth and directs new code toward encode_basic_auth with proxy_headers. The URL-encoded credential method used by our complete script is also documented and was exercised by the lab.

For code that chooses the new header API, the relevant request fragment is:

python
proxy_headers = {
    "Proxy-Authorization": aiohttp.encode_basic_auth(username, password)
}
async with session.get(url, proxy=gateway, proxy_headers=proxy_headers) as response:
    await response.read()

This is a source-reviewed migration fragment, not the exact downloadable script. Keep the header in proxy_headers. Placing it in the ordinary headers mapping risks sending it to the destination instead. The lab explicitly checks that the origin receives neither Proxy-Authorization nor the proxy credential in Authorization.

A gateway source allowlist is another mechanism. It checks the worker's public egress, not the proxy exit returned by ipify; the allowlisting guide shows that boundary. Confirm which method your plan supports instead of assuming that both are interchangeable.

For mobile scraping workers, select the country and session policy first. Check available US mobile connections or the product overview, then verify the received endpoint from the actual worker.

Run the same local tests

The scripts were rerun on October 15, 2026 with Python 3.12.14, HTTPX 0.28.1, aiohttp 3.14.5, Node.js 22.23.1 and Undici 8.12.1. The lab runs an authenticated proxy and two origins on loopback. It checks the origin request count, missing proxy credentials at the origin, process exit status and reported output.

There are seven checks for each of the three clients, plus two checks for native Node environment routing. Download the lab ZIP, follow its README, and compare the recorded JSON results. The IP 203.0.113.42 is a documentation address returned by the fixture; it is not a Coronium exit or a measured location.

These are transport tests. They do not measure carrier speed, geographic coverage or success against a particular website. For a purchased port, repeat the single-request example from the machine running your job, then test the authorized destination and session lifetime you need.

Checks you can repeat with the downloadable lab
CheckObserved resultWhat it verifies
Authenticated HTTP and HTTPS CONNECTEach reaches the local origin onceProxy transport works with credentials containing reserved characters.
JSON IP responseThe script prints 203.0.113.42The diagnostic reads the returned IP, rather than guessing from the gateway.
Wrong proxy passwordNonzero exit; origin never reachedAuthentication failure cannot silently fall back to a direct request.
Untrusted TLS certificateNonzero exit; origin never reachedCertificate verification stays enabled.
HTTP 302 redirect302 reported; redirect not followed; nonzero exitThe first response remains visible for diagnosis.
HTTP 429 rate limitOne origin request; nonzero exitThe sample does not immediately retry or rotate.

Sources and review scope

Sources reviewed October 15, 2026. This guide reviews primary documentation. Code examples illustrate configuration and error handling. Any local fixture checks are described in the article; they are not live-provider performance benchmarks or guarantees of destination access.

Frequently asked questions

Configure another runtime

Use the settings supported by the process making the request, then verify routing and authentication.

Related workflows

Mobile proxies for web scraping

Match an authorized collector to its network and session requirements.

US mobile proxy options

Compare available carrier plans when your integration needs a US mobile exit.

Python Requests authentication

Use a synchronous client when the worker does not need asyncio.

Proxy location mismatch

Check country and city results after confirming the transport route.

Where to get a dedicated line

A Coronium mobile proxy is one physical device with its own SIM, rented to one customer. It connects over HTTP or SOCKS5, the IP changes by dashboard button, API link or timer, and data is not metered on dedicated lines. Brazil lines are the exception: 20 GB of data a month and a new IP on request only, with no timer. Stock and prices differ by country and carrier.