Proxies for AI Agents: Sticky per Task, Rotating per Fetch

Route an AI agent's fetches and headless browser through proxies: one session per task, rotation per fetch, and which Node4 meter fits bursty traffic.

Give an AI agent a rotating proxy gateway and two routing rules: a session id for every multi-step task, so the agent's requests leave from one exit while that task runs, and a plain rotating connection for every tool call that stands alone. To choose a plan, estimate two numbers, the data the agent moves in a month and the most connections it holds open at once, and price both meters: on Node4 that is Rotating Datacenter, billed by the gigabyte, and Rotating Unmetered, billed by concurrent connections with no byte meter. Bursty traffic alone does not make the connection plan cheaper; a high peak over little data usually costs less by the gigabyte. Both draw datacenter exits that sites can classify as hosting addresses, so keep residential as the fallback for the targets that refuse them.

This guide covers the web side of an agent: the fetch tool, the calls it makes to third-party sites, and the headless browser it drives. MCP servers and credential brokers are separate integration layers, and some of them also provide hosted fetching; the last section names a few. Vendor pages and every code sample were checked on November 26, 2026. Bulk corpus collection has its own guide in best proxies for AI training data collection, and turning fetched pages into model input is covered in web page to Markdown for an LLM in Python.

Why does an agent get blocked when the same script did not?

An agent produces the traffic shape that rate limiters and bot defenses are tuned to catch, from an address class they already distrust. Four behaviors do it:

  • Fan-out. One research step opens ten or forty fetches at once, across several domains, from one address.
  • Retry storms. A model reads a 403 or an empty page as "try again". Without a cap, the agent retries in a tight loop and rate-limits itself.
  • Refetching. Without a URL or result cache, an agent can fetch the same page again even when the earlier fetch is still in its conversation history, and every repeat costs the same.
  • Cloud origin. Agents run on cloud hosts whose address ranges every defense can look up.

A proxy changes the last of these and spreads the first across many addresses. It does nothing about the other two, and it does not change every signal a site evaluates: TLS and HTTP fingerprints, request timing, session behavior and IP reputation can all affect the result. The retry storm needs a task budget around every tool, with a bounded retry policy; the Python and Node samples below enforce one in code, and the Playwright fragment needs the same budget and limiter around it, because a timeout or a BLOCKED string alone does not stop a model from calling again. A cache keyed by URL handles the refetching, and it is the first place to cut proxy spend, before any plan change. Why is my IP getting blocked shows how to read the response before changing anything.

Sticky session per task, or rotation per fetch?

Hold one exit for the length of a task that carries state, and let every stateless tool call pick its own. On Node4's rotating gateways the choice is made per request by the username you send, so one agent process can do both at once.

Agent tool callRouteWhy
fetch_page(url) on a public page, result used onceRotate: a new connection per call, so a new exit pickNo state to protect, and no single address carries the whole rate
Search, then open five resultsRotate each fetchThe results are independent pages
Paginate through a result setSticky: one session id for the walkSome sites bind the cursor to the address and restart at page one when it changes
Log in, then read account pagesSticky: one session id per account and attemptA login that moves address mid-task is what a stolen cookie looks like
Fill a multi-step form, set a delivery location, build a cartSticky for the flowThe server holds partial progress keyed to your session
Drive a headless browser through a page and its assetsSticky per browser contextA page load opens several connections in parallel; without a session the document and its scripts can arrive from different exits
Call a third-party JSON API with your own keyUsually direct, with no proxyCheck the API's key, account and IP limits first; use a stable approved egress address only when the integration requires one

The mechanics decide how to implement that. The gateway picks an exit once per connection: once per HTTPS tunnel or SOCKS5 connection, and once per request only on plain http:// targets. A client that keeps a tunnel alive sends every request down it from one exit, and a later pick can land on an address the agent had before, so a different address each time is not something to count on. To rotate, open a new connection per fetch. To hold an exit, add -session-<id> to the username: USERNAME-session-task4182 keeps one exit for up to 30 minutes from first assignment, and activity does not extend the window. On residential the pin is best effort with a 30-minute ceiling, and a failing exit needs a new id. Sticky vs rotating sessions covers what breaks when an exit changes mid-task.

