No KYC — no ID, no selfie, no documents. Pay in crypto: BTC, USDT, USDC, ETH, SOL, LTC
Language: English
Get started

Docs · Scrapy 2.x · middleware · AutoThrottle · checked 13 November 2026

How do I use rotating proxies with Scrapy?

One downloader middleware picks the country and the session per request; a handful of settings keep the crawl polite.

Last updated: · 6 min read

Quick answer

How do I use rotating proxies with Scrapy?

CrawlRelay plugs into Scrapy through a 30-line downloader middleware that sets request.meta["proxy"] before the built-in HttpProxyMiddleware at priority 750. The country and an optional sticky session of up to 30 minutes go in the username. Residential traffic costs $0.50/GB from 50 GB and never expires.

In brief
  • Where: request.meta["proxy"], set by a middleware numbered below 750.
  • Rotation: each new connection usually gets a new residential IP; proxy_session="new" forces a fresh session.
  • Stickiness: a fixed proxy_session and proxy_ttl (1 to 30 minutes) keep pagination on one exit.
  • Politeness: ROBOTSTXT_OBEY, 4 requests per domain to start, AutoThrottle on, 3 retries.
  • Cost: $0.50/GB from 50 GB; a Scrapy HTML page usually weighs tens of kilobytes.

What does the Scrapy setup look like at a glance?

What does the Scrapy setup look like at a glance?
Where the proxy goesrequest.meta["proxy"], set by your middleware
Middleware orderYour middleware below 750, the priority of the built-in HttpProxyMiddleware
CredentialsIn the proxy URL; Scrapy turns them into a Proxy-Authorization header
SOCKS5Scrapy's proxy middleware is documented for HTTP and HTTPS proxies; use the HTTP port 7777
RotationNew exit per new connection; a unique session ID per request normally gives a different IP
PolitenessROBOTSTXT_OBEY, CONCURRENT_REQUESTS_PER_DOMAIN, AUTOTHROTTLE_ENABLED
Retries429 and 5xx are in the default RETRY_HTTP_CODES; Retry-After is not read by default

How do I write the proxy middleware?

Add one class to middlewares.py that builds the CrawlRelay username from settings and from three optional meta keys. The keys are proxy_country, proxy_session and proxy_ttl. A request without proxy_session rotates; a request with proxy_session="new" gets a new session, so normally a different exit IP; a request with a fixed session ID shares one exit with the other requests of the same flow. The middleware recomputes its proxy on every pass, retries included, and leaves alone a proxy set by other code. If CRAWLRELAY_USER is missing, the crawl stops at start-up instead of running from your own IP.

middlewares.py
import uuid
from urllib.parse import quote


class CrawlRelayProxyMiddleware:
    """Sets request.meta["proxy"]; Scrapy's HttpProxyMiddleware then sends the credentials."""

    def __init__(self, user, password, country):
        self.user, self.password, self.country = user, password, country

    @classmethod
    def from_crawler(cls, crawler):
        s = crawler.settings
        if not s.get("CRAWLRELAY_USER"):
            # Fail loudly: NotConfigured would only disable the middleware and crawl from your own IP
            raise ValueError("CRAWLRELAY_USER is not set: refusing to crawl without the proxy")
        return cls(s.get("CRAWLRELAY_USER"), s.get("CRAWLRELAY_PASSWORD", ""), s.get("CRAWLRELAY_COUNTRY", "us"))

    def process_request(self, request, spider=None):
        if "proxy" in request.meta and not request.meta.get("_crawlrelay"):
            return None  # a proxy set by other code: leave it alone
        parts = [self.user, "country", request.meta.get("proxy_country", self.country)]
        session = request.meta.get("proxy_session")
        if session == "new":  # a fresh session for this request (and for each of its retries)
            session = uuid.uuid4().hex[:12]
        if session:
            parts += ["session", session, "ttl", str(request.meta.get("proxy_ttl", 10))]
        username = "-".join(parts)
        request.meta["proxy"] = "http://%s:%[email protected]:7777" % (
            quote(username, safe=""), quote(self.password, safe=""))
        request.meta["_crawlrelay"] = True
        return None

Which Scrapy settings keep a proxied crawl polite and fast?

Keep robots.txt on, start at 4 requests per domain and let AutoThrottle slow down when responses get slower. Proxies spread requests over many IPs, but the target still sees the total rate. ROBOTSTXT_OBEY = True is already the default in new Scrapy projects; leave it on.

settings.py (excerpt)
import os

BOT_NAME = "myproject"
ROBOTSTXT_OBEY = True
USER_AGENT = "ExampleCrawler/1.0 (+https://example.com/crawler-info)"

CRAWLRELAY_USER = os.environ.get("CRAWLRELAY_USER")  # e.g. the username from your dashboard
CRAWLRELAY_PASSWORD = os.environ.get("CRAWLRELAY_PASSWORD")
CRAWLRELAY_COUNTRY = "us"

DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.CrawlRelayProxyMiddleware": 350,  # runs before HttpProxyMiddleware (750)
}

CONCURRENT_REQUESTS = 32
CONCURRENT_REQUESTS_PER_DOMAIN = 4
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 1.0
AUTOTHROTTLE_MAX_DELAY = 30.0
AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0

RETRY_ENABLED = True
RETRY_TIMES = 3
RETRY_HTTP_CODES = [429, 500, 502, 503, 504, 522, 524, 408]
DOWNLOAD_TIMEOUT = 45

How do I keep one IP for pagination and rotate for item pages?

