Running a Scraper on a VPS with Residential Proxies: Setup, Sticky Sessions and a Traffic Estimate

Running a Scraper on a VPS with Residential Proxies: Setup, Sticky Sessions and a Traffic Estimate

  1. Home
  2. Blogs
  3. Running a Scraper on a VPS with Residential Proxies: Setup, Sticky Sessions and a Traffic Estimate

A scraper that runs on a laptop stops when the lid closes, the Wi-Fi drops or the system restarts for updates. Moving it to a VPS makes it far more available — the server keeps running when your own machine does not — although no server guarantees 100% uptime, so the job should still handle failures and restarts gracefully. Residential proxies cover the network side: requests leave from residential IPs in the country you choose, with rotating or sticky sessions. This guide walks through a practical setup: a Linux VPS, a Python scraper, SmartProxy.ai residential proxies, responsible retry handling and a way to estimate how much proxy traffic you will need.

1. Pick the server

For a typical Python scraper with requests or httpx and a few hundred to a few thousand pages per hour, the bottleneck is usually the network and the target site, not the CPU. The sizes below are starting points — benchmark your own job and resize.

Workload

Suggested starting VPS

Why

1–3 scripts, plain HTML pages

1–2 vCPU, 2–4 GB RAM

Enough for async HTTP requests and parsing

Several scrapers + a database (PostgreSQL/SQLite)

2–4 vCPU, 4–8 GB RAM

Room for the DB cache and parallel workers

Headless browsers (Playwright, Puppeteer)

4+ vCPU, 8+ GB RAM

Each Chromium instance takes roughly 200–500 MB

Location: the proxy decides which country the target site sees; the VPS location affects the latency between your code and the proxy gateway. Total latency is the sum of both legs — VPS → gateway and proxy exit → target — so a nearby gateway helps, but the target’s distance from the exit IP matters too. PSB Hosting VPS plans start from 1 vCPU / 2 GB; for CPU-heavy parsing or many headless browsers, Hi-CPU VPS on Ryzen 9 7950X are a better fit.

2. Prepare the VPS

Ubuntu 24.04 or Debian 12 are good defaults.

apt update && apt upgrade -y
apt install -y python3-venv python3-pip
adduser scraper && su - scraper
python3 -m venv ~/venv && source ~/venv/bin/activate
pip install "httpx[http2]" selectolax

3. Get the connection details from SmartProxy.ai

In the SmartProxy.ai dashboard open Proxy Setup → Residential Proxy → User·Pass Auth. There you choose the country, the session type (rotating or sticky) and, for sticky sessions, the session lifetime; the dashboard then generates the host, port, username and password.

SmartProxy.ai dashboard: Proxy Setup → Residential Proxy → User·Pass Auth

SmartProxy.ai dashboard: Proxy Setup → Residential Proxy → User·Pass Auth

An example of what the generator produces for a Russian exit IP with a 5-minute sticky session (the values below are fictitious — use the ones from your own account):

Host:      proxy.smartproxy.net
Port:      3120
Username:  smart-DEMOUSER_area-RU_life-5_session-demo123
Password:  DEMO_PASSWORD

The country (area-RU), lifetime (life-5) and session ID (session-demo123) are already part of the generated username. Use the full username exactly as generated — do not append your own -session-… suffix. For a different country, lifetime or session, generate a new username in the dashboard.

Keep credentials out of the code — put them in a shell-compatible environment file (comments on their own lines, no spaces around =):

cat > ~/.proxy.env <<'ENV'
# Values from SmartProxy.ai: Proxy Setup > Residential Proxy > User·Pass Auth
PROXY_HOST=proxy.smartproxy.net
PROXY_PORT=3120
PROXY_USER=smart-DEMOUSER_area-RU_life-5_session-demo123
PROXY_PASS=DEMO_PASSWORD
ENV
chmod 600 ~/.proxy.env

To run the scraper manually, export the variables into the current shell first (the systemd service in section 6 loads the same file through EnvironmentFile, so this step is only for manual runs):

set -a; . ~/.proxy.env; set +a
python ~/scraper.py

Quick check from the VPS that the proxy works (some networks block outgoing proxy ports):

curl -x "http://$PROXY_HOST:$PROXY_PORT" -U "$PROXY_USER:$PROXY_PASS" https://httpbin.org/ip

4. Rotating vs sticky sessions

Both are modes of the SmartProxy.ai gateway, selected when you generate the username:

  • Rotating — the gateway assigns exit IPs from the pool and changes them over time. Use it for catalogues, search results and other pages where requests are independent. Do not build logic on the assumption that every single request or retry gets a new IP.

  • Sticky — the gateway tries to keep the same exit IP for the session lifetime you chose (for example, 5 minutes). Use it when a sequence of requests must look like one visitor: pagination with cookies, a login, a cart. A residential peer can go offline, so a sticky session can still change IP before the lifetime ends — make multi-step flows tolerant of that.