Two rules for the id. Derive it from the task, so a retry of the same task rejoins the same exit and the same conversation with the target. When the failure was the exit itself, salt the id with the attempt number (task4182a2) so the retry is a fresh identity. Use letters and digits only. Because the window is counted from first assignment, an agent task that outlives it should finish a unit of work, mint a new id and continue, rather than resume a half-finished flow from a new address.

If the agent needs one identity held for hours, Node4 is the wrong buy. IPRoyal's residential proxies offer sticky sessions from 1 second up to 7 days, Decodo's sticky sessions of up to 24 hours, and on Oxylabs residential a sticky session lasts 10 minutes by default, and the sesstime parameter extends it up to 24 hours. On Node4, the way to keep one address for days is a dedicated datacenter proxy, a fixed address with no session machinery at all, which works where the target accepts datacenter addresses and not otherwise.

Per gigabyte or per connection: which meter fits agent traffic?

Price the month both ways and buy the lower bill. Node4 sells its rotating gateway on both meters, from one pool with exits in the United States, Italy and Spain, and residential on a third:

Rotating DatacenterRotating UnmeteredResidential
Billed byGigabyteConcurrent connections, no byte meterGigabyte
What to size byPages a month times page weightMost connections open at one momentPages a month times page weight
Smallest plan$5.90/month for 10 GB ($0.59/GB)$29.00/month for 250 connections ($0.116 per connection)$4.99/month for 3 GB ($1.66/GB)
ExitsDatacenter, US, Italy and SpainThe same pool as Rotating DatacenterConsumer connections in 160+ countries
Sticky sessionUp to 30 minutesUp to 30 minutesBest effort, 30-minute ceiling
FitsLow monthly transfer, even with a high peakHigh monthly transfer through a predictable peakTargets that refuse datacenter addresses

Those are Node4's standard monthly prices; the pricing pages list every size.

The meter matters more for an agent than for a scheduled scraper. A scraper's bandwidth is predictable, a page count times an average page weight, and a per-GB plan prices it well. An agent's bytes depend on choices the model makes at run time: a plain httpx fetch pulls the HTML document and nothing else, while a headless browser pulls every script, style and image the page references, and the agent decides step by step which one to use. What stays bounded is concurrency: the framework's parallel tool-call limit, or the size of your browser pool. A connection-priced plan turns that bounded number into a fixed monthly bill whatever the agent downloads, which pays off only when the downloads are large.

Two worked examples, both at standard monthly prices and both hypothetical workloads rather than measurements. A monitoring agent that opens 1,500 connections for a few minutes each hour and moves 20 GB a month fits a 25 GB Rotating Datacenter plan at $13.00/month for 25 GB ($0.52/GB); covering its peak by connections takes the 2,000-connection plan at $149.00/month for 2,000 connections ($0.074 per connection). A browser pool that never holds more than 200 connections but moves 200 GB a month needs four 50 GB plans at $23.50/month for 50 GB ($0.47/GB) each, against one 250-connection plan at $29.00/month for 250 connections ($0.116 per connection). Read your own transfer and peak from a day on the smallest plan before choosing.

Three things to get right on Rotating Unmetered, because the connection count is what you bought:

  1. Cap the agent's open connections at or below the plan's count, across the whole process. The limit belongs to the account: every credential, source address and protocol draws on it, and two plans on one account add together. A per-task or per-origin pool setting does not add up to an account-wide cap, so use one limiter shared by every task and origin and keep idle tunnels from piling up beside it. The Node sample below caps fetches in flight and closes each fetch's tunnel before freeing its slot, so it never holds more tunnels than that cap; leave headroom for browser subrequests.
  2. Idle kept-alive tunnels hold a slot. An HTTP client pool left open between agent steps can sit at the limit while sending nothing. Close each tunnel when its fetch ends, as the Node sample does; closing the client only when the task ends does not help a long task that keeps going.
  3. Tell the gateway's refusal from the target's. Over the limit, the gateway answers the next HTTP(S) connection with a 429 carrying an X-Node4-Conn-Limit header, before any exit is picked; a 429 from the target carries no Node4 header. On the SOCKS5 port the same refusal is reply code 0x02, which a wrong password also returns, so check the live connections panel to tell them apart. Back off for a second or two instead of retrying in a loop. Rotating Unmetered connection limits explains what counts and how to read the live connections panel.

