How to Build an Async Proxy Checker in Python (aiohttp)

Published:

10 minute read

Acar Diveroli
Written by: Acar Diveroli
A CSV table with proxy, status, latency and exit IP columns in a tall window; exit IP column in blue, dashed list behind

A proxy checker is a program that tests whether the proxies in a list work. It sends a single request through each proxy and records the result, the latency and the exit IP. If the list is long, the check should run concurrently, not one by one. In a sequential check, every dead proxy holds the queue until its timeout runs out. This post builds a small checker with asyncio and aiohttp that runs concurrently and writes the results to CSV.

What the tool does

The tool sends a single request through each proxy to an IP echo endpoint. The echo endpoint returns the IP the request came from as JSON. That IP is the exit address the target site will see. If the request succeeds, the proxy works, and the returned address tells you where the proxy actually exits.

The tool writes one CSV row per proxy:

ColumnContent
proxyhost:port, without the password
statusworking, timeout, auth error, proxy unreachable
latency_msTotal request time in milliseconds
exit_ipThe IP the echo endpoint saw
countryOptional, two-letter country code

This tool is for addresses you bought, for example an ISP Proxy list. Free lists floating around the internet are not worth checking. Nobody knows who runs those nodes. They can read your traffic, inject code into pages or harvest your credentials. We covered the risks in detail in Are Free Proxies and Web Proxy Sites Safe?.

Concurrency limit and timeout

The total time is roughly the number of proxies divided by the concurrency limit, times the longest request. Dead proxies always take the full timeout. On a list with many dead addresses, the timeout is what really sets the total.

asyncio.Semaphore(20) lets at most 20 checks run at once. The other tasks wait in line and start when a slot frees up. Without a limit, a list of a thousand proxies opens a thousand connections at once. That runs into your machine's file descriptor limit and your provider's concurrent connection quota.

The timeout is set with aiohttp.ClientTimeout(total=10). total covers the whole request, from connection setup to reading the response. In our test we checked 20 slow proxies with a 2-second timeout:

ConcurrencyTotal time
58.6 s
202.6 s

With a limit of 5, the list finished in four waves. With a limit of 20, one wave was enough. Pick a timeout a few times longer than your working proxies need. Anything beyond that is wasted waiting.

Start measuring latency inside the semaphore. If the clock starts before the semaphore, the time spent in line is added to the latency and the proxies at the end look slower than they are.

Full code

The script below reads the list from a text file, runs the checks and writes the result to a CSV. Put one proxy URL per line:

text
http://user:pass@pr.proxynet.io:8000
http://user:pass@203.0.113.10:8000

If your list uses the host:port:user:pass format, convert it to this format first. The proxy URL starts with http:// even when the target is HTTPS, because aiohttp opens a CONNECT tunnel through the proxy for HTTPS.

python
import argparse
import asyncio
import csv
import time
from urllib.parse import urlsplit

import aiohttp

# Endpoint that returns the exit IP as JSON
ECHO_URL = "https://api.ipify.org?format=json"
# Endpoint that returns ip and country fields, used when country is requested
COUNTRY_URL = "https://ipinfo.io/json"


def mask(proxy_url: str) -> str:
    # Keep passwords out of the CSV: only host:port remains
    u = urlsplit(proxy_url)
    return f"{u.hostname}:{u.port}"


async def check(session, limit, proxy_url, target):
    row = {"proxy": mask(proxy_url), "status": "", "latency_ms": "",
           "exit_ip": "", "country": ""}
    async with limit:  # at most N checks at once
        start = time.perf_counter()
        try:
            async with session.get(target, proxy=proxy_url) as resp:
                if resp.status == 407:
                    row["status"] = "auth error"
                    return row
                if resp.status != 200:
                    row["status"] = f"http {resp.status}"
                    return row
                data = await resp.json(content_type=None)
            row["latency_ms"] = round((time.perf_counter() - start) * 1000)
            row["exit_ip"] = data.get("ip", "")
            row["country"] = data.get("country", "")
            row["status"] = "working"
        except aiohttp.ClientHttpProxyError as e:
            # With an HTTPS target, 407 arrives as an exception during CONNECT
            row["status"] = "auth error" if e.status == 407 else f"proxy {e.status}"
        except aiohttp.ClientProxyConnectionError:
            row["status"] = "proxy unreachable"
        except asyncio.TimeoutError:
            row["status"] = "timeout"
        except aiohttp.ClientError as e:
            row["status"] = f"error: {type(e).__name__}"
    return row


