How to Handle Retries, Rate Limits and Session State with Mobile Proxies
When to retry requests through a mobile proxy, how to handle 429 responses and Retry-After, why POST requests need their own session, and what to check when your exit IP changes. Tested Python examples with requests and urllib3.
Requests through a mobile proxy fail for different reasons. A site may rate limit you, a server may be briefly unavailable, the proxy may reject your credentials, or the connection may break for a moment while the mobile connection reconnects during an IP rotation. Retrying all of these the same way causes problems: some failures need a pause, some should never be retried, and some leave your session in a state you need to check.
This guide explains which errors to retry, how to handle 429 responses and the Retry-After header, how to add backoff with jitter, why POST requests need their own handling, and what to check when the exit IP changes. The examples use Python with requests and urllib3, and we ran all of them against a local test server and test proxy.
Which Errors to Retry
Start by sorting failures into those that are worth retrying and those that are not:
| Response or error | What it usually means | What to do |
|---|---|---|
| 429 Too Many Requests | The site is rate limiting you | Wait for the time in Retry-After, or back off if there is none, then slow down |
| 503 Service Unavailable | The server cannot handle the request right now, for example under load or during maintenance | Retry idempotent requests such as GET with backoff, and honour Retry-After if the server sends it |
| 502 Bad Gateway, 504 Gateway Timeout | A gateway or proxy got an invalid response, or no timely response, from the server behind it | Retry idempotent requests such as GET with backoff, a limited number of times |
| 407 Proxy Authentication Required | The proxy received missing or invalid credentials, or an authentication method it does not accept | Do not retry. Check the credentials and proxy settings |
| Connection refused | The proxy is not accepting connections, for example while a mobile connection reconnects during an IP rotation | Retry with backoff. The request never reached the server |
| Connection dropped | An open connection broke. The request may already have reached the server | Retry only idempotent requests such as GET. Never retry a POST automatically |
| Other 4xx, such as 403 or 404 | The site rejected this request | Do not retry automatically. Find out why first |
The status code definitions come from RFC 9110 and, for 429, from RFC 6585. Retrying a 407 or a 403 only repeats a request that will fail again, and it adds load to the proxy and the site.
What a 429 Response Tells You
RFC 6585 defines 429 Too Many Requests: it "indicates that the user has sent too many requests in a given amount of time." The response may include a Retry-After header that says how long to wait.
The RFC deliberately leaves open how a server identifies the user and counts requests. A limit can apply to one resource or a whole server, and a user can be identified by credentials or a cookie, not only by IP address. This matters with mobile proxies. Through carrier-grade NAT, many subscribers can share one public IP address, as explained in What Is CGNAT?. A limit tied to the IP can therefore also be reached by other people using the same address, and a limit tied to an account or cookie stays in place when the IP changes. Either way, rotating to a new IP after a 429 does not reliably reset a limit, and it is not what the response asks for. A 429 asks you to slow down.
Slowing down means lowering the request rate itself, for example with a fixed delay between requests or a maximum number of requests per second. If several workers share the same account or API quota, coordinate their rate, and pause all of them for the interval the server asks for, not only the worker that received the 429.
RateLimit header fields
Some APIs also send headers that describe their limits in advance. The IETF HTTPAPI working group is standardising this as RateLimit-Policy and RateLimit header fields. As of November 2026 the specification is still an Internet-Draft, not an RFC, so header names and formats vary between services. If a site sends such headers, read its documentation and keep your request rate below the stated limit.
Honour Retry-After
Under RFC 9110, Retry-After takes one of two forms: an HTTP date, or a number of seconds to wait after receiving the response:
Retry-After: Fri, 31 Dec 1999 23:59:59 GMT
Retry-After: 120
RFC 9110 describes its use with 503 responses, to say how long the service is expected to be unavailable. RFC 6585 and MDN describe its use with 429 responses, to say how long to wait before the next request. An HTTP date can arrive in any of the three date formats that RFC 9110 requires recipients to accept. MDN notes that support for the header is still inconsistent, so treat it as information to use when it is present. A 429 without Retry-After still asks you to slow down, so your own backoff applies.
urllib3, the library that requests uses underneath, can follow Retry-After itself. Its respect_retry_after_header setting is enabled by default, and then urllib3 retries 413, 429 and 503 responses that carry the header, even when those codes are not in status_forcelist. Since urllib3 2.6.3, a Retry-After longer than six hours is treated as six hours, and the Retry documentation describes a retry_after_max parameter for setting a different cap.
A lower cap has a catch: when the server asks for a longer pause than the cap, the client retries earlier than the server asked, which goes against the rate limit. When the requested pause is longer than your job can wait, it is better to stop and schedule the request for later. That is why the setup below turns respect_retry_after_header off and handles 429 and 503 in a small function of its own.
Add Backoff with Jitter
When there is no Retry-After header, wait longer after each failed attempt. This is exponential backoff. On its own, it still lets many clients retry at the same moments. In an AWS Architecture Blog post, Marc Brooker showed that plain exponential backoff leaves "clusters of calls," and concluded that jitter, a random part in each wait, "should be considered a standard approach for remote clients." The strategies he compared randomise a large part of each wait.
In urllib3, backoff_factor controls the growth, backoff_max caps a single wait, and backoff_jitter adds a small random amount of up to the given number of seconds on top. The documentation describes the formula as the backoff factor multiplied by 2 to the power of the number of previous retries, applied after the second try. In practice, the first retry happens without a pause. Backoff is disabled by default. For 429 and 503, the function below picks a random wait between 1 second and a growing upper limit, which spreads clients out more.
Do Not Retry POST Requests Automatically
RFC 9110 calls a method idempotent when several identical requests have the same intended effect as one. PUT, DELETE and the safe methods such as GET and HEAD are idempotent. POST is not. The RFC says a client "SHOULD NOT automatically retry a request with a non-idempotent method" unless it knows the request is idempotent or can tell that the original request was never applied, and that a proxy "MUST NOT automatically retry non-idempotent requests."
urllib3 only retries status codes and read errors for the methods in allowed_methods, which by default are DELETE, GET, HEAD, OPTIONS, PUT and TRACE. That is not the whole story with a proxy. In our test, a POST to an http:// URL went through the proxy to the server, and the connection then broke before the response came back. urllib3 counted this as an "other" error, which does not check the method, and sent the POST again. The server received it six times. requests on its own does not retry by default, and its documentation describes its simple max_retries number as covering only failed connections, but in the same test HTTPAdapter(max_retries=3) delivered the POST four times.
The safe approach is to send POST and other non-idempotent requests through a separate session without retries, as in the setup below, and to retry them only when the API documents a safe way to do so, for example with an idempotency key.
RFC 9110 also says a client "SHOULD NOT automatically retry a failed automatic retry." The setup below allows several retries for GET requests on purpose, with backoff and limits, because short connection failures during IP rotations are expected with mobile proxies. Keep those limits low.
A Retry Setup with requests and urllib3
The setup uses two sessions that share one cookie jar. session retries GET and other idempotent requests. post_session sends POST requests without retries. Replace proxy-endpoint, 8000, user and pass with your own proxy details:
import ipaddress
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
# Percent-encode the password if it contains characters such as @ : / %
PROXY = "http://user:pass@proxy-endpoint:8000"
PROXIES = {"http": PROXY, "https": PROXY}
# For GET and other idempotent requests: urllib3 retries connection
# problems and the status codes 502 and 504.
retry = Retry(
total=5,
connect=3,
backoff_factor=1,
backoff_max=30,
backoff_jitter=0.5,
status_forcelist=[502, 504],
respect_retry_after_header=False,
)
session = requests.Session()
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
# For POST and other non-idempotent requests: no automatic retries.
# It shares the cookie jar, so both sessions keep the same login state.
post_session = requests.Session()
post_session.cookies = session.cookies
# POST requests go through post_session, without retries
result = post_session.post("https://example.com/api/orders", json={"id": 1}, proxies=PROXIES, timeout=(10, 30))
What each setting does:
total=5 allows up to five retries, so up to six attempts in all. connect=3 limits how many of them can be refused connections.https:// URL counts as a read error, and a dropped http:// request through a proxy counts as an "other" error. All of them are capped by total.backoff_factor=1 and backoff_jitter=0.5 give growing waits, each with up to half a second of randomness. With total=5 the longest wait is about 16 seconds. backoff_max=30 caps a single wait if you later allow more retries.status_forcelist=[502, 504] lists the status codes urllib3 retries, and only for methods in allowed_methods, such as GET. 407, 403 and 404 are deliberately left out.respect_retry_after_header=False stops urllib3 from retrying 413, 429 and 503 on its own. The function in the next section handles 429 and 503.post_session.cookies = session.cookies makes both sessions use the same cookies, so a login done with one is visible to the other.The proxy is passed with proxies= on each request, because the requests documentation warns that proxy settings from environment variables such as HTTPS_PROXY can override session.proxies. Setting session.trust_env = False also ignores those variables, but it switches off other settings taken from the environment as well, such as a custom CA bundle, so use it with care. If your proxy password contains characters such as @, :, / or %, percent-encode it in the proxy URL.
backoff_max and backoff_jitter were added in urllib3 2.0.0, so this example needs urllib3 2.0 or later. We tested it with requests 2.34.2 and urllib3 2.8.0. When the retries for 502 or 504 run out, requests raises a RetryError, so catch it and log the request instead of letting the job stop without a record.
Handling 429 and 503
get_politely() follows Retry-After when the server sends it, in seconds or as an HTTP date, with at least one second and a small random amount added. Without Retry-After it backs off with a random wait. If the server asks for a longer pause than MAX_WAIT, or the response is still 429 or 503 after the last attempt, it raises RetryLater instead of retrying early. The exception carries the wait in seconds, so you can schedule the request for later:
MAX_WAIT = 120 # the longest pause this job accepts, in seconds
class RetryLater(Exception):
"""The request should be tried again later, after `wait` seconds."""
def __init__(self, message, wait):
super().__init__(message)
self.wait = wait
def retry_after_seconds(response):
value = (response.headers.get("Retry-After") or "").strip()
if not value:
return None
if value.isascii() and value.isdigit():
return int(value)
try:
when = parsedate_to_datetime(value)
if when.tzinfo is None: # HTTP dates without a zone are in UTC
when = when.replace(tzinfo=timezone.utc)
return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
except (TypeError, ValueError):
return None
def get_politely(session, url, attempts=3, **kwargs):
for attempt in range(attempts):
response = session.get(url, proxies=PROXIES, **kwargs)
if response.status_code not in (429, 503):
return response
server_wait = retry_after_seconds(response)
if server_wait is not None:
if server_wait > MAX_WAIT:
raise RetryLater(f"{url}: the server asked for a {server_wait:.0f} s pause", server_wait)
wait = max(server_wait, 1) + random.uniform(0, 1)
else:
wait = random.uniform(1, 2 ** (attempt + 1)) # no Retry-After: back off
if attempt < attempts - 1:
time.sleep(wait)
raise RetryLater(f"{url}: still {response.status_code} after {attempts} attempts", wait)
try:
response = get_politely(session, "https://example.com/products", timeout=(10, 30))
except RetryLater as e:
print(f"Try again in {e.wait:.0f} s: {e}")
get_politely() only sends GET requests, so it never repeats a POST. timeout=(10, 30) sets a 10 second connect timeout and a 30 second read timeout. The read timeout applies to each wait for data from the server, not to the whole response, and retries add up, so the worst case for one call is longer than 40 seconds.
Check the Proxy Credentials Before the Job
A wrong proxy password looks different depending on the target. For an http:// URL, the proxy answers with a 407 status, which the setup above returns at once because 407 is not in status_forcelist. For an https:// URL, urllib3 first sends a CONNECT request to the proxy, and a 407 on that step arrives as a ProxyError instead of a status code. urllib3 counts it as an "other" error, limited only by total. In our test environment, that meant five retries and about 31 seconds before the error appeared.
You could stop those retries with urllib3's other=0 setting, but in our test that also stopped the retries during a simulated rotation for http:// URLs. A simpler approach is to check the proxy once, without retries, before the job starts. A plain requests session does not retry. The function also checks the status code and that the answer is a valid IP address, so an error page from the IP service is not mistaken for an exit IP:
def check_proxy():
probe = requests.Session() # a plain session: no retries
try:
r = probe.get("https://api.ipify.org", proxies=PROXIES, timeout=(10, 30))
if r.status_code == 407:
raise SystemExit("The proxy rejected the credentials (407).")
r.raise_for_status()
return str(ipaddress.ip_address(r.text.strip()))
except requests.exceptions.ProxyError as e:
raise SystemExit(f"Proxy check failed. Check host, port and credentials: {e}")
except (requests.exceptions.RequestException, ValueError) as e:
raise SystemExit(f"Proxy check failed: {e}")
print("Exit IP:", check_proxy())
The check also gives you the starting exit IP, which is useful for the session checks below.
Retries During an IP Rotation
When a mobile proxy changes its IP, the mobile connection reconnects, and for a short time the proxy may refuse new connections or drop open ones. How Mobile Proxy Rotation Works covers the mechanics. For retry logic, the difference matters: refused connections count against connect, dropped ones against read or other, and all of them against total.
Size these limits and the backoff to the gap you actually see. In our test, the proxy refused or dropped connections for four seconds. The client retried immediately, again after about two seconds, and then after about four more, and the request went through after 6.3 to 6.8 seconds, for both http:// and https:// URLs. With refused connections, connect=3 was just enough. Measure the reconnect time of your own proxy during a rotation and give your retry settings some margin above it.
Session state after a rotation
A rotation changes the exit IP, but not the rest of your session. In our test, the session still held its cookie after the rotation, and the next requests came from the new IP. Some sites notice when a logged-in session suddenly comes from a new address. A site may end the session, ask you to log in again or run extra security checks, and your client cannot see that from the cookie alone. To keep this under control:
A small check is enough. If the exit IP cannot be checked, or the answer is not an IP address, the function logs the error and returns None instead of stopping the job:
def exit_ip(session):
try:
r = session.get("https://api.ipify.org", proxies=PROXIES, timeout=(10, 30))
r.raise_for_status()
return str(ipaddress.ip_address(r.text.strip()))
except (requests.exceptions.RequestException, ValueError) as e:
print(f"Could not check the exit IP: {e}")
return None
start_ip = exit_ip(session)
# ... run the task ...
end_ip = exit_ip(session)
if start_ip and end_ip and end_ip != start_ip:
print(f"Exit IP changed from {start_ip} to {end_ip} during the task")
What We Tested
We ran the code above against a local test server, reachable over HTTP and HTTPS, and a local HTTP proxy with Basic authentication. The test proxy could simulate a rotation by refusing or dropping connections for four seconds and then switching to a different exit address. For check_proxy() and exit_ip(), we pointed the IP check at both an http:// and an https:// test URL. The results:
| Test | Result | Time |
|---|---|---|
| 429 with Retry-After: 2, then 200 | Waited, then 200 | 2.7 s |
429 with Retry-After: 30, with MAX_WAIT set to 5 |
RetryLater raised, one request sent |
0.0 s |
| 429 without Retry-After, then 200 | Backed off, then 200 | 1.7 s |
| 429 with Retry-After as an HTTP date about 3 s ahead, with and without a time zone | Waited, then 200 | 2.8 and 3.1 s |
| 429 with Retry-After: 0 twice, then 200 | Waited at least 1 s each time, then 200 | 3.4 s |
| 429 on every attempt | RetryLater after three requests |
3.7 s |
| 503 twice, then 200 | 200 on the third attempt | 2.6 s |
| 502 once, then 200 | Retried by urllib3, then 200 | 0.0 s |
| 413 with Retry-After: 1 | Returned, not retried | 0.0 s |
POST through post_session, connection dropped after the server received it |
Error raised, POST received once | 0.0 s |
| The same POST through the retry session | POST received six times | 31.5 s |
GET right after a rotation starts, connections dropped or refused for 4 s, http:// and https:// |
200 after retries | 6.3 to 6.8 s |
GET to an https:// URL with a wrong proxy password, retry session |
ProxyError after five retries |
30.9 s |
check_proxy() with a wrong password, http:// and https:// |
Stopped at once with a clear message | 0.0 s |
check_proxy() when the IP service answers 502 |
Stopped with a clear message | 0.0 s |
exit_ip() when the answer is not an IP, or the proxy cannot be reached |
Error logged, None returned | 0.0 and 6.1 s |
The results match the behaviour described above: Retry-After is followed in seconds and in date form, a pause longer than MAX_WAIT stops the request instead of retrying early, a 429 without Retry-After backs off, a POST sent through post_session reaches the server once, and retries cover the simulated rotation. These tests used a simulated rotation, so the four second gap and the timings say nothing about the performance of a real mobile network.
Checklist
For keeping an eye on proxies over time, see Mobile Proxy Monitoring and Health Checks, and for switching to a backup connection when one fails, Mobile Proxy Failover and Redundancy.
FAQ
Should I rotate the IP when I get a 429?
Not as a first response. A 429 asks you to slow down, and the site may identify you by something other than the IP, such as a cookie or credentials. Wait for the Retry-After time and lower your request rate.
Does requests retry failed requests by default?
No. requests disables retries by default. Pass an explicit urllib3 Retry object to an HTTPAdapter to control connection errors, read errors and status codes separately.
Is it safe to retry a POST request?
Not automatically. POST is not idempotent, so repeating it can repeat its effect, such as submitting a form twice. Through a proxy, a POST can even be resent after a dropped connection, so send it through a session without retries, and only retry it if the API documents a safe way to do so.
How many retries should I allow?
Enough to cover short failures, such as a reconnect during a rotation, but low enough that a real problem is reported quickly. Measure how long your typical failures last and set the retry count and backoff to cover that with some margin.
Platform terms of service still apply. Retry logic and mobile proxies change how your requests reach a website. They do not authorize activity that a platform prohibits, and a rate limit is a signal to respect.
Related Reading
Dedicated Mobile Proxies with Rotation Control
PowerProxy provides dedicated mobile connections on real carrier SIMs, with HTTP, SOCKS5, and OpenVPN support. In Amsterdam, PowerProxy offers Odido, KPN, and Vodafone SIMs.
No credit card required · 4.3 / 5 on Trustpilot ★★★★★ · 1,200+ businesses
Narmin Kamilsoy
Contributing author sharing insights and stories on our blog.