---
title: "How to Health-Check a Proxy Pool in Python: Code Example"
description: "Track errors, timeouts, 403/429 responses and latency per proxy endpoint, and rest the ones that cross a threshold. State machine and tested Python code."
url: https://proxynet.io/blog/proxy-pool-health-check-python
date: 2026-12-01
author: "Acar Diveroli"
category: "Web Scraping, Tutorial"
lang: en
---

# How to Health-Check a Proxy Pool in Python: Code Example

A health check in a proxy pool tracks the errors and latency of each endpoint and temporarily takes degraded ones out of selection. Endpoints rarely die all at once. They slow down first, then fail now and then. Code that picks at random from a list does not see this decline and keeps sending work to a bad endpoint. This post explains the health signals, how to choose thresholds and a Python class that applies them.

> **Note: Short answer**
>
> Keep counters for consecutive errors, timeouts, 403/429 responses and latency on every proxy endpoint. When a threshold is crossed, take the endpoint out of rotation for a while, then bring it back with a single probe request.

## Five health signals

Five signals show that an endpoint is degrading, and each points to a different source. The code folds them into two counters. The error counter measures the proxy side. The block counter measures how the target site reacts to that IP.

| Signal | What it tells you | Counter |
|---|---|---|
| Connection error | The proxy is down or the network path is broken | Error |
| Timeout | The proxy or the target is not responding | Error |
| 502 / 504 | The proxy could not reach the target | Error |
| Repeated 403 / 429 | The site is refusing this IP or asking you to slow down | Block |
| Rising latency | The endpoint is loaded or the route got longer | Error |

The counters only count consecutive events. A single successful response resets both. A healthy endpoint that fails once in a while is not punished.

A single 403 is often specific to one page. Repeated 403s from the same IP point to the IP's reputation or a wrong country setting. A separate counter lets you see that difference.

Measure latency with a moving average, not a single request. On every response the code takes 70 percent of the average from the old value and 30 percent from the new measurement. One slow response barely moves the average. Sustained slowness crosses the threshold.

## Healthy, suspect, cooling down

The state machine keeps each endpoint in one of three states and picks endpoints accordingly. The transitions:

- **Healthy → suspect.** The first error or the first block. The endpoint stays in rotation, but it is picked a third as often as a healthy one.
- **Suspect → healthy.** One successful response. All counters reset.
- **Suspect → cooling down.** The error or block counter hits its limit (default 3), or the response carries a `Retry-After` header. The endpoint is not picked until the rest period ends.
- **Cooling down → probe.** When the period ends, the endpoint comes back as suspect. If the first request succeeds, it returns to healthy. If it fails, it goes straight back to cooldown and the period doubles.

Doubling makes a permanent failure cheap. The default 60-second rest grows to 120, 240 and 480 seconds and stops at 900. A completely dead endpoint costs four probe requests an hour, no more.

## The full code

The file below runs on its own: the standard library plus `requests` is enough. There is no scraping logic. The class only picks endpoints, records results and manages the rest period.