async def main():
    ap = argparse.ArgumentParser(description="Checks a proxy list concurrently")
    ap.add_argument("list", help="one proxy per line: http://user:pass@host:port")
    ap.add_argument("--output", default="results.csv")
    ap.add_argument("--concurrency", type=int, default=20)
    ap.add_argument("--timeout", type=float, default=10.0)
    ap.add_argument("--country", action="store_true", help="also fetch the country")
    ap.add_argument("--target", help="set the echo endpoint manually")
    a = ap.parse_args()

    with open(a.list, encoding="utf-8") as f:
        proxies = [s.strip() for s in f if s.strip() and not s.startswith("#")]
    if not proxies:
        raise SystemExit("List is empty: no proxies to check")
    target = a.target or (COUNTRY_URL if a.country else ECHO_URL)

    limit = asyncio.Semaphore(a.concurrency)
    timeout = aiohttp.ClientTimeout(total=a.timeout)
    connector = aiohttp.TCPConnector(limit=a.concurrency)
    async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:
        tasks = [check(session, limit, p, target) for p in proxies]
        results = await asyncio.gather(*tasks)  # order matches the input

    with open(a.output, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=results[0].keys())
        writer.writeheader()
        writer.writerows(results)

    working = sum(r["status"] == "working" for r in results)
    print(f"{working}/{len(results)} proxies working, results: {a.output}")


if __name__ == "__main__":
    asyncio.run(main())

All you need to run it is pip install aiohttp:

bash
python proxy_checker.py proxies.txt --concurrency 20 --timeout 10 --country

Here is the output of our local test. The addresses and country codes come from our test setup:

text
proxy,status,latency_ms,exit_ip,country
127.0.0.1:18081,working,11,127.0.0.2,TR
127.0.0.1:18082,proxy unreachable,,,
127.0.0.1:18083,timeout,,,
127.0.0.1:18084,auth error,,,
127.0.0.1:18084,working,10,127.0.0.3,DE

asyncio.gather returns results in input order. The row order in the CSV matches your list. TCPConnector(limit=...) sets the connection pool to the same number as the semaphore. aiohttp's default pool limit is 100, and it quietly becomes a bottleneck when you ask for higher concurrency.

Authenticated addresses

The username and password go inside the proxy URL, as http://user:pass@host:port. aiohttp turns them into a Proxy-Authorization header. If the password contains @, # or :, it needs URL encoding. We showed this trap with examples in How to Use a Proxy With aiohttp.

A wrong password returns 407 Proxy Authentication Required, but it reaches your code by two different paths. If the target is http://, the 407 arrives as an ordinary response status. If the target is https://, the proxy rejects the CONNECT request and aiohttp raises ClientHttpProxyError. We saw both paths in our test. That is why the code checks for 407 in both places.

Do not write the password to the CSV. The results file often gets shared by email or in a chat channel. The mask function keeps only the host:port part of the address.

Exit IP and country

The exit IP is the address the echo endpoint sees, not the address you connect to. The two may differ. Proxies behind a gateway have different exits behind a single entry address. If you are checking a static IP you bought, the exit_ip column should match the address you were given.

The default echo endpoint, api.ipify.org, returns only an ip field. The --country flag switches the target to ipinfo.io/json. In our test this endpoint worked without a token and returned the two-letter code in the country field. The service's current docs describe the token-based endpoints. For regular use, get a token or use your own geolocation database.

The country code is a database estimate. Geolocation databases can disagree, and an IP's record can be updated late. If the country column does not match the location your provider states, check it in another database first.

latency_ms is not a ping value. It measures the proxy connection, the tunnel, the TLS handshake and the response together. Use it to compare proxies with each other, not as a measure of network latency itself.

The same check with httpx

In httpx, the proxy is set on the client, not per request. You need a separate httpx.AsyncClient for each proxy. The rest of the logic stays the same:

python
import time

import httpx