5. A minimal scraper with careful retries

import os, random, asyncio
from urllib.parse import quote
import httpx
from selectolax.parser import HTMLParser

H, P = os.environ["PROXY_HOST"], os.environ["PROXY_PORT"]
U, W = os.environ["PROXY_USER"], os.environ["PROXY_PASS"]   # full generated username

# URL-encode the credentials: special characters would otherwise break the URL.
PROXY = f"http://{quote(U, safe='')}:{quote(W, safe='')}@{H}:{P}"

HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                         "(KHTML, like Gecko) Chrome/131.0 Safari/537.36",
           "Accept-Language": "en-US,en;q=0.9"}

TEMPORARY = {500, 502, 503, 504}   # worth a limited retry
MAX_TRIES = 3

class StopScraping(Exception):
    """Access problem that retries will not fix."""

async def fetch(client: httpx.AsyncClient, url: str, rate: dict) -> str | None:
    for attempt in range(1, MAX_TRIES + 1):
        try:
            r = await client.get(url)
        except (httpx.ConnectError, httpx.ReadTimeout):
            await asyncio.sleep(2 ** attempt)           # temporary network issue
            continue
        if r.status_code == 407:
            raise StopScraping("proxy auth failed (407): check username/password")
        if r.status_code == 403:
            raise StopScraping(f"403 on {url}: stop and check the site's access terms")
        if r.status_code == 429:
            wait = int(r.headers.get("Retry-After", "60"))
            rate["delay"] = min(rate["delay"] * 2, 30)  # slow down for the rest of the run
            await asyncio.sleep(wait)
            continue
        if r.status_code in TEMPORARY:
            await asyncio.sleep(2 ** attempt)
            continue
        r.raise_for_status()                            # other 4xx: no retry
        return r.text
    return None                                         # give up on this URL, log it

async def main(urls):
    rate = {"delay": 1.0}
    sem = asyncio.Semaphore(5)                          # concurrency limit
    # One client for the whole run: keeps the connection pool and the cookie jar,
    # so a multi-step sticky flow keeps its cookies between requests.
    async with httpx.AsyncClient(proxy=PROXY, headers=HEADERS, timeout=30,
                                 http2=True, follow_redirects=True) as client:
        async def one(u):
            async with sem:
                html = await fetch(client, u, rate)
                if html:
                    title = HTMLParser(html).css_first("title")
                    print(u, title.text() if title else "-")
                else:
                    print(u, "FAILED")
                await asyncio.sleep(rate["delay"] * random.uniform(0.5, 1.5))
        await asyncio.gather(*(one(u) for u in urls))

if __name__ == "__main__":
    asyncio.run(main([f"https://example.com/catalog?page={i}" for i in range(1, 51)]))

What matters here:

  • One AsyncClient per run (or per sticky flow). Creating a new client for every request throws away connections and cookies. For a multi-step sticky scenario — open a page, paginate, add to cart — use one client with one sticky username for all steps. The same session ID alone does not preserve a login — the cookies live in the client.

  • Retries only for temporary errors, and only a few: timeouts, connection errors and 5xx.

  • 429 means “too fast”. Respect Retry-After and lower the request rate for the rest of the run.

  • 403 means “stop”. It usually signals that access is restricted; check the site’s terms and robots rules instead of retrying.

  • Authentication errors (407) are never retried — fix the credentials.

Changing IPs is not a way around bans or rate limits. Scrape only what you are allowed to, keep the request rate reasonable and follow the target site’s terms.

6. Run it on a schedule with systemd

The example processes 50 pages and exits, so it should run as a oneshot service triggered by a timer, not as an always-restarting daemon.

# /etc/systemd/system/scraper.service
[Unit]
Description=Catalog scraper (one batch)
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
User=scraper
EnvironmentFile=/home/scraper/.proxy.env
ExecStart=/home/scraper/venv/bin/python /home/scraper/scraper.py
# /etc/systemd/system/scraper.timer
[Unit]
Description=Run the catalog scraper every 6 hours

[Timer]
OnCalendar=*-*-* 00/6:00:00
RandomizedDelaySec=300
Persistent=true

[Install]
WantedBy=timers.target
systemctl daemon-reload && systemctl enable --now scraper.timer
systemctl list-timers scraper.timer
journalctl -u scraper -n 100

Persistent=true runs a missed batch after a reboot. If instead you have a long-lived worker that processes a queue continuously, use a regular service with Restart=on-failure and RestartSec=30 — it restarts after crashes but not after a clean exit.

7. Estimating proxy traffic

Residential proxies are usually billed by traffic, so estimate before you start. The formula:

Traffic per month = pages per run × average transfer size per page × (1 + extra requests per page) × runs per month

Assumptions for an example (decimal units: 1 KB = 1,000 bytes, 1 GB = 1,000,000 KB):

  • 20,000 product pages per run;

  • 150 KB average transfer size per page — the compressed (gzip/brotli) HTML response as it travels over the network, without images, scripts or CSS, which plain HTTP clients do not load;

  • 0.1 extra requests per page on average (retries, redirects);

  • 4 runs per day → 120 runs per month.

20,000 × 150 KB × 1.1 × 120 = 396,000,000 KB ≈ 396 GB per month — an estimate, not a quote.

Three numbers are easy to mix up:

  • Transferred bytes — what actually crosses the network, compressed, plus headers and TLS overhead. This is closest to what a proxy meters.

  • Decoded size — the HTML after decompression, as your code sees it (len(r.content)). It is often 3–8× larger than the transfer size, so measuring it would overstate the estimate.

  • Billed traffic — what your plan actually counts. Check SmartProxy.ai’s terms for how upload, download and overhead are counted.

Run a sample of a few hundred pages, compare the dashboard’s usage with your estimate, then scale.

The same job with a headless browser that loads full pages (1.5–3 MB each) would need 10–20× more traffic — one more reason to use plain HTTP requests where possible. Ways to cut the number:

  • request only the HTML (block images, fonts and media in headless browsers);

  • use the site’s JSON endpoints when they exist and are permitted — they are often much lighter than HTML;

  • scrape only changed pages (compare sitemaps, ETag/Last-Modified);

  • keep extra requests low with sensible rates and delays.

Check current per-GB pricing and plan types (residential, static residential, ISP, unlimited) on SmartProxy.ai and compare with your estimate.

8. Monitoring

Log the status code, response size and time for every request. A rise in 429/403, a drop in average page size (error and captcha pages are small) or growing latency are signals to slow down, review the access terms or adjust the setup — not to push harder.

Related articles

FlashID Review 2026: Anti-Detect Browser for Managing Multiple Accounts at Scale

FlashID Review 2026: Anti-Detect Browser for Managing Multiple Accounts at Scale

Partner content: FlashID. In today’s hyperconnected world, cross-border e-commerce and social media marketing have become essential growth drivers for modern businesses. However, global teams

Testing Ads and Apps for Southeast Asia: a VPS Plus a Singapore Mobile IP

Testing Ads and Apps for Southeast Asia: a VPS Plus a Singapore Mobile IP

If you run ads or launch an app for Southeast Asia, what you see from your office is not what your users see. Ad networks, app stores and many websites show different creatives, prices, languages and

How to Add the DiveChat Live Chat to a Website on a VPS

How to Add the DiveChat Live Chat to a Website on a VPS

Partner guide: PSB Hosting × DiveChat. A live chat on your website gives visitors a quick way to ask a question at the moment they are ready to buy, instead of filling in a form and waiting. If

403 Forbidden Error: Causes and How to Fix It

403 Forbidden Error: Causes and How to Fix It

A 403 Forbidden error means the server understood the request but refuses to fulfil it: access to the page or file is not allowed. Unlike 5xx errors, the server is working here — it has simply d

9HTTP: Global Proxy IP Solutions for Cross-Border Business and AI Applications

9HTTP: Global Proxy IP Solutions for Cross-Border Business and AI Applications

Partner content: 9HTTP. As businesses expand into global markets, data collection, market research, SEO monitoring, ad verification, and AI-related applications require increasingly diverse network e

504 Gateway Timeout and Error 524: Causes and How to Fix Them

504 Gateway Timeout and Error 524: Causes and How to Fix Them

Errors 504 and 524 mean essentially the same thing: the server took too long to respond and the intermediary stopped waiting. The difference is who gave up waiting — your web server or Cloudflar

How to Automate CAPTCHA Solving on a VPS with CaptchaAI

How to Automate CAPTCHA Solving on a VPS with CaptchaAI

Partner content. Prepared by the CaptchaAI team. Moving an automation project to a VPS solves one problem: the application no longer depends on someone keeping a laptop open. But a server that sta

VPN vs VPS: What's the Difference and Which One Do You Need?

VPN vs VPS: What's the Difference and Which One Do You Need?

VPN and VPS are easy to mix up: the abbreviations look alike, and both come up in conversations about servers and security. In reality they are completely different things. Let's look at the differenc

Mobile Proxies on a VPS: Building Reliable Workflows for Social Media and Automation

Mobile Proxies on a VPS: Building Reliable Workflows for Social Media and Automation

Teams that manage dozens of social media accounts or run automation eventually arrive at the same setup: a server that runs 24/7 and mobile proxies that carry that traffic to the internet. Here is how

Telegram