How do you pass the proxy to the HTTP client the agent framework uses?

Configure the HTTP client the fetch tool uses, separately from the model-provider client. In LangChain, CrewAI, the OpenAI Agents SDK and a hand-written tool loop alike, the fetch inside a tool function is an ordinary HTTP client call; some frameworks and SDKs also expose transport settings, so check the version you run, and remember that configuring one client does not configure the other. Three patterns cover the common runtimes. The Python and Node samples were run on November 26, 2026 against a local test proxy that refuses HTTPS tunnels with a 429 or a 407, a local target that answers 200, 403 and 429, a hung proxy for the timeout, and through the real gateway with placeholder credentials; each returned the verdict its comments describe. The Playwright sample was run against the gateway, with the result noted under it. Replace USERNAME and PASSWORD with the proxy credential from Auth & IP Access under Account Settings; one credential works on every product your account holds an active plan for.

Python: one httpx client per task

import os
import httpx

GATEWAY = "gw-rotating_unmetered.node4.io:8084"
USER = os.environ["NODE4_USER"]
PASS = os.environ["NODE4_PASS"]
FETCHES_PER_TASK = 40  # the task's fetch budget; raise it on purpose, never from a retry loop


def proxy_url(task_id: str | None) -> str:
    # No task id: rotate, a fresh exit pick per connection.
    # A task id: hold one exit for the task, up to the gateway's sticky window.
    user = USER if task_id is None else f"{USER}-session-{task_id}"
    return f"http://{user}:{PASS}@{GATEWAY}"


class BudgetSpent(Exception):
    """The task used its fetch budget. Raised, not returned, so no retry gets past it."""


class FetchTool:
    """One instance per agent task: `with FetchTool(...) as tool:` closes it on any exit."""

    def __init__(self, task_id: str | None = None):
        self.budget = FETCHES_PER_TASK
        self.client = httpx.Client(
            proxy=proxy_url(task_id),
            timeout=30,
            follow_redirects=True,
            headers={"User-Agent": "Mozilla/5.0 (compatible; research-agent/1.0)"},
            # Without a session, disabling keep-alive opens a new tunnel per fetch,
            # so each fetch gets its own exit pick. With a session it does not matter.
            limits=httpx.Limits(max_keepalive_connections=0 if task_id is None else 20),
        )

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.client.close()

    def fetch(self, url: str) -> str:
        if self.budget == 0:
            raise BudgetSpent(f"fetch budget for this task is spent ({FETCHES_PER_TASK})")
        self.budget -= 1
        try:
            r = self.client.get(url)
        except httpx.ProxyError as e:
            # The GATEWAY refused the HTTPS tunnel before the target saw anything:
            # 429 is the plan's connection limit, 407 the credential. Not a target block.
            return f"PROXY_REFUSED {e} {url}"
        except httpx.TimeoutException:
            return f"TIMEOUT {url}"
        if r.status_code in (403, 429, 503):
            # The target's answer (or, on a plain http:// URL, the gateway's, which
            # carries an X-Node4-Conn-Limit header). Hand the model a verdict, not a page.
            who = "PROXY_REFUSED" if "x-node4-conn-limit" in r.headers else "BLOCKED"
            return f"{who} {r.status_code} {url}"
        r.raise_for_status()
        return r.text


if __name__ == "__main__":
    with FetchTool(task_id="task4182") as tool:
        print(tool.fetch("https://api.ipify.org"))

Tested with httpx 0.29; versions before 0.26 spell the argument proxies=. With requests, the equivalent is a Session whose proxies is {"http": url, "https": url}, closed at the end of the task; Python proxy integration has the full requests version. A gateway refusal on an https:// URL never reaches the status check: httpx raises httpx.ProxyError (407 Proxy Authentication Required with placeholder credentials, 429 Too Many Requests over the connection limit), which is why the tool catches it and reports PROXY_REFUSED instead of a target BLOCKED. requests raises a ProxyError ending in Tunnel connection failed: 407 Proxy Authentication Required in the same place. Keep any retry inside the task budget, and back off for a second or two after a 429 from the gateway.

