[{"data":1,"prerenderedAt":36},["ShallowReactive",2],{"blog:post:en:lightweight-proxy-health-checks-python-stdlib":3,"blog:related:en:lightweight-proxy-health-checks-python-stdlib":23},{"slug":4,"lang":5,"title":6,"summary":7,"date":8,"tags":9,"tag_slugs":15,"thumbnail_url":16,"translations":17,"body":18,"asset_base":19,"checksum":20,"published_at":21,"content_updated_at":22},"lightweight-proxy-health-checks-python-stdlib","en","Lightweight Proxy Health Checks with Python Stdlib","Build a dependency‑free Python script that tests proxy connectivity, measures latency, and verifies IP rotation using only the standard library.","2026-11-16",[10,11,12,13,14],"proxy","python","testing","troubleshooting","networking",[10,11,12,13,14],"https://blog-api.ro-proxy.com/api/blog/posts/lightweight-proxy-health-checks-python-stdlib/thumbnail.svg?lang=en",[5],"## Why Lightweight Health Checks Matter\n\nRotating proxies are only useful if they actually work. A proxy that returns 5xx errors, times out, or leaks the wrong exit IP can break scrapers, cause failed API calls, and waste budget. Heavy monitoring stacks (Prometheus, Grafana, custom agents) add operational overhead and are overkill for many teams. A small, self‑contained health check that runs on the same machines as your scrapers gives you immediate feedback with zero extra infrastructure.\n\n## Design Goals\n\n- **Zero external dependencies** – only Python’s standard library.\n- **Fast execution** – each check should finish in under a second for healthy proxies.\n- **Clear signals** – distinguish between connection failure, high latency, and unexpected exit IP.\n- **Rotation awareness** – detect whether a sticky proxy has kept its IP or a timed proxy has rotated as expected.\n- **Easy scheduling** – run from cron, systemd timers, or a simple loop.\n\n## Prerequisites\n\n- Python 3.8 or newer (for `time.perf_counter` and `http.client`).\n- Network access to the proxy gateway and to `https://api.ipify.org`.\n- Proxy credentials: gateway host, HTTP port, username, password. If you are using RoProxy, set the gateway host, port, username, and password as provided.\n\n## Building the Checker\n\n### 1. Proxy Configuration\n\nStore the connection details in constants so the script stays readable.\n\n```python\nGATEWAY_HOST = \"GATEWAY_HOST\"\nHTTP_PORT = 8080  # replace with actual port\nUSERNAME = \"USERNAME\"\nPASSWORD = \"PASSWORD\"\nPROXY_URL = f\"http://{USERNAME}:{PASSWORD}@{GATEWAY_HOST}:{HTTP_PORT}\"\n```\n\n### 2. Core Function: `test_proxy`\n\nThe function opens a connection through the proxy, sends a HEAD request to a reliable endpoint, measures round‑trip time, and returns a structured result.\n\n```python\nimport http.client\nimport socket\nimport time\nimport json\nfrom urllib.parse import urlparse\n\ndef test_proxy(proxy_url: str, target_url: str = \"https://api.ipify.org?format=json\", timeout: float = 5.0) -> dict:\n    \"\"\"Return a dict with keys: ok, latency_ms, exit_ip, error.\"\"\"\n    parsed = urlparse(proxy_url)\n    proxy_host = parsed.hostname\n    proxy_port = parsed.port or 80\n    proxy_user = parsed.username\n    proxy_pass = parsed.password\n\n    # Build the CONNECT tunnel for HTTPS target\n    conn = http.client.HTTPConnection(proxy_host, proxy_port, timeout=timeout)\n    conn.set_tunnel(target_url.split(\"://\")[1].split(\"/\")[0], headers={\n        \"Proxy-Authorization\": \"Basic \" + \n        __import__(\"base64\").b64encode(f\"{proxy_user}:{proxy_pass}\".encode()).decode()\n    })\n\n    start = time.perf_counter()\n    try:\n        conn.request(\"HEAD\", target_url)\n        resp = conn.getresponse()\n        latency_ms = (time.perf_counter() - start) * 1000\n        # Read body to get exit IP (ipify returns JSON)\n        body = resp.read().decode()\n        data = json.loads(body)\n        exit_ip = data.get(\"ip\")\n        ok = 200 \u003C= resp.status \u003C 300\n        return {\"ok\": ok, \"latency_ms\": round(latency_ms, 2), \"exit_ip\": exit_ip, \"error\": None}\n    except (socket.timeout, ConnectionRefusedError, http.client.HTTPException, json.JSONDecodeError) as e:\n        latency_ms = (time.perf_counter() - start) * 1000\n        return {\"ok\": False, \"latency_ms\": round(latency_ms, 2), \"exit_ip\": None, \"error\": str(e)}\n    finally:\n        conn.close()\n```\n\n**Why HEAD?** It avoids downloading a full response body, keeping the check fast while still exercising the TLS handshake and proxy authentication.\n\n### 3. Measuring Latency\n\n`time.perf_counter()` provides sub‑millisecond resolution. The returned `latency_ms` lets you set alerts (e.g., > 800 ms) without needing a separate metrics system.\n\n### 4. Verifying Exit IP\n\nThe script calls `https://api.ipify.org?format=json`, which returns `{\"ip\": \"\u003Cexit‑ip>\"}`. Comparing this value across runs tells you whether the proxy rotated.\n\n### 5. Handling Rotation Modes\n\n- **Sticky proxies** keep the same IP until a manual rotate or failure. Expect the same `exit_ip` on consecutive checks.\n- **Timed proxies** change IP after a configured interval. If you know the interval, you can assert that `exit_ip` differs after that period.\n\nThe checker itself does not enforce rotation logic; it merely reports the observed IP. Your orchestration layer decides when to call the rotation API.\n\n### 6. Putting It Together: a Runnable Script\n\n```python\n#!/usr/bin/env python3\n\"\"\"Lightweight proxy health check – run once or in a loop.\"\"\"\nimport argparse\nimport sys\nimport time\n\nfrom test_proxy import test_proxy  # assume the function above lives in test_proxy.py\n\ndef main() -> int:\n    parser = argparse.ArgumentParser(description=\"Check a rotating proxy\")\n    parser.add_argument(\"--proxy\", default=PROXY_URL, help=\"Proxy URL with credentials\")\n    parser.add_argument(\"--interval\", type=int, default=0, help=\"Seconds between checks (0 = single run)\")\n    parser.add_argument(\"--latency-threshold\", type=float, default=800.0, help=\"Max acceptable latency in ms\")\n    args = parser.parse_args()\n\n    last_ip = None\n    while True:\n        result = test_proxy(args.proxy)\n        timestamp = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n        if result[\"ok\"]:\n            status = \"OK\"\n            if result[\"latency_ms\"] > args.latency_threshold:\n                status = \"HIGH_LATENCY\"\n            ip_msg = f\"IP={result['exit_ip']}\"\n            if last_ip and result[\"exit_ip\"] != last_ip:\n                ip_msg += f\" (changed from {last_ip})\"\n            last_ip = result[\"exit_ip\"]\n            print(f\"{timestamp} {status} latency={result['latency_ms']}ms {ip_msg}\")\n        else:\n            print(f\"{timestamp} FAIL error={result['error']}\")\n\n        if args.interval \u003C= 0:\n            break\n        time.sleep(args.interval)\n    return 0\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n```\n\nSave as `check_proxy.py` and make it executable (`chmod +x check_proxy.py`). Run a single check:\n\n```bash\n./check_proxy.py --proxy http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT\n```\n\nOr run continuously every 60 seconds:\n\n```bash\n./check_proxy.py --interval 60 --latency-threshold 800\n```\n\n## Running the Check Periodically\n\n- **cron**: `* * * * * /path/check_proxy.py --proxy $PROXY_URL >> /var/log/proxy_health.log 2>&1` (runs every minute).\n- **systemd timer**: create a service and timer unit for more control over logging and restart policy.\n- **Embedded loop**: the script’s `--interval` flag is handy for container sidecars.\n\nChoose the method that matches your deployment model. The script writes one line per check, making it trivial to tail, grep, or feed into a log aggregator.\n\n## Interpreting Results\n\n| Output | Meaning |\n|--------|---------|\n| `OK latency=120ms IP=203.0.113.45` | Proxy healthy, low latency, IP as expected. |\n| `HIGH_LATENCY latency=950ms IP=203.0.113.45` | Proxy works but latency exceeds threshold – consider rotating or switching. |\n| `FAIL error=timed out` | Connection failed – proxy may be down, credentials wrong, or network issue. |\n| `OK latency=130ms IP=198.51.100.12 (changed from 203.0.113.45)` | IP rotated – expected for timed proxies; for sticky proxies this signals an unplanned rotation. |\n\nSet alerts on `FAIL` and `HIGH_LATENCY`. Track IP changes to verify that your rotation strategy (manual API call or timed interval) behaves as designed.\n\n## Extending the Checker\n\n- **Structured logging** – output JSON lines for ingestion by Loki, Elasticsearch, or Splunk.\n- **Alerting** – pipe `FAIL` lines to a webhook (Slack, PagerDuty) with a small wrapper script.\n- **Multiple proxies** – iterate over a list of `PROXY_URL`s and run checks in parallel with `concurrent.futures.ThreadPoolExecutor`.\n- **TLS verification** – add `ssl.create_default_context()` to enforce certificate validation if your proxy terminates TLS.\n- **Metrics export** – push latency and success counters to a Prometheus Pushgateway for dashboarding without a full Prometheus server.\n\nAll extensions stay optional; the core script remains a single file with no third‑party packages.\n\n## Conclusion\n\nA tiny, standard‑library health check gives you immediate visibility into proxy reliability, latency, and rotation behavior. It runs anywhere Python runs, needs no extra services, and integrates cleanly with existing scheduling tools.\n","https://blog-api.ro-proxy.com/api/blog/posts/lightweight-proxy-health-checks-python-stdlib/assets","3898ffc11f698cbd8e6eb124a048fd462c6dcffdf471de23b6bf39825c794176","2026-11-16T01:21:16.102714Z","2026-11-16T01:21:16.104314Z",[24,28,32],{"slug":25,"title":26,"summary":27},"debugging-proxy-tls-failures","Debugging Proxy TLS Failures: SNI, ALPN, and Certificates","Learn to separate TCP, TLS, certificate, SNI, and ALPN failures, then fix proxy trust and handshake configuration with curl, Python, and browser checks.",{"slug":29,"title":30,"summary":31},"diagnose-http-502-forward-proxy","How to Diagnose HTTP 502 Errors Behind a Forward Proxy","Trace the CONNECT tunnel, TLS handshake, and HTTP response to separate proxy-generated 502s from origin failures, then isolate, retry, and escalate the real cause.",{"slug":33,"title":34,"summary":35},"configure-proxy-bypass-lists-local-internal-traffic","How to Configure Proxy Bypass Lists for Local and Internal Traffic","Learn why routing local and internal traffic through a proxy breaks your setup, and how to configure NO_PROXY, PAC files, and app-level exceptions to keep your network safe and fast.",1794816128054]