A mid-session IP change happens when the steps of a multi-step flow reach a site from different exit IPs. The site ties the session to a cookie, and sometimes also to the IP it saw first. When the address changes, the server may end the session, reject the CSRF token or show content for another region. The trap: the client often sees no error. This article covers why the change happens, how to spot it and how to design a flow that can rebuild the session.
What the site sees
A site that sees the same session cookie arrive from a new IP may treat it as a risk signal. The OWASP session management guidance suggests binding the session ID to client properties such as the IP and treating a mid-session change as a sign of hijacking. So the site is running a security check. Do not try to bypass it. Build your flow to fit it.
The site responds in four ways:
| Response | What you see | Error raised |
|---|---|---|
| Session ends | 302 redirect to the login page, 401, a Set-Cookie that clears the session cookie | Sometimes |
| Extra verification | Email code or an "is this you" page, status 200 | No |
| CSRF rejection | 403, or a non-standard 419 in some frameworks | Yes |
| Location-based content | Different currency, language or stock data, status 200 | No |
CSRF rejection is a separate mechanism. The form token is tied to the session. If the site renews the session because of the IP change, your token still belongs to the old session and the form is rejected. The error shows up in the form, but the root cause is the address change.
The last row is the quietest. If the new IP is in another city or country, the site may show prices in another currency. The flow completes without an error, but the data you collect is mixed.
Four reasons for the change
The exit IP changes in four ways. Two come from the nature of sticky sessions, two from your own setup.
The sticky duration expired. A sticky session binds the same ID to the same exit for the chosen duration. At Proxynet that duration is 1-60 minutes. After it expires, the first new connection gets a different exit. If the flow runs longer than the duration, the address changes halfway through. We cover choosing the duration in What Is a Sticky Session?.
The exit device left the network. In residential and mobile pools the exit is a real device. If the device shuts down or reconnects, the open tunnel breaks. A new connection with the same ID leaves from a different IP.
A rotating endpoint. In rotating mode every new connection gets a new exit. That is right for collecting independent pages. It breaks linked steps such as login and checkout. Use Sticky Proxy for those steps.
The connection pool. HTTP clients keep connections open and reuse them. In Requests this happens automatically inside a session object. Even on a rotating endpoint, the flow seems to leave from one IP for a while, because every request goes through the same tunnel. When the server or the proxy closes the connection, the client quietly opens a new one and a new IP arrives. With parallel requests the pool opens a second connection. That connection may get a different exit too.
When the last two combine, the failure is misleading. The code works locally or in a short test, then breaks under load or on a slow day.
Detecting the change
An IP change shows up in two places: the exit IP itself and the site's response. Watch both.
Record the exit IP at the start of the flow. Check it again before critical steps such as login and payment. Make that check over a new connection, or you will see the address of the old tunnel in the pool. The code for this check is in the troubleshooting section of the sticky session article.
Response signals need no extra request. Look for:
- A
Locationheader pointing to the login page. A client that follows redirects automatically shows this as200, so turn redirects off or check the final URL of the response. - A
Set-Cookieheader that empties the session cookie or sets its lifetime to zero. 401,403and419statuses in the middle of the flow.- A change in a marker on the page: currency, language, country selector or the name of the logged-in user.
Do not trust the exception message. In our test the proxy dropped the connection before passing on the order response. Requests reported it as Unable to connect to proxy. Yet the request had reached the site and the order had been created.
Short, repeatable flows
You cannot fully prevent address changes. A device can drop off the network. So the goal is that a change does no harm to the flow. Four rules get you there.
Keep the steps short. Measure the time from login to the last step. It should sit comfortably below the sticky duration. Split long jobs and give each part a new ID.
One ID and one cookie jar per flow. Each flow uses its own sticky session ID and its own session object. The ID is not handed to another job before the flow ends. We cover how cookies carry through a session in Sessions and Cookies in Python.
Start over when the session drops. Retrying the broken step does not help, because the server has closed the session. Get a new ID, reset the cookies and start from login. Cap the number of attempts and wait between them. Retrying with growing waits is covered in our exponential backoff article.
Make the steps idempotent. An idempotent step leaves the same result whether it runs once or twice. RFC 9110 puts the PUT and DELETE methods in this class. A PUT that says "the cart holds one of this item" leaves the cart unchanged even if it is sent twice. A POST, on the other hand, may create a new record on every call. If the server supports it, the Idempotency-Key header closes this risk. If it does not, read the state before sending: does the order already exist?
If the site asks for extra verification, stop the flow. An email code or a verification page is a point where a person has to decide. Do not try to automate that code. The pattern in this article is for your own account, your own test application or flows you have permission to run.
Flow code that can start over
The example below runs the login, cart and order steps in one attempt. If one of the signs of session loss shows up, or the connection breaks, it abandons the attempt and rebuilds the flow with a new ID. The order key stays the same across all attempts.
import os
import uuid
import requests
SITE = os.environ.get("SITE", "http://127.0.0.1:8081") # your own test app
PROXY = os.environ.get("PROXY", "http://user:pass@pr.proxynet.io:8000")
class SessionLost(Exception):
pass
def check(resp):
# Signs of session loss: redirect to login, 401, 419, CSRF rejection
location = resp.headers.get("Location", "")
if resp.status_code in (401, 419) or "/login" in location:
raise SessionLost(f"{resp.status_code} {location}")
if resp.status_code == 403 and "csrf" in resp.text.lower():
raise SessionLost("CSRF token rejected")
resp.raise_for_status()
return resp
def call(s, method, path, **kw):
return check(s.request(method, SITE + path, allow_redirects=False, timeout=20, **kw))
def login(proxy_url):
s = requests.Session() # empty cookie jar on every attempt
s.proxies = {"http": proxy_url, "https": proxy_url}
r = call(s, "POST", "/login", data={"username": "demo", "password": "demo"})
s.headers["X-CSRF-Token"] = r.json()["csrf"]
return s
def place_order(new_proxy_url, attempts=3):
order_key = str(uuid.uuid4()) # same key on every attempt
for attempt in range(1, attempts + 1):
try:
with login(new_proxy_url()) as s:
call(s, "PUT", "/cart/items/sku-42", json={"qty": 1})
r = call(s, "POST", "/orders", headers={"Idempotency-Key": order_key})
return r.json()
except (SessionLost, requests.ConnectionError) as exc:
print(f"attempt {attempt}: session lost ({exc}), starting over")
raise RuntimeError("flow could not be completed")
if __name__ == "__main__":
print(place_order(lambda: PROXY))new_proxy_url should return a proxy URL built with a new sticky session ID on every call. The lambda in the example returns the same URL every time. In real use, change the ID on each attempt, or the second attempt may land on the same problematic exit. requests.ConnectionError also covers proxy errors. So a dropped connection starts a new attempt too.
allow_redirects=False is a deliberate choice. With redirects on, the client would go to the login page and return 200. The code would never notice that the session had dropped. If you want a wait between attempts, put it at the end of the except block.
How we tested
We ran the test on December 1, 2026 with Python 3.13, Requests 2.34.2 and urllib3 2.6.3. The setup had two local servers. The test site bound the session to the IP seen at login; when the IP changed, it deleted the session and redirected to the login page with 302. The order endpoint recognised the Idempotency-Key header. A local test proxy simulated different exits with the loopback addresses 127.0.0.2-127.0.0.9. We scaled sticky durations to seconds instead of minutes.
| Scenario | Result |
|---|---|
| Sticky, 60 seconds | Completed on the first attempt, one IP |
| Rotating, connection stays open | Completed: three requests went through one tunnel |
| Rotating, connection closes after every response | 302 at the cart step in all three attempts, flow stopped |
| Sticky 2 seconds, slow cart step | First attempt dropped at the order, second completed |
| Order response cut off in transit | Second attempt returned the same order, one order on the server |
The second row shows the pool effect. The rotating endpoint behaved like a sticky one as long as the connection stayed open. In the third row the connection closed after every response. The client opened a new connection without seeing any error, and each step left from a different IP. In the last row Requests reported the error as a proxy connection problem. The second order request with the same key did not create a new record.
The bottom line
Give each flow one sticky session ID and one cookie jar, measure how long the flow takes and build a retry that starts from login when the session drops. Above all, turn off redirects and check the response, because an IP change usually raises no error. For long jobs that need an uninterrupted address, use ISP Proxy.
Sources
- RFC 9110, HTTP Semantics, section 9.2.2 Idempotent Methods: rfc-editor.org
- OWASP Session Management Cheat Sheet, Binding the Session ID to Other User Properties: owasp.org
- The Idempotency-Key HTTP Header Field, IETF HTTPAPI draft: datatracker.ietf.org
- Requests Advanced Usage, Keep-Alive: requests.readthedocs.io
Frequently asked questions
Why does the site ask me to log in again when the proxy IP changes?
Because the site also ties the session to the IP address. When the same session cookie arrives from another IP, the site reads it as a sign that the session was hijacked and closes it. This is a security check. Pin the flow to one sticky session ID, choose a duration that fits the length of the flow and start again from login when the session drops.
I use a sticky session, so why did the IP still change?
Most likely the duration expired or the exit device left the network. After the duration expires, the first new connection gets a different exit. In residential and mobile pools, the session moves before the duration ends if the device drops off the network. Also check that the session ID in the username stays the same for the whole flow.
Does a flow that needs a login work with a rotating proxy?
Not reliably. While the connection stays open, requests go through one tunnel and the flow seems to work for a while. When the server or the proxy closes the connection, the client quietly opens a new one and a new IP arrives. In our test, with the connection closing after every response, the flow failed at the cart step in all three attempts. Use a sticky session for linked steps.
How do I detect an IP change in code?
In two ways. The first is to record the exit IP at the start of the flow and check it again over a new connection before critical steps. The second is to watch the responses: a redirect to the login page, a Set-Cookie that clears the session cookie, 401, 403, 419 and a currency change on the page. Turn redirects off, or the login page comes back as 200.
Can I continue from the step where the session dropped?
Usually not. The server has closed the session, so the old cookie and CSRF token are no longer valid. Start from login with a new ID. If the steps are idempotent, starting over does no harm: a PUT that writes the same quantity to the cart gives the same result even if it runs twice. For POST steps such as an order, use an Idempotency-Key or check the state first.
Is a price that changes with location the same problem?
Yes, it is the silent form of the same problem. If the new IP is in another city or country, the site may show a different price, currency or stock level. The flow raises no error, but the collected data gets mixed. Record a marker such as the currency on every page and check that it stays the same throughout the flow. If it changed, discard that run and collect again.