Setting HTTP_PROXY and HTTPS_PROXY in the environment instead is tempting because it needs no code, and it is the wrong default for an agent. httpx and requests read those variables, and so does any SDK built on them, including model-provider SDKs. The agent's model calls would then hold connections on your plan, and on a per-GB plan their request and response bytes would count against the allowance. Keep model requests direct by default, unless your deployment requires an approved outbound proxy: put the proxy on the fetch tool as above, or add the provider's API host to NO_PROXY.

Node.js: fetch with an undici ProxyAgent

import { fetch, ProxyAgent } from "undici";

const GATEWAY = "gw-rotating_unmetered.node4.io:8084";
const { NODE4_USER, NODE4_PASS } = process.env;
const PLAN_CONNECTIONS = 250; // your Rotating Unmetered plan's count
const MAX_OPEN = PLAN_CONNECTIONS - 25; // headroom for anything else on the account
const FETCHES_PER_TASK = 40;

// ONE limiter for the whole process, shared by every task and every origin.
// Each fetch opens its own tunnel and closes it before giving the slot back,
// so open tunnels never exceed MAX_OPEN, and none sit idle between steps.
let open = 0;
const waiting = [];
async function withSlot(fn) {
  while (open >= MAX_OPEN) await new Promise((wake) => waiting.push(wake));
  open++;
  try {
    return await fn();
  } finally {
    open--;
    waiting.shift()?.();
  }
}

// One task: its own budget. No taskId rotates the exit per fetch; a taskId holds one exit.
export function startTask(taskId) {
  const user = taskId ? `${NODE4_USER}-session-${taskId}` : NODE4_USER;
  let budget = FETCHES_PER_TASK;

  return async function fetchTool(url) {
    if (budget <= 0) throw new Error(`fetch budget for this task is spent (${FETCHES_PER_TASK})`);
    budget--;
    return withSlot(async () => {
      const dispatcher = new ProxyAgent({ uri: `http://${user}:${NODE4_PASS}@${GATEWAY}` });
      try {
        const res = await fetch(url, { dispatcher, signal: AbortSignal.timeout(30_000) });
        if ([403, 429, 503].includes(res.status)) {
          await res.body?.cancel();
          const who = res.headers.has("x-node4-conn-limit") ? "PROXY_REFUSED" : "BLOCKED";
          return `${who} ${res.status} ${url}`;
        }
        return await res.text();
      } catch (err) {
        // A refused HTTPS tunnel never becomes a response: the gateway's status
        // (429 connection limit, 407 credential) is two causes deep.
        const detail = String(err?.cause?.cause?.message ?? err?.cause?.message ?? err?.message);
        const refused = detail.match(/Proxy response \((\d{3})\)/);
        if (refused) return `PROXY_REFUSED ${refused[1]} ${url}`;
        if (err?.name === "TimeoutError") return `TIMEOUT ${url}`;
        throw err;
      } finally {
        await dispatcher.destroy(); // the tunnel closes here, before the slot is released
      }
    });
  };
}

const fetchTool = startTask("task4182");
console.log(await fetchTool("https://api.ipify.org"));

Tested with undici 8.13 on Node 24. Node's built-in fetch is undici, so the dispatcher option is the same there. A refused tunnel rejects with TypeError: fetch failed, whose cause says only that the request was canceled; the gateway's status sits one level deeper, in err.cause.cause.message, as Proxy response (407) !== 200 when HTTP Tunneling (or (429) over the connection limit), which is what the catch block reads. ProxyAgent's own connections option caps sockets per origin, so on its own it does not bound a task that fans out across domains, and a kept-alive pool holds idle tunnels between steps. Here every fetch gets its own dispatcher, destroyed before withSlot releases its slot, so the client never holds more tunnels than fetches in flight, whatever the number of tasks and origins, and none stay open between steps. The gateway can still count a closing tunnel for about a round trip after the client drops it, which is what the headroom in MAX_OPEN is for. In the local test, with the limit set to 5, three tasks fanning out over three origins never had more than 5 fetches in flight; because those fetches finished in about a millisecond, the test proxy briefly saw up to 8 connections while closed ones were still arriving, and the count was back to 0 after each fetch of a sequential task. The cost is a new tunnel per fetch, which on a rotating gateway is also what gives each stateless fetch its own exit. Node.js proxy setup covers got, node-fetch, axios and the https module.