```python
"""Health tracking for a proxy pool: healthy -> suspect -> cooldown -> probe."""
import logging
import random
import threading
import time
from dataclasses import dataclass
from urllib.parse import urlsplit

import requests

log = logging.getLogger("proxy_health")

HEALTHY, SUSPECT, COOLDOWN = "healthy", "suspect", "cooldown"
BLOCK_CODES = {403, 429}        # the site is refusing this IP
GATEWAY_CODES = {502, 504}      # the proxy could not reach the target

@dataclass
class Endpoint:
    url: str
    state: str = HEALTHY
    errors: int = 0             # consecutive errors, timeouts or slow responses
    blocks: int = 0             # consecutive 403 / 429
    latency: float = 0.0        # moving average of response time (s)
    rest_until: float = 0.0     # when the cooldown ends (monotonic)
    rests: int = 0              # how many cooldowns in a row

    @property
    def name(self):
        # Only host:port, so no password ends up in the logs
        parts = urlsplit(self.url)
        return f"{parts.hostname}:{parts.port}"

def retry_after_seconds(response):
    value = response.headers.get("Retry-After", "")
    return float(value) if value.isdigit() else None

class ProxyPool:
    def __init__(self, urls, error_limit=3, block_limit=3, slow_after=3.0,
                 cooldown=60.0, max_cooldown=900.0):
        self.endpoints = [Endpoint(u) for u in urls]
        self.error_limit = error_limit
        self.block_limit = block_limit
        self.slow_after = slow_after
        self.cooldown = cooldown
        self.max_cooldown = max_cooldown
        self.lock = threading.Lock()

    def _set(self, ep, state):
        if ep.state != state:
            log.info("%s: %s -> %s", ep.name, ep.state, state)
            ep.state = state

    def _rest(self, ep, retry_after=None):
        # Each consecutive cooldown doubles the period, capped at max_cooldown
        seconds = min(self.cooldown * 2 ** ep.rests, self.max_cooldown)
        if retry_after:
            seconds = max(seconds, retry_after)
        ep.rest_until = time.monotonic() + seconds
        ep.rests += 1
        ep.latency = 0.0        # measure the probe request cleanly
        self._set(ep, COOLDOWN)

    def pick(self):
        now = time.monotonic()
        with self.lock:
            ready = []
            for ep in self.endpoints:
                if ep.state == COOLDOWN and now >= ep.rest_until:
                    self._set(ep, SUSPECT)      # time is up: one probe allowed
                if ep.state != COOLDOWN:
                    ready.append(ep)
            if not ready:
                return None
            # A healthy endpoint is picked three times as often as a suspect one
            weights = [3 if ep.state == HEALTHY else 1 for ep in ready]
            return random.choices(ready, weights)[0]

    def report(self, ep, status=None, elapsed=None, retry_after=None):
        with self.lock:
            if ep.state == COOLDOWN:
                return                          # late result that arrived after the cooldown began
            if elapsed is not None:
                ep.latency = elapsed if ep.latency == 0 else 0.7 * ep.latency + 0.3 * elapsed
            slow = ep.latency > self.slow_after
            if status is None or status in GATEWAY_CODES or slow:
                ep.errors += 1
            elif status in BLOCK_CODES:
                ep.blocks += 1
            else:
                ep.errors = ep.blocks = ep.rests = 0
                self._set(ep, HEALTHY)
                return
            if (ep.state == SUSPECT and ep.rests > 0) or retry_after \
                    or ep.errors >= self.error_limit or ep.blocks >= self.block_limit:
                self._rest(ep, retry_after)     # probe failed or threshold crossed
            else:
                self._set(ep, SUSPECT)

    def get(self, url, tries=3, timeout=(3.05, 10), **kwargs):
        last_error = None
        for _ in range(tries):
            ep = self.pick()
            if ep is None:
                raise RuntimeError("No endpoint left in the pool outside cooldown")
            start = time.monotonic()
            try:
                r = requests.get(url, proxies={"http": ep.url, "https": ep.url},
                                 timeout=timeout, **kwargs)
            except (requests.ConnectionError, requests.Timeout) as exc:
                if "407" in str(exc):           # auth error inside the HTTPS tunnel
                    raise
                self.report(ep)                 # status=None: error
                last_error = exc
                continue
            if r.status_code == 407:            # credential error, not the pool's fault
                raise requests.HTTPError(f"407 via {ep.name}: username/password", response=r)
            self.report(ep, r.status_code, time.monotonic() - start,
                        retry_after_seconds(r))
            if r.status_code in GATEWAY_CODES:
                last_error = requests.HTTPError(f"{r.status_code} via {ep.name}")
                continue                        # proxy failure: try another endpoint
            return r                            # 403/429 included: your call
        raise last_error

    def snapshot(self):
        with self.lock:
            return [(ep.name, ep.state, ep.errors, ep.blocks, round(ep.latency, 2))
                    for ep in self.endpoints]

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
    pool = ProxyPool([
        # Your static IP endpoints (the addresses are examples)
        "http://user:pass@203.0.113.10:8000",
        "http://user:pass@203.0.113.11:8000",
        "http://user:pass@203.0.113.12:8000",
    ])
    for _ in range(10):
        try:
            r = pool.get("https://httpbin.org/ip")
            print(r.status_code, r.text.strip())
        except Exception as exc:
            print("error:", exc)
        time.sleep(1)
    print(pool.snapshot())
```

