[{"data":1,"prerenderedAt":35},["ShallowReactive",2],{"blog:post:en:rotate-proxy-ip-after-n-requests":3,"blog:related:en:rotate-proxy-ip-after-n-requests":22},{"slug":4,"lang":5,"title":6,"summary":7,"date":8,"tags":9,"tag_slugs":14,"thumbnail_url":15,"translations":16,"body":17,"asset_base":18,"checksum":19,"published_at":20,"content_updated_at":21},"rotate-proxy-ip-after-n-requests","en","Rotate Proxy IP After N Requests in Python","Change your proxy IP after a fixed number of requests instead of on a timer. Includes Python code, exit-IP checks, and API rotation steps.","2026-12-01",[10,11,12,13],"proxy-rotation","python","web-scraping","proxy-configuration",[10,11,12,13],"https://blog-api.ro-proxy.com/api/blog/posts/rotate-proxy-ip-after-n-requests/thumbnail.svg?lang=en",[5],"Time-based rotation is convenient, but it does not always match how your application uses a proxy. An IP can change in the middle of a multi-step form, or it can stay the same long after a target site has flagged it. Rotating after a fixed number of requests gives you a clear boundary without depending on the clock.\n\nThis guide shows how to route traffic through an HTTP proxy in Python, count requests, and rotate the IP on demand through the provider API. It works with sticky or timed rotation modes, and it uses only the standard library plus the requests package.\n\n## Why rotate by request count\n\nTime-based rotation assumes all requests are equal. They are not. A single page load can trigger dozens of requests for scripts, images, and API calls. If your timer fires in the middle of that load, some requests use the old IP and some use the new one. That breaks cookies, authentication state, and any logic that expects a stable address for a short sequence.\n\nCounting requests gives you control. You decide what counts as a unit of work—one page, one API call, or one product detail—and you rotate only when that unit is complete. This also makes logs easier to read because each IP address is tied to a known number of requests.\n\n## Prerequisites\n\nYou need:\n\n- A proxy username and password.\n- The gateway host and HTTP port.\n- An API key for the provider API.\n- The proxy identifier for the rotate endpoint.\n- Python 3 and the requests package.\n\nIf you are on the Pro or Business plan, you can rotate an IP immediately with the API. On the Free plan, the IP changes on a fixed schedule and cannot be rotated by hand.\n\n## Configure the proxy in Python\n\nRoProxy proxies use a gateway host on an HTTP port for both HTTP and HTTPS traffic. Each proxy has its own username and password. Configure the proxy URL like this:\n\n```python\nPROXY_URL = \"http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT\"\n\nPROXIES = {\n    \"http\": PROXY_URL,\n    \"https\": PROXY_URL,\n}\n```\n\nIf your plan includes a SOCKS5 port, you can use `socks5h://USERNAME:PASSWORD@GATEWAY_HOST:SOCKS5_PORT` instead. The `socks5h` scheme sends DNS lookups through the proxy rather than resolving them locally.\n\nTest the connection by checking the exit IP:\n\n```python\nimport requests\n\nresponse = requests.get(\n    \"https://api.ipify.org?format=json\",\n    proxies=PROXIES,\n    timeout=15,\n)\nprint(response.json())\n```\n\nThe `origin` field should show the proxy IP, not your local address. You can also use `https://httpbin.org/ip` for the same check.\n\n## Track requests and trigger rotation\n\nCreate a small wrapper that counts every request and calls the rotate endpoint after N requests. The rotate endpoint is:\n\n```\nPOST https://backend-api.ro-proxy.com/api/session/SESSION_ID/rotate\n```\n\nIt requires an `Authorization: Bearer API_KEY` header. Pro and Business plans enforce a minimum wait between rotation calls, so track the last rotation time and sleep if needed.\n\n```python\nimport time\nimport urllib.error\nimport urllib.request\n\nimport requests\n\nAPI_KEY = \"API_KEY\"\nSESSION_ID = \"SESSION_ID\"\nROTATE_URL = f\"https://backend-api.ro-proxy.com/api/session/{SESSION_ID}/rotate\"\n\nPROXY_URL = \"http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT\"\nPROXIES = {\n    \"http\": PROXY_URL,\n    \"https\": PROXY_URL,\n}\n\nMAX_REQUESTS = 50\nMIN_ROTATE_INTERVAL = 60\n\n\nclass RequestLimitRotator:\n    def __init__(self, max_requests, min_interval):\n        self.max_requests = max_requests\n        self.min_interval = min_interval\n        self.count = 0\n        self.last_rotate = 0.0\n\n    def get(self, url, **kwargs):\n        self.count += 1\n        if self.count >= self.max_requests:\n            self.rotate()\n            self.count = 0\n        return requests.get(url, proxies=PROXIES, **kwargs)\n\n    def rotate(self):\n        now = time.time()\n        elapsed = now - self.last_rotate\n        if elapsed \u003C self.min_interval:\n            time.sleep(self.min_interval - elapsed)\n\n        req = urllib.request.Request(\n            ROTATE_URL,\n            method=\"POST\",\n            headers={\"Authorization\": f\"Bearer {API_KEY}\"},\n        )\n        try:\n            with urllib.request.urlopen(req, timeout=20) as resp:\n                if resp.status != 200:\n                    raise RuntimeError(f\"rotate returned {resp.status}\")\n        except urllib.error.HTTPError as err:\n            if err.code in (401, 407):\n                raise RuntimeError(\"invalid API key or proxy credentials\") from err\n            if err.code == 429:\n                raise RuntimeError(\"rotation rate limit reached\") from err\n            raise\n        self.last_rotate = time.time()\n```\n\nThe wrapper resets the counter after every rotation. If a request fails before you reach the limit, the counter still advances. You can move the increment inside a success-only block if you prefer to count only successful responses.\n\n### Running through a list of URLs\n\nIn a real scraper, you usually have a queue of URLs. Pass the same rotator instance to every fetch so the counter persists across the loop. When the limit is reached, the next request triggers rotation before the request is sent.\n\n```python\ntargets = [\n    \"https://example.com/item/1\",\n    \"https://example.com/item/2\",\n    \"https://example.com/item/3\",\n]\n\nfor target in targets:\n    try:\n        resp = rotator.get(target, timeout=30)\n        print(f\"{target} -> {resp.status_code}\")\n    except requests.RequestException as err:\n        print(f\"{target} failed: {err}\")\n```\n\nThis pattern keeps the IP stable for exactly MAX_REQUESTS fetches, then switches before the next one.\n\n## Verify the exit IP changed\n\nBefore rotating, capture the current IP. After rotating, request the same endpoint again and compare.\n\n```python\ndef fetch_ip():\n    resp = requests.get(\n        \"https://api.ipify.org?format=json\",\n        proxies=PROXIES,\n        timeout=15,\n    )\n    return resp.json()[\"ip\"]\n\n\nrotator = RequestLimitRotator(MAX_REQUESTS, MIN_ROTATE_INTERVAL)\n\nurls = [\n    \"https://example.com/page-1\",\n    \"https://example.com/page-2\",\n]\n\nold_ip = fetch_ip()\nprint(f\"Starting IP: {old_ip}\")\n\nfor url in urls:\n    try:\n        resp = rotator.get(url, timeout=20)\n        print(f\"{url} -> {resp.status_code}\")\n    except requests.RequestException as err:\n        print(f\"{url} failed: {err}\")\n\nnew_ip = fetch_ip()\nprint(f\"IP after rotation: {new_ip}\")\nprint(f\"IP changed: {old_ip != new_ip}\")\n```\n\nIf `IP changed` is false, the rotation may not have completed yet, or the proxy may be in sticky mode and waiting for a failure or manual trigger. On timed mode, the IP also changes automatically after the interval you set, independent of your request count.\n\n## Sticky versus timed rotation\n\nEach proxy has a rotation mode:\n\n- Sticky: keeps the same IP until it is rotated manually or the IP fails.\n- Timed: changes the IP after an interval you set.\n\nRequest-based rotation works with both modes. With sticky mode, your manual API rotation ends the current IP assignment. With timed mode, the IP may change before you reach the request limit; your counter simply continues across the automatic change.\n\nIf you are on the Business plan, you can choose the proxy country from the countries in stock. This is useful when you need traffic to appear from a specific region, but it does not change how request counting or rotation works.\n\n## Error handling and rotation budgets\n\nProxy errors and API errors are different. A `407 Proxy Authentication Required` means your username or password is wrong. A `401 Unauthorized` from the rotate endpoint means your API key is wrong. A `429 Too Many Requests` from the rotate endpoint means you called it more often than your plan allows.\n\nWrap network calls in try/except blocks and log the status code. Do not rotate on every transient error. Rotate only when you hit your request limit or when a target consistently returns errors from the same IP. Rotating after every failure can burn through your rotation budget and make debugging harder.\n\n### When not to rotate\n\nDo not rotate on a single timeout or a 502 error. Those often come from the target server, not the proxy IP, and rotating wastes your rotation budget. Rotate only when the same IP repeatedly fails or when you reach your planned request count.\n\n## Conclusion\n\nRequest-based proxy rotation gives you predictable IP boundaries and puts you in control of when the address changes. Combine it with exit-IP checks and careful error handling, and your scraper will be easier to debug and less likely to surprise you mid-run.\n\nRoProxy provides the gateway, credentials, and API endpoints described here. New accounts can try the service with free proxies, and support is available on Telegram.\n","https://blog-api.ro-proxy.com/api/blog/posts/rotate-proxy-ip-after-n-requests/assets","d8c3f40652bacc9a1a01db0eeb47e3d2affb6394287c19e1f6b7f9f294e26af8","2026-12-01T01:08:09.216458Z","2026-12-01T01:08:09.218342Z",[23,27,31],{"slug":24,"title":25,"summary":26},"scheduled-proxy-ip-rotation-python","Schedule Proxy IP Rotation in Python","Use timed proxy rotation for predictable Python scrapers, with requests code, retry checks, and safe IP change scheduling.",{"slug":28,"title":29,"summary":30},"cut-scraping-bandwidth-with-etags","Save Scraping Bandwidth with ETags and 304 Responses","Turn repeat scrapes into cheap 304 Not Modified responses with ETags and If-Modified-Since, cutting bandwidth and origin load.",{"slug":32,"title":33,"summary":34},"configuring-rotating-proxies-nextjs-ssr-fetching","Configuring Rotating Proxies for Next.js SSR Fetching","Learn how to route Next.js server‑side data fetching through rotating proxies, handle authentication, and rotate IPs on demand using the RoProxy API.",1796251608966]