Rotate Proxy IP After N Requests in Python
December 1, 2026
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.
This 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.
Why rotate by request count
Time-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.
Counting 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.
Prerequisites
You need:
- A proxy username and password.
- The gateway host and HTTP port.
- An API key for the provider API.
- The proxy identifier for the rotate endpoint.
- Python 3 and the requests package.
If 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.
Configure the proxy in Python
RoProxy 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:
PROXY_URL = "http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT"
PROXIES = {
"http": PROXY_URL,
"https": PROXY_URL,
}
If 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.
Test the connection by checking the exit IP:
import requests
response = requests.get(
"https://api.ipify.org?format=json",
proxies=PROXIES,
timeout=15,
)
print(response.json())
The origin field should show the proxy IP, not your local address. You can also use https://httpbin.org/ip for the same check.
Track requests and trigger rotation
Create a small wrapper that counts every request and calls the rotate endpoint after N requests. The rotate endpoint is:
POST https://backend-api.ro-proxy.com/api/session/SESSION_ID/rotate
It 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.
import time
import urllib.error
import urllib.request
import requests
API_KEY = "API_KEY"
SESSION_ID = "SESSION_ID"
ROTATE_URL = f"https://backend-api.ro-proxy.com/api/session/{SESSION_ID}/rotate"
PROXY_URL = "http://USERNAME:PASSWORD@GATEWAY_HOST:HTTP_PORT"
PROXIES = {
"http": PROXY_URL,
"https": PROXY_URL,
}
MAX_REQUESTS = 50
MIN_ROTATE_INTERVAL = 60
class RequestLimitRotator:
def __init__(self, max_requests, min_interval):
self.max_requests = max_requests
self.min_interval = min_interval
self.count = 0
self.last_rotate = 0.0
def get(self, url, **kwargs):
self.count += 1
if self.count >= self.max_requests:
self.rotate()
self.count = 0
return requests.get(url, proxies=PROXIES, **kwargs)
def rotate(self):
now = time.time()
elapsed = now - self.last_rotate
if elapsed < self.min_interval:
time.sleep(self.min_interval - elapsed)
req = urllib.request.Request(
ROTATE_URL,
method="POST",
headers={"Authorization": f"Bearer {API_KEY}"},
)
try:
with urllib.request.urlopen(req, timeout=20) as resp:
if resp.status != 200:
raise RuntimeError(f"rotate returned {resp.status}")
except urllib.error.HTTPError as err:
if err.code in (401, 407):
raise RuntimeError("invalid API key or proxy credentials") from err
if err.code == 429:
raise RuntimeError("rotation rate limit reached") from err
raise
self.last_rotate = time.time()
The 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.
Running through a list of URLs
In 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.
targets = [
"https://example.com/item/1",
"https://example.com/item/2",
"https://example.com/item/3",
]
for target in targets:
try:
resp = rotator.get(target, timeout=30)
print(f"{target} -> {resp.status_code}")
except requests.RequestException as err:
print(f"{target} failed: {err}")
This pattern keeps the IP stable for exactly MAX_REQUESTS fetches, then switches before the next one.
Verify the exit IP changed
Before rotating, capture the current IP. After rotating, request the same endpoint again and compare.
def fetch_ip():
resp = requests.get(
"https://api.ipify.org?format=json",
proxies=PROXIES,
timeout=15,
)
return resp.json()["ip"]
rotator = RequestLimitRotator(MAX_REQUESTS, MIN_ROTATE_INTERVAL)
urls = [
"https://example.com/page-1",
"https://example.com/page-2",
]
old_ip = fetch_ip()
print(f"Starting IP: {old_ip}")
for url in urls:
try:
resp = rotator.get(url, timeout=20)
print(f"{url} -> {resp.status_code}")
except requests.RequestException as err:
print(f"{url} failed: {err}")
new_ip = fetch_ip()
print(f"IP after rotation: {new_ip}")
print(f"IP changed: {old_ip != new_ip}")
If 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.
Sticky versus timed rotation
Each proxy has a rotation mode:
- Sticky: keeps the same IP until it is rotated manually or the IP fails.
- Timed: changes the IP after an interval you set.
Request-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.
If 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.
Error handling and rotation budgets
Proxy 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.
Wrap 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.
When not to rotate
Do 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.
Conclusion
Request-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.
RoProxy provides the gateway, credentials, and API endpoints described here. New accounts can try the service with free proxies, and support is available on Telegram.