Four methods carry the decisions. `pick()` skips endpoints in cooldown and brings back expired ones as suspect. `report()` updates the counters and makes the transition. `get()` tries another endpoint only on proxy-side errors. `snapshot()` returns a password-free state table for logging.

Pass the proxy address with `proxies=` on every request. A value set through `Session.proxies` can be overridden by environment variables, so the Requests docs recommend passing it per request. The basics of proxy settings in Requests are in [How to Use a Proxy With Python Requests](/blog/python-requests-proxy).

The lock (`threading.Lock`) keeps the counters consistent across threads. You can share one pool object with every job in a `ThreadPoolExecutor`.

If you use HTTPX, two places change. The request becomes `httpx.get(url, proxy=ep.url, timeout=httpx.Timeout(10, connect=3.05))`, and the caught error becomes `httpx.TransportError`. The state machine stays the same.

## No retries on 403 and 429

The code does not retry a 403 or a 429 through another endpoint. It returns the response to you. A 429 is the site asking you to slow down. Sending the same request straight away from another IP is an attempt to get around that limit.

The class's job is to protect the endpoint. If `Retry-After` arrives in seconds, it rests the endpoint for at least that long. It also rests it after three blocks in a row. Lowering the request rate is your code's job: follow robots.txt rules, and use the official API if the site offers one. We covered the causes of 429 and how to wait properly in [429 Too Many Requests](/blog/http-429-too-many-requests).

`Retry-After` can also arrive as a date. The code only reads the seconds form. If a date arrives, the default rest period applies.

## Choosing thresholds

Choose thresholds from measurements of your own traffic, not from guesses. First log the `snapshot()` output for a few hours and look at the average latency of healthy endpoints.

| Setting | Default | When to change it |
|---|---|---|
| `error_limit` | 3 | Raise it on a noisy network |
| `block_limit` | 3 | Lower it when blocks are costly for the job |
| `slow_after` | 3.0 s | Set it to 2-3 times normal latency |
| `cooldown` | 60 s | Shorten it for short jobs |
| `max_cooldown` | 900 s | Lengthen it for long-running jobs |
| `timeout` | (3.05, 10) | Match the read time to the target's response time |

The 3.05 in the connect timeout is not random. The Requests docs suggest setting connect timeouts slightly larger than a multiple of 3, the default TCP packet retransmission window.