Give listing requests a fixed proxy_session and leave item requests without one. Pagination that depends on the previous page then stays on one exit for up to 30 minutes, while independent product pages spread over rotating exits. The spider below runs on books.toscrape.com, a sandbox site published for scraping practice.

spiders/catalog.py
import scrapy


class CatalogSpider(scrapy.Spider):
    name = "catalog"
    start_urls = ["https://books.toscrape.com/"]

    def parse(self, response):
        for href in response.css("article.product_pod h3 a::attr(href)").getall():
            # Product pages are independent: rotating exits
            yield response.follow(href, callback=self.parse_item)
        next_page = response.css("li.next a::attr(href)").get()
        if next_page:
            # The listing flow keeps one sticky exit for 30 minutes
            yield response.follow(next_page, callback=self.parse,
                                  meta={"proxy_session": "listing1", "proxy_ttl": 30})

    def parse_item(self, response):
        yield {
            "title": response.css("div.product_main h1::text").get(),
            "price": response.css("p.price_color::text").get(),
            "url": response.url,
        }

Does Scrapy reuse connections, and does that stop rotation?

Yes, Scrapy reuses connections per proxy and host, but it opens several per domain, and each new one usually gets a different IP. For most crawls that is fine: up to CONCURRENT_REQUESTS_PER_DOMAIN connections run per site, and consecutive requests on one connection share an exit.

When a request must leave through a new IP, for example a retry after a 502 from a failing exit, re-issue it with response.request.replace(meta={**response.meta, "proxy_session": "new"}, dont_filter=True). The middleware builds a new session username, a different username means a different connection pool, so Scrapy opens a new connection and the gateway normally assigns a different exit.

How do I honour Retry-After on 429 responses in Scrapy?

Scrapy retries 429 but ignores Retry-After, so rely on AutoThrottle or add a small middleware that reads the header. AutoThrottle slows the domain down over time, which is usually enough. For APIs that send long Retry-After values, schedule the retry with that delay, or lower CONCURRENT_REQUESTS_PER_DOMAIN for that domain. The 429 page explains what the header means.

How do I use the proxy with scrapy-playwright?

Pass the gateway in PLAYWRIGHT_LAUNCH_OPTIONS, with the username and password as separate fields. Chromium ignores credentials written inside the server URL. Use one context per sticky session if you render logged-out flows that span several pages, and render only the pages that need JavaScript: a browser page weighs far more than its HTML.

settings.py for scrapy-playwright
import os

DOWNLOAD_HANDLERS = {
    "http": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
    "https": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
}
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"

PLAYWRIGHT_LAUNCH_OPTIONS = {
    "proxy": {
        "server": "http://gw.crawlrelay.com:7777",
        "username": os.environ.get("CRAWLRELAY_USER", "USERNAME") + "-country-us",
        "password": os.environ.get("CRAWLRELAY_PASSWORD", "PASSWORD"),
    },
}

How much does a Scrapy crawl cost through residential proxies?

Divide downloader/response_bytes by the response count at the end of a test run, then multiply by the pages you plan to fetch. Scrapy downloads HTML only, so a page usually costs tens of kilobytes once compressed; the bandwidth guide converts that into gigabytes and dollars.

According to CrawlRelay's survey of 13 October 2026, the median residential price was $2.73/GB at 50 GB across 14 offers. CrawlRelay sells 50 GB for $25, and the rate stays at $0.50/GB up to 1 TB. Bought traffic never expires, so a crawl that runs once a month keeps its remaining gigabytes for the next run.

Scrapy and proxies: questions

Do I need scrapy-rotating-proxies or a proxy list with CrawlRelay?

No. Those packages rotate a list of addresses and ban the failing ones; CrawlRelay rotates behind one gateway address, so each new connection usually gets a different IP. The single middleware above is enough.

Why does Scrapy show TunnelError with CrawlRelay?

TunnelError: Could not open CONNECT tunnel means the CONNECT step failed for an HTTPS site. The status in the message says why: 407 means CrawlRelay rejected the credentials, 502 or 504 points to the exit or the target.

How many concurrent requests per domain should I run through CrawlRelay?

Start at 2 to 4 per domain and let AutoThrottle adjust. CrawlRelay bills per GB, not per connection, so raise the number only while 429, 403 and 5xx shares stay flat.

Should I disable ROBOTSTXT_OBEY to get more data through CrawlRelay?

No. robots.txt states which paths automated clients may fetch, RFC 9309 standardised it in September 2022, and using CrawlRelay to reach excluded content breaks its Acceptable Use Policy.

Can Scrapy use the CrawlRelay SOCKS5 port?

Use the HTTP port 7777 instead: Scrapy's HttpProxyMiddleware is documented for HTTP and HTTPS proxies, and CrawlRelay serves HTTPS sites through CONNECT tunnels on that port.

Verdict
  • Use the middleware for any Scrapy project: it replaces proxy-list packages and keeps rotation, stickiness and country in one place.
  • Add scrapy-playwright only for pages that need JavaScript, because a rendered page costs far more traffic than its HTML.
Sources (3)
  1. Scrapy downloader middleware reference (HttpProxyMiddleware, DOWNLOADER_MIDDLEWARES_BASE) — Scrapy (read 2026-11-13)
  2. Scrapy AutoThrottle extension — Scrapy (read 2026-11-13)
  3. RFC 9309, Robots Exclusion Protocol — IETF (September 2022, read 2026-11-13)

Plug residential IPs into your Scrapy project

$5.94 for 10 GB to test, $25 for 50 GB once the spider is ready.

From $0.50/GB · no KYC

Get started