Playwright: one browser context per task

import os
from playwright.sync_api import sync_playwright

GATEWAY = "http://gw-rotating_unmetered.node4.io:8084"
USER = os.environ["NODE4_USER"]
PASS = os.environ["NODE4_PASS"]


# This fragment has no budget of its own: call it from a task controller that
# counts navigations and holds a slot in the same process-wide limiter. The
# 30-second goto timeout bounds one navigation, not the task.
def browse_task(browser, task_id: str, url: str) -> str:
    # One context per task: its own cookies, and one exit for every connection it opens.
    context = browser.new_context(proxy={
        "server": GATEWAY,
        "username": f"{USER}-session-{task_id}",
        "password": PASS,
    })
    try:
        page = context.new_page()
        resp = page.goto(url, wait_until="domcontentloaded", timeout=30000)
        if resp is None or resp.status >= 400:
            return f"BLOCKED {resp.status if resp else 'no response'} {url}"
        return page.inner_text("body")
    finally:
        context.close()


with sync_playwright() as p:
    browser = p.chromium.launch()
    print(browse_task(browser, "task4182", "https://api.ipify.org")[:200])
    browser.close()

The Node API takes the same proxy object in browser.newContext. One Chromium quirk to know before you debug a timeout: with a wrong or missing password, an https:// page does not report a 407; page.goto waits and fails with Timeout 30000ms exceeded, while a plain http:// page returns a response with status 407. Both happened in the test run. When the first navigation through a new proxy times out, check the credential with curl before anything else:

curl -q --noproxy '' --max-time 30 -x "http://USERNAME-session-task4182:PASSWORD@gw-rotating_unmetered.node4.io:8084" https://api.ipify.org

Run it twice and both lines print the same address while the session lives. Each browser context should visit an IP-echo page once at the start of a task and log the exit, so a mid-task change shows up in your logs rather than in the output. Puppeteer and Playwright proxies covers Puppeteer's page.authenticate, SOCKS5 and WebRTC leaks.

A browser sends its proxy login only after the proxy asks for one, so an agent host whose address is on your IP whitelist is never asked, and the session and country segments in the username never reach the gateway. IP whitelisting works on every product, and that is what it costs here: on the rotating gateways a whitelisted connection keeps targeting only if you send the username with an empty password, and on residential a whitelisted connection is untargeted because the username is where targeting lives. httpx, undici and curl send the credential without waiting to be asked, so the samples above keep their sessions from a whitelisted address; a browser context that needs a session has to run from an address that is not whitelisted. Authentication sets out both modes.

Where do datacenter exits fail, and when is residential the fallback?

Every Node4 rotating exit is a datacenter address from blocks Node4 owns, and an IP-intelligence lookup reports it as hosting. Many targets never check: documentation, most public APIs, news and the long tail of the web. Some targets reject hosting ranges outright, and rotating across more addresses of the same class does not change that verdict; others weigh several signals, so the address class is only part of the answer. Route by target rather than by agent: datacenter by default, and when your own test shows datacenter exits refused, compare a residential exit with the same client and the same permitted task before changing plans. Block replay requests one URL through a datacenter exit and a residential exit at the same time and reports whether the two answers differ, which is the test to run before paying for either.

On Node4, residential is gw-residential.node4.io on port 8082 (SOCKS5 on 1082), with the same credential. Targeting rides in the username as segments: USERNAME-country-de-session-task4182 holds one German exit for the task, and state, city and asn narrow it further. The residential parser is strict, so a misspelled key is a 400 that names it, and a country with no exits is refused with a 502 rather than served from somewhere else. Residential country and city targeting has the grammar.