This setup is most useful with a fixed list of IPs. Every IP you get with [ISP Proxy](https://proxynet.io/static-isp-residential-proxy) is a separate endpoint in the list and carries its own counters.

## Health in a rotating residential pool

In a rotating residential pool, health checks do not happen at IP level, because you only have one endpoint. Every request goes to a single gateway such as `pr.proxynet.io:8000`, and the exit IP changes on every request. Resting a bad IP is pointless: the next request already leaves from another IP.

So the unit you monitor changes:

- **Session level.** In a sticky session, the session ID stays bound to one IP for 1-60 minutes. If a session keeps failing, do not rest it. Drop it and start over with a new session ID.
- **Country level.** If you use country targeting, keep counters per country. If errors rise in one country but not in the others, rest that country for a short while.
- **Gateway level.** If you cannot connect to the gateway at all, the problem is not the pool. It is your network or your credentials.

If you set up a separate proxy address for each country or session setting, the class works unchanged. Each address in the list stands for one country or session. How the pool behind the gateway is managed is covered in [What Is a Proxy Pool](/blog/what-is-a-proxy-pool).

In the rotating model, IP selection and weeding out bad IPs happen on the provider side. Your job is to watch error rates at session and country level. The product's scope is on the [Rotating Proxy](https://proxynet.io/rotating-proxy) page.

## Debugging

The symptoms usually tell you where the problem is:

- **If every endpoint goes into cooldown at once**, the problem is most likely not the proxies but the target or your own network. Try the target with a single request without a proxy.
- **If you see `RuntimeError: No endpoint left in the pool outside cooldown`**, the whole pool is resting. Stop the loop and wait until the nearest `rest_until` moment.
- **If you get 407**, the credentials are wrong. The code does not retry this error and raises it at once, because another endpoint would not change the result.
- **If an endpoint flips between suspect and healthy**, the threshold is right and the endpoint is unstable. The weighting already picks it less often.
- **On Windows, a closed port** may not be refused right away. In our test it showed up as a connect timeout. The code counts both errors in the same counter.

## How we tested

We tested on 1 December 2026 on Windows 11 with Python 3.13.17, requests 2.34.2 and httpx 0.28.1. The setup was five local fake proxies written with `http.server` and a target serving plain HTTP. The proxies required `user:pass` credentials. One was healthy, one delayed every response by 1.5 seconds, and one had nothing listening on its port. One returned 429 with `Retry-After: 3`, and the last returned 502 for the first 6 seconds, then recovered.

For the test we shortened the thresholds: `slow_after=1.0`, `cooldown=2`, `max_cooldown=8`. The results:

- In a 25-second sequential loop we made 61 calls. 58 returned 200 and 3 returned 429. No connection error reached the caller.
- The dead endpoint went into cooldown on the third error, the slow one on the third slow response. The dead endpoint's rest period grew to 2, 4 and 8 seconds.
- The endpoint returning 429 went into cooldown on its first response.
- The 502 endpoint went into cooldown and returned to healthy on the first probe after it recovered.
- With eight threads, in our first version the slow endpoint's error counter climbed to 7-10 with a limit of 3. Requests still in flight when the cooldown began reported later and restarted the cooldown. After we added the line `if ep.state == COOLDOWN: return`, the counter stayed at 3.
- With a wrong password, 407 was raised at once both on the plain HTTP target and inside the HTTPS tunnel, and the endpoint stayed healthy.

On the HTTPX side we only verified the request and error types against the same fake proxies. We ran the full class with Requests.

## The bottom line

Count consecutive events, double the rest period, and slow down instead of retrying 403/429. Above all, if you run in parallel, ignore late results from an endpoint in cooldown. Otherwise a single bad endpoint keeps extending its own rest period.

## Sources

- [RFC 9110, HTTP Semantics, §10.2.3 Retry-After: rfc-editor.org](https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3)
- [RFC 6585, §4 429 Too Many Requests: rfc-editor.org](https://www.rfc-editor.org/rfc/rfc6585#section-4)
- [Requests documentation, Advanced Usage, Timeouts: requests.readthedocs.io](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts)
- [Python documentation, random.choices: docs.python.org](https://docs.python.org/3/library/random.html#random.choices)

## Frequently asked questions

### Do I need a separate test request for proxy health checks?

No. The results of real requests are the most reliable health signal and create no extra traffic. A separate check request only makes sense if you want to bring a resting endpoint back before work arrives. In that case, use your own check URL and do not send check requests to the target site.

### How long should the cooldown be?

Starting at sixty seconds and doubling on every failed probe is enough for most jobs. Choose the cap by how often you want a dead endpoint to be retried. A 900-second cap means four probes an hour. If `Retry-After` arrived, the period should be at least that value.

### Should I retry right away through another proxy when I get a 429?

No. A 429 is the site asking you to slow down, and switching IPs ignores that request. Rest the endpoint, lower your request rate and follow the `Retry-After` header if there is one. If the site offers an official API, use it for regular data needs.

### Does this code work with asyncio?

Not as it is, because `requests` is synchronous. The state machine stays the same, though. You write `get()` as an async method with `httpx.AsyncClient` and use `asyncio.Lock` instead of `threading.Lock`. `pick()` and `report()` contain no waiting, so the logic needs no other change. We did not test the async version for this post.

### How do I set the latency threshold?

By measuring. Run the pool with normal traffic for a few hours and log the latency averages from the `snapshot()` output. Set `slow_after` to two or three times the typical value of healthy endpoints. Too low, and healthy endpoints go into cooldown. Too high, and slowdowns go unnoticed.

### Can I use this class with rotating residential proxies?

Partly. On a single gateway the IP changes with every request, so resting an IP does nothing. You can use the class with addresses set up per country or session setting. Each address stands for one country or sticky session, and the counters live at that level. Opening a new session ID is more practical than resting a bad session.
