Residential proxies are usually billed per gigabyte, so the two questions people ask before starting a data project are “how do I wire the proxy into my scraper?” and “how much traffic will it actually use?”. This guide answers both for ProxySale on a Linux VPS: choosing the authentication method, keeping credentials out of code, running a Scrapy project on a schedule, and turning a small test crawl into a monthly traffic estimate with every assumption written down.
A VPS helps here because it is online when your laptop is not and has a fixed public IP — which matters for one of the two ways ProxySale lets you authorise connections. It improves availability, but no server is immune to restarts or network issues, so the job is built to fail safely and resume on the next run.
1. What you need
A VPS. For a Scrapy project of a few hundred thousand pages per month, 1–2 vCPU and 2 GB RAM is a reasonable starting point; HTML parsing at high concurrency or headless browsers need more (see the companion sizing guide). PSB Hosting VPS plans start from 1 vCPU / 2 GB; for CPU-heavy parsing, Hi-CPU VPS run on Ryzen 9 7950X.
A ProxySale plan. ProxySale offers rotating residential traffic, unlimited residential (time-based), long-acting ISP, static residential and static datacenter proxies, over HTTP(S) and SOCKS5. This guide uses rotating residential traffic, because that is where a traffic estimate matters most.
Permission to collect the data. Check the target site’s terms and robots rules before you start. ProxySale also blocks some site categories by policy, so confirm your target is supported.
2. Choose an authentication method
In the ProxySale dashboard, both methods live under Get Proxy:
Method | Where | How it works | Good for |
|---|---|---|---|
Username & password | Get Proxy → User | You pick country, city, session time and other parameters, click Generate and copy the generated credentials | Most setups; works from any machine |
IP whitelist | Get Proxy → Whitelist | After adding the VPS IP to the whitelist, you generate an extraction API link | A VPS with a fixed IP; no password stored on the server |
A practical tip for budgeting: under Get Proxy → Sub-account you can create a separate authentication account per project and set a traffic limit on it. A sub-account per scraper means the dashboard shows usage per project, and a bug that loops on one site cannot burn through the whole balance.
The rest of this guide uses username & password, because it is the same on every machine. Whatever parameters you choose in the generator (country, city, session time), use the generated username exactly as shown — don’t edit or append parameters by hand; generate a new one instead.
3. Prepare the VPS
apt update && apt upgrade -y
apt install -y python3-venv
adduser scraper && su - scraper
python3 -m venv ~/venv && source ~/venv/bin/activate
pip install scrapy
scrapy startproject prices && cd pricesStore the connection details in a shell-compatible environment file — one KEY=value per line, comments on their own lines:
cat > ~/.proxy.env <<'ENV'
# From ProxySale: Get Proxy > User (or a sub-account for this project)
# Replace the placeholders with the generated values.
# If a value contains spaces or shell characters ($ ` \\ " ! etc.), wrap it in single quotes: PROXY_PASS='value'
PROXY_HOST=HOST_FROM_GENERATOR
PROXY_PORT=PORT_FROM_GENERATOR
PROXY_USER=FULL_GENERATED_USERNAME
PROXY_PASS=YOUR_PASSWORD
ENV
chmod 600 ~/.proxy.envFor manual runs, load it into the current shell (the systemd unit in section 7 reads the same file with EnvironmentFile):
set -a; . ~/.proxy.env; set +a
curl -x "http://$PROXY_HOST:$PROXY_PORT" -U "$PROXY_USER:$PROXY_PASS" https://httpbin.org/ipIf the curl check prints an IP from the country you selected, the proxy works from this server. A 407 means the credentials are wrong; a timeout can mean the VPS network blocks the proxy port.
4. Wire the proxy into Scrapy
Scrapy’s built-in HttpProxyMiddleware uses the proxy key in request.meta. A tiny downloader middleware sets it for every request — including Scrapy’s own robots.txt requests — and URL-encodes the username and password so special characters don’t break the URL.
# prices/prices/proxy.py
import os
from urllib.parse import quote
def proxy_url() -> str:
user = quote(os.environ["PROXY_USER"], safe="")
pwd = quote(os.environ["PROXY_PASS"], safe="")
return f"http://{user}:{pwd}@{os.environ['PROXY_HOST']}:{os.environ['PROXY_PORT']}"
class ProxyFromEnv:
"""Downloader middleware: route every request through the ProxySale gateway."""
def __init__(self):
self.proxy = proxy_url()
def process_request(self, request, spider):
request.meta.setdefault("proxy", self.proxy)# prices/prices/spiders/catalog.py
import scrapy
from scrapy.exceptions import CloseSpider
class CatalogSpider(scrapy.Spider):
name = "catalog"
start_urls = ["https://example.com/catalog?page=1"]
custom_settings = {"HTTPERROR_ALLOWED_CODES": [403, 407]} # let us see them in parse()
def parse(self, response):
if response.status == 407:
raise CloseSpider("proxy authentication failed (407) - check credentials")
if response.status == 403:
raise CloseSpider(f"403 on {response.url} - stop and check the site's access terms")
for card in response.css("div.product"):
yield {"url": response.urljoin(card.css("a::attr(href)").get()),
"title": card.css("h2::text").get(),
"price": card.css(".price::text").get()}
next_page = response.css("a.next::attr(href)").get()
if next_page:
yield response.follow(next_page)Settings that keep the crawl polite and the retries bounded:
# prices/prices/settings.py (relevant lines)
ROBOTSTXT_OBEY = True
CONCURRENT_REQUESTS_PER_DOMAIN = 4
DOWNLOAD_DELAY = 1.0
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0
RETRY_ENABLED = True
RETRY_TIMES = 2 # at most 2 extra attempts
RETRY_HTTP_CODES = [500, 502, 503, 504, 408] # temporary errors only; no 403/407/429
DOWNLOADER_MIDDLEWARES = {
"prices.proxy.ProxyFromEnv": 740, # before HttpProxyMiddleware (750)
"prices.middlewares.RespectRetryAfter": 560,
}429 Too Many Requests gets its own handling: the whole crawl pauses until the latest Retry-After deadline (one shared cooldown, so a short wait never cuts a longer one), the request is retried at most twice, and then dropped. The same middleware stops proxy authentication failures from being retried:
# prices/prices/middlewares.py
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from scrapy.core.downloader.handlers.http11 import TunnelError
from scrapy.http import Response
def retry_after_seconds(value: bytes | None, default: int = 60) -> int:
if not value:
return default
v = value.decode().strip()
if v.isdigit():
return int(v)
try: # HTTP-date form
delta = parsedate_to_datetime(v) - datetime.now(timezone.utc)
return max(int(delta.total_seconds()), 1)
except (TypeError, ValueError):
return default
class RespectRetryAfter:
"""429: one shared cooldown for the whole crawl. 407 via CONNECT: no retries."""
def __init__(self, crawler):
self.crawler = crawler
self.resume_at = 0.0 # latest deadline requested by any 429
self.paused = False
@classmethod
def from_crawler(cls, crawler):
return cls(crawler)
def _schedule_resume(self):
from twisted.internet import reactor # imported here, after Scrapy has installed its reactor
reactor.callLater(max(self.resume_at - time.monotonic(), 0), self._try_resume)
def _try_resume(self):
if time.monotonic() < self.resume_at: # a later 429 extended the cooldown
self._schedule_resume()
return
self.paused = False
self.crawler.engine.unpause()
def process_response(self, request, response, spider):
if response.status != 429:
return response
tries = request.meta.get("tries_429", 0)
if tries >= 2:
spider.logger.warning("429 persists on %s - giving up on this URL", request.url)
return response
wait = retry_after_seconds(response.headers.get(b"Retry-After"))
self.resume_at = max(self.resume_at, time.monotonic() + wait)
if not self.paused:
self.paused = True
spider.logger.info("429 - pausing the crawl for at least %s s", wait)
self.crawler.engine.pause()
self._schedule_resume()
retry = request.replace(dont_filter=True)
retry.meta["tries_429"] = tries + 1
return retry
def process_exception(self, request, exception, spider):
# For HTTPS targets the proxy rejects the CONNECT tunnel itself, so a wrong
# password arrives as TunnelError, not as a 407 response. Turn it into a 407
# response before RetryMiddleware sees it, so parse() stops the crawl.
if isinstance(exception, TunnelError) and "407" in str(exception):
return Response(request.url, status=407, request=request)
return NoneWhy these rules:
Retries only for temporary failures (timeouts, 5xx), and only a couple of times.
429 means “slow down”: honour
Retry-After, and if 429s keep appearing, lowerCONCURRENT_REQUESTS_PER_DOMAINor raiseDOWNLOAD_DELAYfor the next run.403 means “stop”: the site is refusing access; check its terms rather than retrying.
407 is never retried: it is a credentials problem. For HTTPS targets the proxy rejects the CONNECT tunnel, so it arrives as an exception rather than a response — the middleware converts it to 407 before the retry logic sees it.
Rotating residential IPs are not a way around bans or rate limits. If a site limits you, the fix is a lower rate or permission, not more IPs.
Multi-step flows. If a sequence must look like one visitor (pagination behind a cookie, a filtered search), generate a sticky-session username in Get Proxy → User and use it for every request in that flow. Scrapy’s cookie middleware keeps cookies per cookiejar meta key, so give each flow its own meta={"cookiejar": n} and set meta["proxy"] to a proxy URL built from the sticky username — ProxyFromEnv only fills in the default when proxy is not already set. A sticky session is “best effort”: a residential peer can go offline, so the IP may change before the session time ends — make the flow tolerant of that.
5. Run a test crawl and read the traffic numbers
Before committing to a plan size, run a sample:
set -a; . ~/.proxy.env; set +a
scrapy crawl catalog -s CLOSESPIDER_PAGECOUNT=500 -O sample.jsonl 2>&1 | tee sample.log
grep -E "response_bytes|response_count|request_bytes|retry/count|redirect" sample.logScrapy prints stats at the end. The lines below are an illustrative sample (not a measurement of a specific site) — your own run will give your numbers:
'downloader/request_bytes': 594000,
'downloader/response_bytes': 41500000,
'downloader/response_count': 540,
'retry/count': 25,
'downloader/response_status_count/301': 15,What they mean:
downloader/response_bytes— bytes received from the proxy for responses (headers plus the body as it arrived, before Scrapy decompresses it with the default middleware order). This is the closest figure in Scrapy to what crosses the network.downloader/request_bytes— bytes sent (requests are small, but they count as traffic too).retry/countand redirects — extra requests on top of the pages you wanted.
6. The worked traffic estimate
Assumptions (all decimal units: 1 KB = 1,000 bytes, 1 GB = 1,000,000 KB):
Assumption | Value | Where it comes from |
|---|---|---|
Pages per day | 30,000 | 6 runs × 5,000 product pages |
Days per month | 30 | |
Average transferred size per response | 76.9 KB | 41,500,000 bytes ÷ 540 responses in the illustrative sample (compressed HTML + headers) |
Extra requests per page | 0.08 | (25 retries + 15 redirects) ÷ 500 pages |
Upload per request | 1.1 KB | 594,000 bytes ÷ 540 requests (request headers) |
Safety margin | 15% | layout changes, more retries on bad days |
Calculation:
Requests per month: 30,000 × 30 × 1.08 = 972,000
Download: 972,000 × 76.9 KB ≈ 74.7 GB
Upload: 972,000 × 1.1 KB ≈ 1.1 GB
Subtotal: ≈ 75.8 GB; with a 15% margin ≈ 87 GB per month
So this project fits a 100 GB package with a little room, and a sub-account limit of ~90 GB would stop a runaway crawl before it eats into other projects.
What the estimate does and doesn’t include:
Transferred vs decoded size. The estimate uses compressed transfer size. The decompressed HTML your parser sees is often several times larger — sizing by
len(response.body)would overstate traffic.Billed traffic. What the plan counts can differ slightly from what Scrapy measures (TLS overhead, connection setup, upload counting). After the first few runs, compare the dashboard usage with your estimate and adjust the per-page figure.
Headless browsers load images, scripts and fonts; the same 30,000 pages could need 10–20× more traffic. Use plain HTTP requests where possible and block media if you must render pages.
7. Schedule it with systemd
The crawl finishes and exits, so run it as a oneshot service started by a timer. A small wrapper script names each output file by date (doing this inside the unit file would need escaping, because systemd treats % as a specifier):
cat > /home/scraper/run.sh <<'SH'
#!/bin/sh
cd /home/scraper/prices
exec /home/scraper/venv/bin/scrapy crawl catalog -O "/home/scraper/out/catalog-$(date +%Y%m%d-%H%M).jsonl"
SH
chmod +x /home/scraper/run.sh && mkdir -p /home/scraper/out# /etc/systemd/system/prices.service
[Unit]
Description=ProxySale price crawl (one batch)
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=scraper
EnvironmentFile=/home/scraper/.proxy.env
ExecStart=/home/scraper/run.sh# /etc/systemd/system/prices.timer
[Unit]
Description=Run the price crawl every 4 hours
[Timer]
OnCalendar=*-*-* 00/4:00:00
RandomizedDelaySec=600
Persistent=true
[Install]
WantedBy=timers.targetsystemctl daemon-reload && systemctl enable --now prices.timer
systemctl list-timers prices.timer
journalctl -u prices -n 50Persistent=true runs a missed batch after a reboot. For a long-lived worker that consumes a queue continuously, use a regular service with Restart=on-failure instead.
8. Keep an eye on it
Track three numbers per run: pages collected, response_bytes per page and the share of non-200 responses. If bytes per page drop sharply, you are probably receiving error or captcha pages; if 429/403 grow, slow down and check the access terms. Compare monthly usage in the ProxySale dashboard (per sub-account) with the estimate above and correct the assumptions — after a month you will be planning traffic from your own data rather than from guesses.