async def check_httpx(limit, proxy_url, target, timeout=10.0):
    async with limit:
        # In httpx the proxy is set per client: open a separate client for each proxy
        async with httpx.AsyncClient(proxy=proxy_url, timeout=timeout) as client:
            start = time.perf_counter()  # keep client setup out of the timing
            try:
                resp = await client.get(target)
            except httpx.TimeoutException:
                return "timeout", None, None
            except httpx.ProxyError as e:
                return f"proxy error: {e}", None, None
            except httpx.HTTPError as e:
                return f"error: {type(e).__name__}", None, None
            ms = round((time.perf_counter() - start) * 1000)
    if resp.status_code != 200:
        return f"http {resp.status_code}", None, None
    return "working", ms, resp.json().get("ip")

Start the timer after the client is open. Client setup prepares a TLS context every time. In our first attempt that setup ended up in the measurement, and a working proxy looked several times slower than it was. On a closed port, httpx raised ConnectError, not ProxyError. That case falls into the httpx.HTTPError branch.

Troubleshooting

The status column tells you where the problem is:

StatusMeaningWhat to do
proxy unreachablePort closed or wrong addressCheck host and port
auth errorThe proxy rejected the passwordCheck the password and its URL encoding
timeoutNo response in timeRaise the timeout and try once more
http 403 / 429The echo endpoint rejected the requestLower the concurrency

If every row times out, the problem is most likely your network, not the proxies. Try a single proxy with curl -x first. If only a few working proxies time out, recheck them on their own with a longer timeout.

How we tested

We ran the tests on December 1, 2026, on Windows 11 with Python 3.13.17, aiohttp 3.13.3 and httpx 0.28.1. Locally we set up HTTP proxies written with asyncio on four ports and an IP echo endpoint. The proxies required Basic authentication. Two worked, one held every request for 15 seconds, and one port had no server at all. The wrong-password attempt was a separate row. The working proxies forwarded requests from different loopback addresses (127.0.0.2, 127.0.0.3). The echo endpoint assigned fake country codes to those addresses.

To test the HTTPS path, we opened a CONNECT tunnel from the same working proxy to api.ipify.org and ipinfo.io/json. The status of all five rows came out right on both paths. A connection to a closed port was refused after about 2 seconds on Windows. We checked a list containing the same proxy 200 times in under 1 second at concurrency 50.

The bottom line

Cap concurrency with a semaphore, keep the timeout short and measure latency inside the semaphore. Above all, do not write passwords to the results file. The same tool checks a Datacenter Proxy list without any changes.

Sources

Frequently asked questions

How many proxies should I check at once?

Start with 20 and raise it based on the results. Two things set the ceiling: how many connections your machine can open at once and your provider's concurrent connection quota. Go past it and you will see timeouts and connection errors even when the proxies are fine. The echo service may also return 429 when it sees too many requests. If the results are consistent, raise the limit step by step.

Can I use threads instead of asyncio?

Yes. You can run the same check with concurrent.futures.ThreadPoolExecutor and Requests. The difference is scale. Each thread holds memory and operating system resources, while asyncio handles thousands of pending requests on a single thread. For a few hundred proxies, both approaches are fine. As the list grows, asyncio does the same job with fewer resources.

Is the latency column the same as ping?

No. Ping measures only the round trip across the network. latency_ms measures the proxy connection, the CONNECT tunnel, the TLS handshake with the target and the response together. That is why it is always higher than the ping value. Use it to compare proxies against the same target, not as an absolute network measure.

Why does the country differ from what my provider says?

Geolocation databases draw on different sources. When an IP block has just moved, some databases keep showing the old country. The country an echo service returns is that service's own estimate. If you see a mismatch, check the IP in a second database too. You cannot know which database the target site uses.

Can I check SOCKS5 proxies too?

Yes, but you need an extra package. aiohttp speaks only HTTP to proxies. For SOCKS5, use the ProxyConnector class from the aiohttp-socks package, with one connector per proxy. In httpx, installing httpx[socks] and passing a socks5:// URL is enough. The status, latency and CSV parts stay the same. The tests in this post used HTTP proxies only.

Is this tool suitable for ongoing monitoring?

No, it is built for one-off checks. It scans the list once and writes a snapshot of that moment to CSV. Ongoing monitoring needs results stored over time, a count of consecutive failures and alerts. Still, you can run this script as a scheduled task and write each output to a dated file to keep a simple history.

Ask ChatGPTAsk Claude