Residential is billed per gigabyte, so page weight is the cost. Fetch the HTML document without a browser wherever the page allows it, reserve the browser for pages that render client-side, and cache. Node4's smallest residential plan is $4.99/month for 3 GB ($1.66/GB), enough to find out whether residential is needed at all before buying volume. At the size Proxidize's page on proxies for AI agents quotes as its starting residential plan, $25 a month for 25 GB, or $1 a GB, on its Lite residential plan, renewing monthly until canceled, with KYC identity verification required before the proxies can be used, Node4's plan for the same allocation is $19.99/month for 25 GB ($0.79/GB), the lower bill of the two, bought self-serve with no KYC step; the per-gigabyte rate falls further on each larger Node4 plan, and the pricing page lists every size.

What Node4 sells an agent builder, and what it does not

Node4 sells the network layer:

  • One account credential, over HTTP(S) or SOCKS5, against three gateway hostnames, valid on every product the account holds an active plan for.
  • Same-type plans stack, so capacity is added without changing a connection string.
  • Rotating Unmetered carries no byte meter, so a browser pool's download volume never changes the bill.
  • Ready-made proxy strings for a country or a sticky session from the REST API at https://node4.io/api/v1 (GET /gateways/endpoint), which a tool can call instead of assembling usernames by hand.

The free tier is static shared datacenter over HTTP(S) only and cannot reach the gateways, so evaluating any of this needs the smallest paid plan, paid by card, PayPal, Bitcoin or USDT (TRC-20) and refundable in full within 7 days of a first purchase whichever way you paid (free trial and refund period).

What it does not sell, each of which another vendor does:

Buy Node4 for an agent whose targets mostly accept datacenter addresses and whose tasks finish inside the sticky window, on whichever meter prices its month lower: by the gigabyte for light transfer, by connection for heavy transfer through a predictable peak. Buy elsewhere for a day-long single identity, for mobile or ISP addresses, or when you want the vendor's agent tooling to do the fetching for you.

Proxies for AI agents FAQ

Do AI agents need proxies? Not always. An agent that fetches public pages from a cloud host may meet rate limits or hosting-IP blocks, depending on its targets and request pattern, and a rotating proxy spreads its requests across many exits. Test the intended workload first. An agent that only calls keyed APIs and its model provider usually does not need one, unless an integration requires an approved egress address.

Which proxy type fits AI agents? Rotating datacenter exits by default, with a session id per stateful task; residential for the targets that refuse datacenter addresses, chosen per target after a test such as block replay. Price both meters from the agent's monthly transfer and its peak connections, and buy the lower bill.

Should the agent's model API calls go through the proxy? Usually not. Keep them direct by default unless your deployment requires an approved outbound proxy: through the proxy they hold connections on your plan and, on a per-GB plan, their request and response bytes count against the allowance. Keep the proxy on the fetch tool, or add the provider's host to NO_PROXY.

Can a chat assistant scrape a site through my proxy? The hosted assistants fetch from their own infrastructure and take no proxy setting of yours. Proxies apply to the agents you run, where the fetch happens in your code.

How many concurrent connections does an agent need? Start from the framework's parallel tool-call limit times the connections each call opens: one for an httpx fetch, several for a browser page load. Run that for a day on the smallest plan, read the peak on the live connections panel, and add a plan if connections were turned away; same-type plans stack.

Is it legal for an agent to scrape with proxies? Public visibility alone does not settle whether collection is permitted, and using a proxy does not change the answer. It depends on the jurisdiction, any access controls, the terms you agreed to, personal data, and copyright or database rights, so review those conditions for the planned use. Is it legal to use proxies for web scraping covers the detail.

Does Node4 have an MCP server? No. The REST API at https://node4.io/api/v1 returns proxy strings, usage and live connection counts, and a tool in your agent can call it; there is no MCP wrapper.

Can I test this on the free tier? No. The free tier is static shared datacenter proxies over HTTP(S) and cannot reach the rotating or residential gateways, so a test needs the smallest paid plan of the product you are considering.