# How to Use a Proxy Rotator: Python Code, Rotating Endpoints and APIs

How a proxy rotator works and how to use one: a Python rotator with requests and asyncio, rotating endpoints, a rotator API, and auto-replacing banned IPs.

- Author: [Brandon Perry](https://fineproxy.org/brandon-perry/)
- Published: 2026-11-29T21:00:00.000Z
- Updated: 2026-11-29T21:00:00.000Z
- Canonical: https://fineproxy.org/articles/proxy-rotator/

A proxy rotator sends each request, or each session, through a different proxy IP, so no single address makes enough requests to get rate-limited or banned. You can run the rotation yourself over a list of proxies, or hand it to the provider's rotating endpoint. For long jobs, a third option combines the two: your code rotates, and the provider's API replaces the IPs that keep failing.

| Way | How it works | When to use it |
| --- | --- | --- |
| Your own list | Your code or a local tool picks the next proxy for each request | You have a list of static proxies and want full control |
| Rotating endpoint | One gateway address; the provider picks a new IP per request or per session | You want rotation without writing it, and a large pool |
| List plus API | Your code rotates, and the provider's API replaces IPs with too many errors | Long-running jobs where dead or banned IPs pile up |

We ran every example below on November 29, 2026, on Linux with Python 3.11. The proxies were 100 FineProxy datacenter IPs and a rotating plan. The code is in one folder: `rotator.py` and `async_httpx.py` work with any provider's proxies, while `fineproxy_api.py`, `self_healing.py` and `rotating_endpoint.py` call the FineProxy API.

## What is a proxy rotator?

A proxy rotator is the part of your setup that decides which proxy serves which request. It can be ten lines of Python, a local proxy server like mubeng, a middleware in a scraping framework or a gateway run by the provider.

Sites limit how many requests one IP can make. Past the limit, you get a 429 (Too Many Requests), a 403, a CAPTCHA or an empty page. A rotator spreads the requests over many IPs, so each one stays under the limit. It also handles the failures: when an IP times out or gets blocked, the request goes out again through another one.

## Rotation strategies: per request, sticky and on error

The first decision is when the IP should change:

![Three proxy rotation strategies: a new IP per request, the same IP for a sticky session, and a switch only after an error](/wp-content/uploads/2026/11/proxy-rotation-strategies.webp)

- **Per request.** Every request gets the next IP. This fits pages that don't depend on cookies: search results, product pages, public profiles.
- **Sticky session.** One IP serves a whole session, then the next session gets a new one. This fits logins, carts and pagination, where a sudden IP change looks like an account takeover.
- **On error.** Keep the current IP until it fails, then switch. This saves clean IPs when the site is tolerant and the pool is small.

The code in this article rotates per request and rests failing IPs. For sticky sessions, the simplest route is the provider's sticky port, shown in the [rotating endpoint section](#rotating-endpoint-let-the-provider-rotate).

The order of IPs matters less than people think. Round-robin goes through the list in order and spreads the load evenly. Random choice is just as even over many requests and makes the pattern harder to spot. Weighted choice sends more requests to faster or more reliable IPs, but you need statistics per IP to set the weights.

The other choice is where the IPs come from. A list of static datacenter IPs is cheaper per request and keeps the same addresses every day, which matters if the target whitelists your IPs or you log in to accounts. A rotating gateway gives you a much larger pool without managing it, which matters when the site bans quickly.

## Python proxy rotator, step by step

Install the libraries and put your proxies in `proxies.txt` next to the scripts, one URL per line:

```bash
pip install requests==2.34.2 httpx==0.29.0
```

```text
http://USER:PASS@203.0.113.10:8080
http://USER:PASS@203.0.113.11:8080
socks5://USER:PASS@203.0.113.12:1080
```

If your provider gives you `IP:PORT:USER:PASS` lines, convert them: `awk -F: '{print "http://"$3":"$4"@"$1":"$2}' list.txt > proxies.txt`. A password with `@`, `:` or `#` must be URL-encoded, or the URL splits in the wrong place. SOCKS proxies in requests need `pip install 'requests[socks]'`. With FineProxy, `fineproxy_api.py` from the [API section](#replace-failing-ips-through-the-api) writes this file for you.

### Step 1: Round-robin with requests

The simplest rotator cycles through the list:

```python
import itertools
import os

import requests


def load_proxies(path):
    with open(path) as f:
        return [line.strip() for line in f if line.strip() and not line.startswith("#")]


proxies = load_proxies(os.environ.get("PROXY_FILE", "proxies.txt"))
pool = itertools.cycle(proxies)


def fetch(url):
    proxy = next(pool)
    # A new request without a shared Session opens a new connection,
    # so every call really goes out through the proxy picked for it.
    return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=15)


if __name__ == "__main__":
    for _ in range(min(5, len(proxies))):
        try:
            print(fetch("https://api.ipify.org").text)
        except requests.RequestException as exc:
            print("failed:", type(exc).__name__)
```

Saved as `01_round_robin.py` and run with `python 01_round_robin.py`, it printed five different IPs. To use it in your own scraper, replace `requests.get(url)` with `fetch(url)`.

A common complaint is "my rotation doesn't work, I always get the same IP", and the usual cause is a shared `requests.Session` with a rotating gateway. Sent one by one through one gateway address, the session's requests go through the same open tunnel, so the exit IP doesn't change. With a list of static proxies, a session is fine: requests keeps a separate connection pool per proxy URL, so the IP still changes, and reusing connections is faster. The catch is that `session.proxies` can be overridden by the `HTTP_PROXY` and `HTTPS_PROXY` environment variables, while `proxies=` passed to each call can't.

### Step 2: Handle timeouts, 403 and 429 with backoff

Round-robin breaks on the first dead proxy: the request fails, and the dead proxy comes up again a few requests later. A usable rotator retries the request on another proxy, takes a failing proxy out of rotation for a while (we call it the bench), and waits a little longer after each failure (exponential backoff). This is `rotator.py`, the version the rest of the article builds on:

```python
import os
import random
import sys
import threading
import time
from collections import defaultdict
from dataclasses import dataclass, field
from email.utils import parsedate_to_datetime

import requests

BAN_STATUSES = {403, 429}             # the site refused this IP: bench it
SERVER_STATUSES = {500, 502, 503, 504}  # the site itself failed: retry elsewhere, don't blame the IP
PROXY_ERRORS = (
    requests.ConnectionError,
    requests.Timeout,
    requests.exceptions.ChunkedEncodingError,
    requests.exceptions.ContentDecodingError,
)
MAX_WAIT = 600  # cap for Retry-After and for waiting on a fully benched pool


class ProxyAuthError(requests.RequestException):
    """407: the proxy rejected the login. Another IP with the same password won't help."""


def retry_after_seconds(value, default):
    value = (value or "").strip()
    if value.isdigit():
        return min(int(value), MAX_WAIT)
    try:
        return min(max(0.0, parsedate_to_datetime(value).timestamp() - time.time()), MAX_WAIT)
    except (TypeError, ValueError):
        return default


@dataclass
class ProxyStats:
    ok: int = 0
    failed: int = 0
    benched_until: float = 0.0
    errors: dict = field(default_factory=lambda: defaultdict(int))

    @property
    def total(self):
        return self.ok + self.failed

    @property
    def error_rate(self):
        return self.failed / self.total if self.total else 0.0


class ProxyRotator:
    def __init__(self, proxies, cooldown=60, max_retries=4, timeout=(5, 15), verbose=False):
        self.proxies = list(proxies)
        if not self.proxies:
            raise ValueError("the proxy list is empty")
        self.stats = {p: ProxyStats() for p in self.proxies}
        self.cooldown = cooldown
        self.max_retries = max_retries
        self.timeout = timeout  # (connect, read) seconds
        self.verbose = verbose
        self._next = 0
        self._lock = threading.Lock()
        self.total_ok = 0
        self.total_failed = 0

    def replace_proxies(self, proxies):
        """Swap in a new list and keep the stats of proxies that stayed."""
        with self._lock:
            self.proxies = list(proxies)
            self.stats = {p: self.stats.get(p, ProxyStats()) for p in self.proxies}

    def pick(self):
        while True:
            with self._lock:
                now = time.monotonic()
                for _ in range(len(self.proxies)):
                    proxy = self.proxies[self._next % len(self.proxies)]
                    self._next += 1
                    if self.stats[proxy].benched_until <= now:
                        return proxy
                wait = min(s.benched_until for s in self.stats.values()) - now
            # Every proxy is on the bench: wait for the first one, with jitter so threads don't wake together.
            time.sleep(min(MAX_WAIT, max(0.0, wait)) + random.uniform(0, 0.5))

    def _bench(self, proxy, seconds, reason):
        with self._lock:
            stats = self.stats[proxy]
            stats.failed += 1
            stats.errors[reason] += 1
            stats.benched_until = time.monotonic() + seconds
            self.total_failed += 1
        if self.verbose:
            print(f"  benched {proxy.rsplit('@', 1)[-1]} for {seconds:.0f}s: {reason}")

    def get(self, url, **kwargs):
        kwargs.pop("proxies", None)
        timeout = kwargs.pop("timeout", self.timeout)
        last_error = None
        for attempt in range(self.max_retries + 1):
            proxy = self.pick()
            try:
                response = requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=timeout, **kwargs)
            except PROXY_ERRORS as exc:
                # For https:// targets a 407 arrives as a failed CONNECT, not as a status code.
                if "407" in str(exc):
                    raise ProxyAuthError(f"proxy login rejected by {proxy.rsplit('@', 1)[-1]}") from exc
                last_error = exc
                self._bench(proxy, self.cooldown, type(exc).__name__)
            else:
                status = response.status_code
                if status == 407:
                    raise ProxyAuthError(f"proxy login rejected by {proxy.rsplit('@', 1)[-1]}")
                if status not in BAN_STATUSES | SERVER_STATUSES:
                    with self._lock:
                        self.stats[proxy].ok += 1
                        self.total_ok += 1
                    return response
                last_error = requests.HTTPError(f"HTTP {status}", response=response)
                response.close()
                if status in BAN_STATUSES:
                    wait = retry_after_seconds(response.headers.get("Retry-After"), self.cooldown)
                    self._bench(proxy, wait, str(status))
                elif self.verbose:
                    print(f"  retry after HTTP {status} from the site")
            # Exponential backoff with jitter before the next proxy: 0.5 s, 1 s, 2 s, 4 s...
            time.sleep(min(30, 0.5 * 2**attempt) * random.uniform(0.5, 1.5))
        raise last_error

    def report(self):
        for proxy, s in sorted(self.stats.items(), key=lambda kv: -kv[1].error_rate):
            host = proxy.rsplit("@", 1)[-1]
            print(f"{host:24} ok={s.ok:<3} failed={s.failed:<3} rate={s.error_rate:.0%} {dict(s.errors)}")


def load_proxies(path):
    with open(path) as f:
        return [line.strip() for line in f if line.strip() and not line.startswith("#")]


if __name__ == "__main__":
    url = sys.argv[1] if len(sys.argv) > 1 else "https://api.ipify.org"
    count = int(sys.argv[2]) if len(sys.argv) > 2 else 20
    rotator = ProxyRotator(load_proxies(os.environ.get("PROXY_FILE", "proxies.txt")), max_retries=3, verbose=True)
    for i in range(count):
        try:
            r = rotator.get(url)
            print(i, r.status_code, r.text[:60])
        except requests.RequestException as exc:
            print(i, "gave up:", exc)
    rotator.report()
```

In your scraper, create one `ProxyRotator` and call `rotator.get(url)` where you used to call `requests.get(url)`. The class is meant for GET requests: retrying a POST through another proxy can submit a form or an order twice. What the code does with each kind of failure:

- **403 and 429 bench the proxy instead of deleting it.** A 429 usually means "slow down on this IP", not "this IP is dead". The 429 status is defined in RFC 6585, and servers may add a `Retry-After` header, which RFC 9110 allows as a number of seconds or as a date. The code reads both forms and caps the wait at 10 minutes.
- **500–504 are retried on another proxy without counting against the IP.** A failing site shouldn't make healthy proxies look bad, especially when those statistics decide which IPs to replace.
- **407 stops everything.** It means the proxy rejected the login. Another IP with the same password won't help, so the rotator raises `ProxyAuthError` instead of trying the whole list. For `https://` targets, requests doesn't return a 407 status at all: the tunnel fails with a `ConnectionError` that mentions 407, and the code checks for that.
- **Timeouts are split.** Five seconds to connect, fifteen to read. A dead proxy is detected in five seconds instead of fifteen.
- **Threads can share one rotator.** The lock protects the list position and the statistics, and the backoff and the wait on a fully benched pool have random jitter, so parallel workers don't retry in lockstep.

We ran it with five working proxies and one address that never answers (`192.0.2.10`, from a range reserved for documentation):

![Output of rotator.py: the unreachable proxy is benched after one failure, and all 12 requests succeed through the other five](/wp-content/uploads/2026/11/proxy-rotator-python-run.webp)

The sixth request hit the dead address, failed with `ProxyError`, and went out again through the next proxy; the "benched" line shows the moment. The dead address stayed on the bench, and all 12 requests succeeded. On the full list of 100 IPs, 250 requests in a row all succeeded in 2 minutes 15 seconds, through 100 different IPs. That's one request at a time with a fresh connection each, so it measures reliability, not throughput, and none of the requests hit a 403 or 429.

### Step 3: Async rotation with httpx

For hundreds of requests, sequential code is slow. httpx sets the proxy per client, not per request. The old `proxies=` argument was removed in httpx 0.28, which still breaks code copied from older tutorials with "unexpected keyword argument 'proxies'". So the async rotator, saved as `async_httpx.py`, keeps one client per proxy and picks a client for each request:

```python
import asyncio
import itertools
import os
import sys
from collections import Counter

import httpx


def load_proxies(path):
    with open(path) as f:
        return [line.strip() for line in f if line.strip() and not line.startswith("#")]


RETRY_STATUSES = {403, 429, 500, 502, 503, 504}


class AsyncRotator:
    def __init__(self, proxies, concurrency=10, timeout=15):
        if not proxies:
            raise ValueError("the proxy list is empty")
        self.clients = [httpx.AsyncClient(proxy=p, timeout=timeout) for p in proxies]
        self.cycle = itertools.cycle(range(len(self.clients)))
        self.limit = asyncio.Semaphore(concurrency)

    async def get(self, url, retries=3):
        last_error = None
        for attempt in range(retries + 1):
            client = self.clients[next(self.cycle)]
            async with self.limit:
                try:
                    response = await client.get(url)
                except httpx.ProxyError as exc:
                    if "407" in str(exc):
                        raise  # wrong proxy login: every IP will reject it
                    last_error = exc
                except httpx.TransportError as exc:
                    last_error = exc
                else:
                    if response.status_code == 407:
                        raise httpx.HTTPStatusError("HTTP 407", request=response.request, response=response)
                    if response.status_code not in RETRY_STATUSES:
                        return response
                    last_error = httpx.HTTPStatusError(
                        f"HTTP {response.status_code}", request=response.request, response=response
                    )
                    await response.aclose()
            await asyncio.sleep(0.5 * 2**attempt)
        raise last_error

    async def close(self):
        await asyncio.gather(*(c.aclose() for c in self.clients))


async def main(count):
    rotator = AsyncRotator(load_proxies(os.environ.get("PROXY_FILE", "proxies.txt")))
    try:
        results = await asyncio.gather(
            *(rotator.get("https://api.ipify.org") for _ in range(count)), return_exceptions=True
        )
    finally:
        await rotator.close()
    ips = Counter(r.text for r in results if isinstance(r, httpx.Response))
    failed = sum(1 for r in results if isinstance(r, Exception))
    print(f"{count} requests, {len(ips)} different IPs, {failed} failed after retries")


if __name__ == "__main__":
    asyncio.run(main(int(sys.argv[1]) if len(sys.argv) > 1 else 50))
```

With 100 proxies and 10 requests in flight, `python async_httpx.py 100` finished in 12.8 seconds: 100 requests, 100 different IPs, none failed. Each client keeps its own connection pool, which is fine for a hundred proxies; for thousands, open clients on demand or switch to aiohttp. aiohttp takes `proxy=` per request, so you don't need a client per proxy. Since aiohttp 3.14, its `proxy_auth` and `BasicAuth` parameters are deprecated, so put the credentials in the proxy URL.

### Step 4: Rotation in Scrapy

Scrapy has its own proxy support: `HttpProxyMiddleware` reads the proxy from `request.meta["proxy"]`, takes the credentials from the URL and sends them in a `Proxy-Authorization` header. A rotating middleware only has to set that key, and it must run before `HttpProxyMiddleware` (priority 750). Save this as `scrapy_rotation/middlewares.py`:

```python
import itertools


class RotatingProxyMiddleware:
    def __init__(self, proxies):
        self.cycle = itertools.cycle(proxies)

    @classmethod
    def from_crawler(cls, crawler):
        with open(crawler.settings.get("PROXY_FILE", "proxies.txt")) as f:
            proxies = [line.strip() for line in f if line.strip() and not line.startswith("#")]
        return cls(proxies)

    def process_request(self, request, spider=None):
        # New requests and retries get the next proxy; redirects keep the one they had.
        retries = request.meta.get("retry_times", 0)
        if "proxy" not in request.meta or request.meta.get("proxy_retry") != retries:
            request.meta["proxy"] = next(self.cycle)
            request.meta["proxy_retry"] = retries
```

The spider next to it, `ip_spider.py`, turns the middleware on and requests an IP echo page ten times:

```python
import os

import scrapy


class IpSpider(scrapy.Spider):
    name = "ip"
    custom_settings = {
        "PROXY_FILE": os.environ.get("PROXY_FILE", "proxies.txt"),
        "DOWNLOADER_MIDDLEWARES": {"middlewares.RotatingProxyMiddleware": 610},
        "RETRY_HTTP_CODES": [403, 429, 500, 502, 503, 504],
        "RETRY_TIMES": 3,
        "DOWNLOAD_TIMEOUT": 15,
    }

    async def start(self):  # Scrapy 2.13+; older versions call start_requests()
        for i in range(10):
            yield scrapy.Request("https://api.ipify.org?format=json", dont_filter=True, cb_kwargs={"n": i})

    def parse(self, response, n):
        yield {"n": n, "ip": response.json()["ip"]}
```

With Scrapy 2.20.0, `cd scrapy_rotation && PYTHONPATH=. PROXY_FILE=../proxies.txt scrapy runspider ip_spider.py -O ips.json` returned 10 different IPs. `dont_filter=True` matters in this test: without it, Scrapy drops the nine identical URLs as duplicates. 407 isn't in `RETRY_HTTP_CODES` on purpose, for the same reason as in step 2. Scrapy retries POST requests too, so for forms set `dont_retry` in the request's meta. The `scrapy-rotating-proxies` package you'll find in older guides hasn't had a release since 2019, so a small middleware of your own is the safer choice.

For browsers, the proxy is set when the browser or context starts, so you rotate by opening a new context with the next proxy. The setup is in our [Playwright proxy guide](/articles/playwright-proxy/).

## Rotating endpoint: let the provider rotate

If you don't want to manage a list at all, use a rotating endpoint, the most common kind of proxy rotator API. You connect to one gateway address, and the provider picks the exit IP from its pool. With FineProxy rotating plans, the gateway has two kinds of ports: rotating ports give a new IP for every connection, and sticky ports keep the same IP for a session. The hosts and ports depend on the plan, so `rotating_endpoint.py` reads them from the API:

```python
import requests

from fineproxy_api import FineProxyAPI

api = FineProxyAPI()
config = api.proxy_config()
auth = api.proxy_auth()
login = api.login_part(auth)
rotating = f"http://{login}@{config['endpoint']}:{config['port']}"
sticky = f"http://{login}@{auth['rotating_gateway']['sticky_hosts'][0]}:{config['sticky_http']}"


def ip_via(proxy):
    # No shared Session: a kept-alive tunnel to the gateway would keep the same exit IP.
    return requests.get("https://api.ipify.org", proxies={"http": proxy, "https": proxy}, timeout=20).text


print("rotating:", [ip_via(rotating) for _ in range(5)])
print("sticky:  ", [ip_via(sticky) for _ in range(5)])
```

Five requests through the rotating port came from five different IPs. Five requests through the sticky port all came from the same IP. A sticky session keeps its IP for 900 seconds (15 minutes) by default; you can change that through the API, down to 30 seconds.

A rotating plan is priced by requests rather than by IPs, and every new connection through the rotating port counts, retries included. The plan we used includes 2.5 million requests a month for $35. That's about one request per second around the clock; our async test ran at almost eight per second and would use the month's quota in about four days. A list of 100 static datacenter IPs costs $12 a month in Germany or the Netherlands and has no request cap: at one request every ten seconds per IP, that's about 26 million requests a month. The gateway wins when the site bans IPs faster than a list of 100 can absorb. The static list wins on price as long as each IP stays under the site's limit.

## Replace failing IPs through the API

A rotator works around dead IPs, but it doesn't fix them. After a few days of scraping, a list of 100 IPs can have several that only time out, and every one of them costs a retry. The fix is to connect your rotator to the provider's API: when an IP fails too often, ask the provider to replace it and reload the list.

With the FineProxy API, a replacement goes through refresh-status (is the next one free?), a quote for the exact IPs, and the refresh call itself. A small client, saved as `fineproxy_api.py`, handles those calls and also exports the proxy list for the other examples:

```python
import os
import time
import uuid
from urllib.parse import quote

import requests

API = "https://fineproxy.org/account_new/api/v1"


class FineProxyAPI:
    def __init__(self, api_key=None, service_id=None):
        self.service_id = service_id or os.environ["FINEPROXY_SERVICE_ID"]
        self.session = requests.Session()
        self.session.trust_env = False  # never send the API key through a proxy from HTTPS_PROXY
        if os.environ.get("FINEPROXY_API_PROXY"):  # only if your network needs a proxy to reach the API
            self.session.proxies["https"] = os.environ["FINEPROXY_API_PROXY"]
        self.session.headers["Authorization"] = f"Bearer {api_key or os.environ['FINEPROXY_API_KEY']}"

    def _url(self, path):
        return f"{API}/customer/services/{self.service_id}{path}"

    def _get(self, path, **params):
        r = self.session.get(self._url(path), params=params, timeout=30)
        r.raise_for_status()
        return r.json()

    def _post(self, path, body):
        r = self.session.post(self._url(path), json=body, timeout=60)
        r.raise_for_status()
        return r.json()

    def ips(self):
        return [item["ip"] for item in self._get("/proxy/ips")["ips"]]

    def ip_countries(self):
        return {item["ip"]: item["country"] for item in self._get("/proxy/ips")["ips"]}

    def proxy_auth(self):
        """Login, password and endpoints. The response contains the proxy password in plain text."""
        return self._get("/proxy/auth", reveal="true")

    def proxy_config(self):
        return self._get("/proxy/config")

    @staticmethod
    def login_part(auth):
        return f"{quote(auth['username'], safe='')}:{quote(auth['password'], safe='')}"

    def proxy_urls(self, protocol="http"):
        """Build login/password proxy URLs for every IP of the service."""
        auth = self.proxy_auth()
        endpoint = next(e for e in auth["endpoints"] if e["protocol"] == protocol)
        login = self.login_part(auth)
        return [f"{endpoint['scheme']}://{login}@{ip}:{endpoint['port']}" for ip in self.ips()]

    def refresh_status(self):
        return self._get("/proxy/refresh-status")

    def quote_refresh(self, target_ips, geo_counts):
        return self._post("/proxy/refresh/quote", {"target_ips": target_ips, "geo_counts": geo_counts})

    def refresh(self, target_ips, idempotency_key=None, attempts=3):
        """Replace IPs. The REST endpoint has no price guard: check the quote right before calling.

        One key per replacement, reused on every retry: if the first response was lost after
        the server charged, the retry returns the same result instead of replacing again.
        """
        key = idempotency_key or f"refresh-{uuid.uuid4()}"
        for attempt in range(attempts):
            try:
                return self._post("/proxy/refresh", {"target_ips": target_ips, "idempotency_key": key})
            except (requests.ConnectionError, requests.Timeout):
                if attempt == attempts - 1:
                    raise
                time.sleep(2 * (attempt + 1))


if __name__ == "__main__":
    for url in FineProxyAPI().proxy_urls():
        print(url)
```

`python fineproxy_api.py > proxies.txt && chmod 600 proxies.txt` exports the list. The file contains your proxy password, so keep it out of git and out of shared folders. Exporting and quoting work with a read-only API key. A paid replacement also needs a key with the `wallet:spend` scope, so give that key only to the script that is allowed to spend.

The self-healing script, `self_healing.py`, reuses the statistics `ProxyRotator` already keeps. An IP goes on the replacement list when its first three or more attempts all failed, or when it has handled at least ten requests and more than 20% of them failed. The 20% is our threshold, not a standard; tune it to your site. The script checks every 100 requests and refuses to pay more than `MAX_REFRESH_CENTS`:

```python
import os
import sys

import requests

from fineproxy_api import FineProxyAPI
from rotator import ProxyRotator

ERROR_RATE_LIMIT = 0.2  # replace an IP when more than 20% of its requests fail (our threshold, tune it)
MIN_REQUESTS = 10       # ...but only after it has handled at least this many
DEAD_AFTER = 3          # or when its first 3+ attempts all failed
MAX_REFRESH_CENTS = int(os.environ.get("MAX_REFRESH_CENTS", "0"))
DRY_RUN = os.environ.get("DRY_RUN") == "1"  # print the quote, replace nothing


def host_of(proxy_url):
    return proxy_url.rsplit("@", 1)[-1].rsplit(":", 1)[0]


def bad_ips(rotator):
    return [
        host_of(p)
        for p, s in rotator.stats.items()
        if (s.total >= MIN_REQUESTS and s.error_rate > ERROR_RATE_LIMIT) or (s.ok == 0 and s.failed >= DEAD_AFTER)
    ]


def heal(api, rotator):
    targets = bad_ips(rotator)
    if not targets:
        return False
    status = api.refresh_status()
    if status["price_cents"] > MAX_REFRESH_CENTS:
        print(f"{len(targets)} bad IPs, but a refresh costs {status['price_cents']} cents; skipping")
        return False
    countries = api.ip_countries()
    geo_counts = {}
    for ip in targets:
        geo_counts[countries[ip]] = geo_counts.get(countries[ip], 0) + 1
    quote = api.quote_refresh(targets, geo_counts)
    if DRY_RUN:
        print("dry run:", targets, quote)
        return False
    if quote["shortfall"] or quote["price_cents"] > MAX_REFRESH_CENTS:
        print("refresh refused by quote:", quote["price_cents"], "cents, shortfall:", quote["shortfall"])
        return False
    result = api.refresh(targets)
    print(f"replaced {len(targets)} IPs for {result['charged_cents']} cents: {targets} -> {result['new_ips']}")
    rotator.replace_proxies(api.proxy_urls())
    return True


if __name__ == "__main__":
    url = sys.argv[1] if len(sys.argv) > 1 else "https://api.ipify.org"
    count = int(sys.argv[2]) if len(sys.argv) > 2 else 200
    api = FineProxyAPI()
    rotator = ProxyRotator(api.proxy_urls(), cooldown=5, max_retries=3, timeout=10)
    for i in range(1, count + 1):
        try:
            rotator.get(url)
        except requests.RequestException:
            pass
        if i % 100 == 0:
            heal(api, rotator)
    print(f"done: {rotator.total_ok} ok, {rotator.total_failed} failed attempts, "
          f"{len(rotator.proxies)} proxies in the pool")
```

The quote needs the country of each replacement, so the script reads it from the IP list and keeps every replacement in the same country. When we first ran our list, three of the 100 IPs failed every attempt with a connection timeout. With `DRY_RUN=1`, the script flagged those three and printed a quote: price 0, stock available in both countries. Without the dry run, the replacement took about two seconds, the rotator reloaded the list, and the next 260 requests all succeeded. (That run used an earlier threshold of two requests; the version above waits for three straight failures.)

The billing is the part to get right. The first replacement of a FineProxy service is free, and the next free one opens 8 days later. In between, each replacement costs $10 however many IPs it covers; `refresh-status` shows the price and the date of the next free window. That's why the script checks the price twice and does nothing when the replacement isn't free, unless you raise `MAX_REFRESH_CENTS`. The REST refresh call has no price guard of its own, so the quote check in the script is the guard. `refresh()` creates one idempotency key per replacement and reuses it on retries: if the response is lost after the server has replaced the IPs, the retry gets the same result back instead of replacing and paying again.

You can run the same check from an AI agent instead of a script. With the FineProxy MCP server connected to Claude Code or Cursor, the task is one sentence: "Check every IP of my German service, list the ones that fail more than 20% of the time and quote their replacement. Don't replace anything yet." In our test, the agent checked 100 IPs, found 4 that timed out on three tries, got a $10 quote and stopped. For a prompt like this, a read-only key is enough; the MCP `refresh_ips` tool also takes the quoted price as `expected_amount_cents` and refuses to charge a different one. Screenshots of that session are in our [proxy manager comparison](/articles/proxy-manager/#manage-proxies-with-an-ai-agent-mcp).

## Free and open-source proxy rotators

If you'd rather not write a rotator, there are free tools. Some popular ones are no longer maintained, so check the dates before you build on them.

[mubeng](https://github.com/mubeng/mubeng) is the most practical free proxy rotator on GitHub today (Apache-2.0). It's one Go binary that both checks a list and runs a local rotating proxy, so any program that can use one proxy gets rotation without code changes:

```bash
# Check the list and keep the proxies that work
mubeng -f proxies.txt -c -t 10s -o live.txt

# Local rotating proxy: a new upstream on every request, retry on errors
mubeng -a 127.0.0.1:8089 -f live.txt -m sequent -r 1 --rotate-on-error -s

curl -k -x http://127.0.0.1:8089 https://api.ipify.org
```

With version 0.23.0, the checker found all 100 of our proxies alive, and five requests through the local port came from five different IPs. Two details aren't obvious from the README. mubeng terminates TLS itself to rotate HTTPS traffic, so the client sees mubeng's certificate: curl needs `-k` or mubeng's CA installed, and mubeng sees the full URLs and page contents, so don't send logins through it. Without `-s` (sync mode), rotation after exactly N requests isn't guaranteed. The local port speaks HTTP only, although the upstream proxies can be SOCKS.

**Scrapoxy** is often listed as the open-source proxy rotator for scrapers, but it shut down on February 6, 2026. Its public documentation and shared backend are gone, and the author doesn't plan to open the code. Other open-source projects have aged too: `scrapy-rotating-proxies` was last released in 2019, and the original ProxyBroker in 2019, with an active fork, ProxyBroker2, in beta.

Running a rotator costs nothing; feeding it free proxies usually costs you the results. Most addresses on public lists don't answer, and the ones that do are slow, shared with strangers and sometimes inject content or break TLS. If you want to experiment, take a fresh [free proxy list](/free-proxy-lists/), run it through a [proxy checker](/proxy-checker/) or mubeng's check mode right before the run, and never send logins or personal data through it.

## How to tell your rotation works

A rotator that "runs" can still send everything through one IP or burn half its retries on dead proxies. Check these four things:

1. **Different IPs.** Send 20–100 requests to an IP echo service such as api.ipify.org and count the unique answers. With per-request rotation and enough proxies, it should be close to the number of requests.
2. **The success rate per IP.** An overall 95% can hide five IPs that never work. `report()` in step 2 prints the error rate per proxy, sorted from worst to best.
3. **Retries and backoff in the logs.** After a 429, the same IP shouldn't be used again before its `Retry-After` time is up. With `verbose=True`, the rotator prints every benched IP and for how long.
4. **The country of each IP.** Geo databases don't always agree, especially for datacenter IPs. If the site serves content by country, check each IP in a geo database before trusting it.

## Where to get proxies for these examples

`rotator.py`, `async_httpx.py`, the Scrapy middleware and mubeng work with any provider's proxies. The API scripts are FineProxy-specific: FineProxy has [rotating proxies](/proxy/unlimited-rotating-proxies/) with rotating and sticky ports, and [datacenter proxies](/datacenter-proxies/) sold as static IP lists, both managed through the REST API used above. The endpoints are in the [developer docs](/developers/docs/).

## Frequently asked questions

### Is a proxy rotator the same as a VPN?

No. A VPN sends all traffic of your device through one server, encrypts it and gives you one IP for the whole connection. A proxy rotator works inside one app or script and gives it a different IP per request or per session, without adding its own encryption. Use a VPN to protect or relocate your own browsing; use a rotator when a script sends many requests and a single IP would get rate-limited.

### How often should I rotate proxies?

Rotate on every request for pages that don't need a login or cookies, such as search results and product pages. Keep the same IP for a session when the site expects continuity: a login, a cart or pagination with cookies. Fifteen minutes is a common session length; FineProxy's sticky sessions default to 900 seconds. If a site returns 429 with Retry-After, let that IP rest for at least that long.

### Is using a proxy rotator legal?

This isn't legal advice. Rotating IPs is a neutral technique, and proxies are used for price monitoring, ad checks and QA every day. The legal risk comes from what you do with it: logging in to accounts against a site's terms, getting around authentication or collecting personal data. US courts have treated scraping of public pages differently from scraping behind a login, so check the site's terms and the rules in your country.

### Can I use a free proxy list with a rotator?

Technically yes, but expect most addresses to fail. The ones that work are slow, shared with strangers and sometimes alter the pages they forward. Use free lists only for experiments, check them right before each run, and never send logins or personal data through them.

### How do I use a proxy rotator?

Put your proxies in a file, one URL per line, and let a script such as the rotator.py in this article pick the next one for each request, retry on another proxy after a failure and rest IPs that get blocked. If you don't want to keep a list, connect to a provider's rotating endpoint instead: one address, and the provider changes the IP for you.
