[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-post-en-proxy-middleware-layer":3},{"success":4,"payload":5,"related":72,"errors":145},true,{"id":6,"slug":7,"title":8,"excerpt":9,"body_html":10,"meta_title":11,"meta_description":12,"canonical_url":13,"canonical_override":14,"og_title":8,"og_description":12,"og_image_url":15,"faq_json":16,"key_takeaways":26,"allow_index":32,"noindex_google_only":32,"allow_follow":4,"published_at":33,"updated_at":34,"content_updated_at":35,"featured_image_url":36,"featured_image_alt":14,"card_image_url":37,"reading_time_minutes":38,"author":39,"categories":43,"tags":50,"alternates":58,"locale_paths":70,"views":71},29,"proxy-middleware-layer","Building a Proxy Middleware Layer for Scraping","Design and build a production-grade proxy middleware layer with retry logic, failover, and metrics. Complete implementations in Python and Node.js using ProxyHat.","\u003Ch2>Why Build a Proxy Middleware Layer\u003C\u002Fh2>\n\u003Cp>When your scraping project grows beyond a single script, you need an abstraction layer between your application code and the proxy provider. A middleware layer handles proxy selection, authentication, retry logic, failover, and logging — so your scrapers only worry about extracting data.\u003C\u002Fp>\n\u003Cp>Without middleware, every scraper in your codebase duplicates proxy configuration, error handling, and rotation logic. This guide shows you how to design and build a production-grade proxy middleware in both Python and Node.js, using \u003Ca href=\"\u002Fblog\u002Fbest-proxies-for-web-scraping-2026\">ProxyHat's rotating residential proxies\u003C\u002Fa>.\u003C\u002Fp>\n\u003Cblockquote>A proxy middleware sits between your application and the internet. It intercepts outgoing requests, routes them through proxies, handles failures, and returns clean responses to your application code.\u003C\u002Fblockquote>\n\u003Ch2>Architecture Overview\u003C\u002Fh2>\n\u003Cp>A well-designed proxy middleware has four core components:\u003C\u002Fp>\n\u003Ctable>\n\u003Ccaption>Architecture Overview\u003C\u002Fcaption>\n\u003Cthead>\n\u003Ctr>\u003Cth>Component\u003C\u002Fth>\u003Cth>Responsibility\u003C\u002Fth>\u003Cth>Why It Matters\u003C\u002Fth>\u003C\u002Ftr>\n\u003C\u002Fthead>\n\u003Ctbody>\n\u003Ctr>\u003Ctd>Proxy Manager\u003C\u002Ftd>\u003Ctd>Manages proxy credentials, sessions, and geo-targeting\u003C\u002Ftd>\u003Ctd>Centralizes proxy configuration\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Request Interceptor\u003C\u002Ftd>\u003Ctd>Wraps outgoing requests with proxy settings and headers\u003C\u002Ftd>\u003Ctd>Eliminates boilerplate in scrapers\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Retry Engine\u003C\u002Ftd>\u003Ctd>Retries failed requests with backoff and proxy rotation\u003C\u002Ftd>\u003Ctd>Increases success rate from 70% to 95%+\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Metrics Collector\u003C\u002Ftd>\u003Ctd>Tracks latency, success rates, and error patterns\u003C\u002Ftd>\u003Ctd>Enables data-driven optimization\u003C\u002Ftd>\u003C\u002Ftr>\n\u003C\u002Ftbody>\n\u003C\u002Ftable>\n\u003Ch2>Python Middleware Implementation\u003C\u002Fh2>\n\u003Ch3>Core Proxy Manager\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>import uuid\nimport time\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nlogger = logging.getLogger(__name__)\n@dataclass\nclass ProxyConfig:\n    gateway: str = \"gate.proxyhat.com\"\n    http_port: int = 8080\n    socks5_port: int = 1080\n    username: str = \"USERNAME\"\n    password: str = \"PASSWORD\"\n@dataclass\nclass RequestMetrics:\n    total: int = 0\n    success: int = 0\n    failed: int = 0\n    retries: int = 0\n    total_latency: float = 0.0\n    @property\n    def success_rate(self) -> float:\n        return (self.success \u002F self.total * 100) if self.total > 0 else 0.0\n    @property\n    def avg_latency(self) -> float:\n        return (self.total_latency \u002F self.success) if self.success > 0 else 0.0\nclass ProxyManager:\n    \"\"\"Manages proxy sessions, geo-targeting, and protocol selection.\"\"\"\n    def __init__(self, config: Optional[ProxyConfig] = None):\n        self.config = config or ProxyConfig()\n        self.metrics = RequestMetrics()\n    def get_proxy_url(\n        self,\n        protocol: str = \"http\",\n        country: Optional[str] = None,\n        session_id: Optional[str] = None,\n        sticky: bool = False,\n    ) -> str:\n        username = self.config.username\n        # Add session for sticky IPs\n        if sticky and not session_id:\n            session_id = uuid.uuid4().hex[:8]\n        if session_id:\n            username = f\"{username}-sid-{session_id}\"\n        # Add country targeting\n        if country:\n            username = f\"{username}-country-{country}\"\n        if protocol == \"socks5\":\n            port = self.config.socks5_port\n            scheme = \"socks5h\"\n        else:\n            port = self.config.http_port\n            scheme = \"http\"\n        return f\"{scheme}:\u002F\u002F{username}:{self.config.password}@{self.config.gateway}:{port}\"\n    def get_requests_proxies(self, **kwargs) -> dict:\n        \"\"\"Return a proxies dict compatible with the requests library.\"\"\"\n        url = self.get_proxy_url(**kwargs)\n        return {\"http\": url, \"https\": url}\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>Retry Engine with Backoff\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>import requests\nfrom requests.exceptions import RequestException\nRETRYABLE_STATUS_CODES = {403, 429, 500, 502, 503, 504}\nclass RetryEngine:\n    \"\"\"Retries failed requests with exponential backoff and proxy rotation.\"\"\"\n    def __init__(\n        self,\n        proxy_manager: ProxyManager,\n        max_retries: int = 3,\n        base_delay: float = 1.0,\n        max_delay: float = 30.0,\n        rotate_on_failure: bool = True,\n    ):\n        self.proxy_manager = proxy_manager\n        self.max_retries = max_retries\n        self.base_delay = base_delay\n        self.max_delay = max_delay\n        self.rotate_on_failure = rotate_on_failure\n    def _should_retry(self, response: Optional[requests.Response], error: Optional[Exception]) -> bool:\n        if error:\n            return True\n        if response and response.status_code in RETRYABLE_STATUS_CODES:\n            return True\n        return False\n    def _get_delay(self, attempt: int) -> float:\n        delay = self.base_delay * (2 ** attempt)\n        return min(delay, self.max_delay)\n    def execute(\n        self,\n        method: str,\n        url: str,\n        country: Optional[str] = None,\n        sticky: bool = False,\n        **request_kwargs,\n    ) -> requests.Response:\n        session_id = uuid.uuid4().hex[:8] if sticky else None\n        last_error = None\n        for attempt in range(self.max_retries + 1):\n            # Rotate proxy on retry if enabled\n            if attempt > 0 and self.rotate_on_failure:\n                session_id = uuid.uuid4().hex[:8]\n                self.proxy_manager.metrics.retries += 1\n            proxies = self.proxy_manager.get_requests_proxies(\n                country=country, session_id=session_id\n            )\n            self.proxy_manager.metrics.total += 1\n            start_time = time.time()\n            try:\n                response = requests.request(\n                    method, url,\n                    proxies=proxies,\n                    timeout=request_kwargs.pop(\"timeout\", 30),\n                    **request_kwargs,\n                )\n                latency = time.time() - start_time\n                self.proxy_manager.metrics.total_latency += latency\n                if self._should_retry(response, None) and attempt \u003C self.max_retries:\n                    logger.warning(\n                        f\"Retryable status {response.status_code} for {url} \"\n                        f\"(attempt {attempt + 1}\u002F{self.max_retries + 1})\"\n                    )\n                    time.sleep(self._get_delay(attempt))\n                    continue\n                self.proxy_manager.metrics.success += 1\n                return response\n            except RequestException as e:\n                last_error = e\n                latency = time.time() - start_time\n                logger.error(f\"Request failed for {url}: {e} (attempt {attempt + 1})\")\n                if attempt \u003C self.max_retries:\n                    time.sleep(self._get_delay(attempt))\n                    continue\n                self.proxy_manager.metrics.failed += 1\n        raise last_error or Exception(f\"All retries exhausted for {url}\")\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>Complete Middleware Class\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>class ProxyMiddleware:\n    \"\"\"High-level middleware that wraps all proxy logic.\"\"\"\n    def __init__(\n        self,\n        config: Optional[ProxyConfig] = None,\n        max_retries: int = 3,\n        default_country: Optional[str] = None,\n    ):\n        self.proxy_manager = ProxyManager(config)\n        self.retry_engine = RetryEngine(\n            proxy_manager=self.proxy_manager,\n            max_retries=max_retries,\n        )\n        self.default_country = default_country\n        self.default_headers = {\n            \"Accept\": \"text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8\",\n            \"Accept-Language\": \"en-US,en;q=0.9\",\n            \"Accept-Encoding\": \"gzip, deflate, br\",\n        }\n    def get(self, url: str, **kwargs) -> requests.Response:\n        kwargs.setdefault(\"headers\", self.default_headers)\n        kwargs.setdefault(\"country\", self.default_country)\n        return self.retry_engine.execute(\"GET\", url, **kwargs)\n    def post(self, url: str, **kwargs) -> requests.Response:\n        kwargs.setdefault(\"headers\", self.default_headers)\n        kwargs.setdefault(\"country\", self.default_country)\n        return self.retry_engine.execute(\"POST\", url, **kwargs)\n    @property\n    def stats(self) -> dict:\n        m = self.proxy_manager.metrics\n        return {\n            \"total_requests\": m.total,\n            \"successful\": m.success,\n            \"failed\": m.failed,\n            \"retries\": m.retries,\n            \"success_rate\": f\"{m.success_rate:.1f}%\",\n            \"avg_latency\": f\"{m.avg_latency:.3f}s\",\n        }\n# Usage\nmiddleware = ProxyMiddleware(max_retries=3, default_country=\"us\")\n# Simple GET — all proxy logic is hidden\nresponse = middleware.get(\"https:\u002F\u002Fhttpbin.org\u002Fip\")\nprint(response.json())\n# Geo-targeted request\nresponse = middleware.get(\"https:\u002F\u002Fexample.com\u002Fpricing\", country=\"de\")\nprint(response.text[:200])\n# Check performance\nprint(middleware.stats)\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Node.js Middleware Implementation\u003C\u002Fh2>\n\u003Ch3>Core Proxy Manager\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>const crypto = require('crypto');\nconst { HttpsProxyAgent } = require('https-proxy-agent');\nconst { SocksProxyAgent } = require('socks-proxy-agent');\nclass ProxyManager {\n  constructor(config = {}) {\n    this.gateway = config.gateway || 'gate.proxyhat.com';\n    this.httpPort = config.httpPort || 8080;\n    this.socks5Port = config.socks5Port || 1080;\n    this.username = config.username || 'USERNAME';\n    this.password = config.password || 'PASSWORD';\n    this.metrics = {\n      total: 0,\n      success: 0,\n      failed: 0,\n      retries: 0,\n      totalLatency: 0,\n    };\n  }\n  getProxyUrl({ protocol = 'http', country, sessionId, sticky = false } = {}) {\n    let username = this.username;\n    if (sticky && !sessionId) {\n      sessionId = crypto.randomBytes(4).toString('hex');\n    }\n    if (sessionId) username += `-sid-${sessionId}`;\n    if (country) username += `-country-${country}`;\n    const port = protocol === 'socks5' ? this.socks5Port : this.httpPort;\n    const scheme = protocol === 'socks5' ? 'socks5h' : 'http';\n    return `${scheme}:\u002F\u002F${username}:${this.password}@${this.gateway}:${port}`;\n  }\n  createAgent(options = {}) {\n    const url = this.getProxyUrl(options);\n    if (options.protocol === 'socks5') {\n      return new SocksProxyAgent(url);\n    }\n    return new HttpsProxyAgent(url);\n  }\n  get stats() {\n    const m = this.metrics;\n    return {\n      total: m.total,\n      success: m.success,\n      failed: m.failed,\n      retries: m.retries,\n      successRate: m.total > 0 ? ((m.success \u002F m.total) * 100).toFixed(1) + '%' : '0%',\n      avgLatency: m.success > 0 ? (m.totalLatency \u002F m.success).toFixed(3) + 's' : '0s',\n    };\n  }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>Retry Engine\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>const RETRYABLE_STATUS_CODES = new Set([403, 429, 500, 502, 503, 504]);\nclass RetryEngine {\n  constructor(proxyManager, options = {}) {\n    this.proxyManager = proxyManager;\n    this.maxRetries = options.maxRetries || 3;\n    this.baseDelay = options.baseDelay || 1000;\n    this.maxDelay = options.maxDelay || 30000;\n    this.rotateOnFailure = options.rotateOnFailure !== false;\n  }\n  _getDelay(attempt) {\n    return Math.min(this.baseDelay * Math.pow(2, attempt), this.maxDelay);\n  }\n  _sleep(ms) {\n    return new Promise(resolve => setTimeout(resolve, ms));\n  }\n  async execute(url, options = {}) {\n    const { country, sticky, ...fetchOptions } = options;\n    let sessionId = sticky ? crypto.randomBytes(4).toString('hex') : undefined;\n    let lastError;\n    for (let attempt = 0; attempt \u003C= this.maxRetries; attempt++) {\n      if (attempt > 0 && this.rotateOnFailure) {\n        sessionId = crypto.randomBytes(4).toString('hex');\n        this.proxyManager.metrics.retries++;\n      }\n      const agent = this.proxyManager.createAgent({ country, sessionId });\n      this.proxyManager.metrics.total++;\n      const startTime = Date.now();\n      try {\n        const response = await fetch(url, {\n          ...fetchOptions,\n          agent,\n          signal: AbortSignal.timeout(fetchOptions.timeout || 30000),\n        });\n        const latency = (Date.now() - startTime) \u002F 1000;\n        this.proxyManager.metrics.totalLatency += latency;\n        if (RETRYABLE_STATUS_CODES.has(response.status) && attempt \u003C this.maxRetries) {\n          console.warn(\n            `Retryable status ${response.status} for ${url} ` +\n            `(attempt ${attempt + 1}\u002F${this.maxRetries + 1})`\n          );\n          await this._sleep(this._getDelay(attempt));\n          continue;\n        }\n        this.proxyManager.metrics.success++;\n        return response;\n      } catch (err) {\n        lastError = err;\n        console.error(`Request failed for ${url}: ${err.message} (attempt ${attempt + 1})`);\n        if (attempt \u003C this.maxRetries) {\n          await this._sleep(this._getDelay(attempt));\n          continue;\n        }\n        this.proxyManager.metrics.failed++;\n      }\n    }\n    throw lastError || new Error(`All retries exhausted for ${url}`);\n  }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3>Complete Middleware Class\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>class ProxyMiddleware {\n  constructor(options = {}) {\n    this.proxyManager = new ProxyManager(options.proxy);\n    this.retryEngine = new RetryEngine(this.proxyManager, {\n      maxRetries: options.maxRetries || 3,\n    });\n    this.defaultCountry = options.defaultCountry || null;\n    this.defaultHeaders = {\n      'Accept': 'text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8',\n      'Accept-Language': 'en-US,en;q=0.9',\n      'User-Agent': 'Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36',\n    };\n  }\n  async get(url, options = {}) {\n    return this.retryEngine.execute(url, {\n      method: 'GET',\n      headers: { ...this.defaultHeaders, ...options.headers },\n      country: options.country || this.defaultCountry,\n      ...options,\n    });\n  }\n  async post(url, body, options = {}) {\n    return this.retryEngine.execute(url, {\n      method: 'POST',\n      headers: { ...this.defaultHeaders, ...options.headers },\n      body: typeof body === 'string' ? body : JSON.stringify(body),\n      country: options.country || this.defaultCountry,\n      ...options,\n    });\n  }\n  get stats() {\n    return this.proxyManager.stats;\n  }\n}\n\u002F\u002F Usage\nconst middleware = new ProxyMiddleware({\n  maxRetries: 3,\n  defaultCountry: 'us',\n});\n\u002F\u002F Simple GET\nconst response = await middleware.get('https:\u002F\u002Fhttpbin.org\u002Fip');\nconst data = await response.json();\nconsole.log(data);\n\u002F\u002F Check stats\nconsole.log(middleware.stats);\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Adding Provider Failover\u003C\u002Fh2>\n\u003Cp>For mission-critical scraping, you can extend the middleware to support multiple proxy providers with automatic failover.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>class MultiProviderMiddleware:\n    \"\"\"Falls back to secondary proxy providers on failure.\"\"\"\n    def __init__(self, providers: list[ProxyConfig], max_retries: int = 3):\n        self.providers = [\n            ProxyMiddleware(config=cfg, max_retries=max_retries)\n            for cfg in providers\n        ]\n    def get(self, url: str, **kwargs) -> requests.Response:\n        last_error = None\n        for i, provider in enumerate(self.providers):\n            try:\n                response = provider.get(url, **kwargs)\n                if response.status_code \u003C 400:\n                    return response\n            except Exception as e:\n                last_error = e\n                logger.warning(f\"Provider {i} failed for {url}: {e}\")\n                continue\n        raise last_error or Exception(f\"All providers failed for {url}\")\n# Primary: ProxyHat | Fallback: backup provider\nproviders = [\n    ProxyConfig(\n        gateway=\"gate.proxyhat.com\",\n        username=\"USERNAME\",\n        password=\"PASSWORD\",\n    ),\n    ProxyConfig(\n        gateway=\"backup-proxy.example.com\",\n        username=\"BACKUP_USER\",\n        password=\"BACKUP_PASS\",\n    ),\n]\nmiddleware = MultiProviderMiddleware(providers)\nresponse = middleware.get(\"https:\u002F\u002Fexample.com\u002Fdata\")\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Async Middleware (Python)\u003C\u002Fh2>\n\u003Cp>For high-throughput scraping, use the async version with \u003Ccode>aiohttp\u003C\u002Fcode>. For more concurrency patterns, see our guide on \u003Ca href=\"\u002Fblog\u002Fscaling-proxy-requests-concurrency\">scaling proxy requests with concurrency control\u003C\u002Fa>.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>import aiohttp\nimport asyncio\nclass AsyncProxyMiddleware:\n    def __init__(self, config: Optional[ProxyConfig] = None, max_retries: int = 3):\n        self.proxy_manager = ProxyManager(config)\n        self.max_retries = max_retries\n    async def get(self, url: str, country: Optional[str] = None) -> str:\n        for attempt in range(self.max_retries + 1):\n            session_id = uuid.uuid4().hex[:8]\n            proxy_url = self.proxy_manager.get_proxy_url(\n                country=country, session_id=session_id\n            )\n            try:\n                async with aiohttp.ClientSession() as session:\n                    async with session.get(\n                        url, proxy=proxy_url, timeout=aiohttp.ClientTimeout(total=30)\n                    ) as response:\n                        if response.status in RETRYABLE_STATUS_CODES and attempt \u003C self.max_retries:\n                            await asyncio.sleep(2 ** attempt)\n                            continue\n                        self.proxy_manager.metrics.success += 1\n                        return await response.text()\n            except Exception as e:\n                if attempt == self.max_retries:\n                    self.proxy_manager.metrics.failed += 1\n                    raise\n                await asyncio.sleep(2 ** attempt)\n# Usage\nasync def main():\n    middleware = AsyncProxyMiddleware(max_retries=3)\n    urls = [f\"https:\u002F\u002Fexample.com\u002Fpage\u002F{i}\" for i in range(100)]\n    tasks = [middleware.get(url) for url in urls]\n    results = await asyncio.gather(*tasks, return_exceptions=True)\n    success = sum(1 for r in results if not isinstance(r, Exception))\n    print(f\"Success: {success}\u002F{len(results)}\")\n    print(middleware.proxy_manager.metrics)\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Integrating with Scraping Frameworks\u003C\u002Fh2>\n\u003Cp>The middleware integrates cleanly with common scraping patterns. Here is how to use it with Playwright and with standard \u003Ca href=\"\u002Fblog\u002Fusing-proxies-in-python\">Python requests\u003C\u002Fa>.\u003C\u002Fp>\n\u003Cpre>\u003Ccode># With Playwright (Node.js)\nconst { chromium } = require('playwright');\nclass PlaywrightProxyMiddleware {\n  constructor(proxyManager) {\n    this.proxyManager = proxyManager;\n    this.browser = null;\n  }\n  async init() {\n    this.browser = await chromium.launch();\n  }\n  async scrape(url, options = {}) {\n    const proxyUrl = this.proxyManager.getProxyUrl({\n      sessionId: crypto.randomBytes(4).toString('hex'),\n      country: options.country,\n    });\n    const parsed = new URL(proxyUrl);\n    const context = await this.browser.newContext({\n      proxy: {\n        server: `${parsed.protocol}\u002F\u002F${parsed.hostname}:${parsed.port}`,\n        username: decodeURIComponent(parsed.username),\n        password: decodeURIComponent(parsed.password),\n      },\n    });\n    const page = await context.newPage();\n    try {\n      await page.goto(url, { timeout: 30000 });\n      return await page.content();\n    } finally {\n      await context.close();\n    }\n  }\n  async close() {\n    if (this.browser) await this.browser.close();\n  }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>For Playwright-specific proxy patterns, see our \u003Ca href=\"\u002Fblog\u002Frotating-proxies-with-playwright\">Playwright proxy rotation guide\u003C\u002Fa>. For monitoring the metrics your middleware collects, see \u003Ca href=\"\u002Fblog\u002Fmonitoring-proxy-performance\">Monitoring Proxy Performance\u003C\u002Fa>.\u003C\u002Fp>\n\u003Cp>Explore the \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fpython-sdk\">Python SDK\u003C\u002Fa>, \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fnode-sdk\">Node SDK\u003C\u002Fa>, or \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fgo-sdk\">Go SDK\u003C\u002Fa> for built-in middleware features, and check \u003Ca href=\"\u002Fpricing\">ProxyHat pricing\u003C\u002Fa> to get started. For full integration documentation, visit \u003Ca href=\"https:\u002F\u002Fdocs.proxyhat.com\u002F\">docs.proxyhat.com\u003C\u002Fa>.\u003C\u002Fp>","Building a Proxy Middleware Laye","Build a proxy middleware layer with retry logic, failover, and metrics tracking. Production-ready Python and Node.js implementations with code examples.","\u002Fblog\u002Fproxy-middleware-layer",null,"https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fproxy-middleware-layer-og.webp",[17,20,23],{"question":18,"answer":19},"Should I build my own middleware or use an SDK?","Use an SDK for simple projects — the ProxyHat Python, Node, and Go SDKs provide retry logic and session management out of the box. Build custom middleware when you need provider failover, custom retry policies, or integration with specific frameworks.",{"question":21,"answer":22},"How does the retry engine decide when to rotate the proxy?","The retry engine rotates to a new proxy session on every retryable failure (HTTP 403, 429, 500, 502, 503, 504 or connection errors). Each retry uses a fresh session ID, which maps to a different IP address through the ProxyHat gateway.",{"question":24,"answer":25},"Can I use the middleware with async Python?","Yes. Replace the requests-based implementation with aiohttp for async support. The same proxy manager and retry logic work with async\u002Fawait, enabling hundreds of concurrent requests through the proxy middleware.",[27,28,29,30,31],"A proxy middleware layer abstracts proxy configuration, retry logic, and failover from your scraping code.","The architecture includes a Proxy Manager, Request Interceptor, Retry Engine, and Metrics Collector.","The guide provides Python and Node.js implementations for a production-grade proxy middleware.","A Retry Engine with exponential backoff and proxy rotation can increase request success rates to 95%+.","The middleware can be extended to support multiple proxy providers for automatic failover.",false,"2026-02-02T07:15:32+00:00","2026-07-19T03:13:07+00:00","2026-10-03T08:21:29+00:00","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fproxy-middleware-layer-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fproxy-middleware-layer-card.webp",12,{"name":40,"slug":41,"bio":42,"avatar_url":14,"website_url":14,"social_links":14},"ProxyHat Team","proxyhat-team","The ProxyHat editorial team covers proxies, web scraping, and data extraction.",[44],{"id":45,"slug":46,"name":47,"description":14,"meta_title":48,"meta_description":49,"parent_id":14},4,"developer-guides","Developer Guides","Developer Guides | ProxyHat Blog","Code tutorials and SDK guides for integrating proxies into your applications.",[51,55],{"id":52,"slug":53,"name":54},1,"web-scraping","Web Scraping",{"id":38,"slug":56,"name":57},"sdk","SDK",{"en":13,"de":59,"es":60,"pt":61,"zh":62,"fr":63,"ru":64,"it":65,"pl":66,"ja":67,"tr":68,"ko":69,"x-default":13},"\u002Fde\u002Fblog\u002Fproxy-middleware-schicht-aufbauen","\u002Fes\u002Fblog\u002Fcapa-middleware-de-proxy-para-scraping","\u002Fpt\u002Fblog\u002Fcamada-middleware-de-proxy","\u002Fcn\u002Fblog\u002Fdaili-zhongjian-jian-ceng","\u002Ffr\u002Fblog\u002Fconstruire-un-middleware-de-proxy","\u002Fru\u002Fblog\u002Fsozdanie-promezhutochnogo-sloya-proksi","\u002Fit\u002Fblog\u002Fcostruire-uno-strato-di-middleware-proxy-per-scraping","\u002Fpl\u002Fblog\u002Fbudowa-warstwa-proxy-middleware-do-skracania","\u002Fja\u002Fblog\u002Fsukureipingu-no-tame-no-prokishi-midoruuea-reiyaa","\u002Ftr\u002Fblog\u002Fscraping-icin-proxy-middleware-katmani","\u002Fko\u002Fblog\u002Fproxy-middleware-layer-guchuk",{"en":13,"de":59,"es":60,"pt":61,"zh":62,"fr":63,"ru":64,"it":65,"pl":66,"ja":67,"tr":68,"ko":69},44,[73,90,108,128],{"id":74,"slug":75,"title":76,"excerpt":77,"featured_image_url":78,"featured_image_alt":14,"card_image_url":79,"og_image_url":80,"published_at":81,"updated_at":34,"content_updated_at":82,"reading_time_minutes":38,"is_featured":32,"indexable":32,"views":83,"author":84,"categories":85,"tags":87},50,"reliable-scraping-architecture","Designing a Reliable Scraping Architecture","Design an end-to-end scraping system: scheduler, URL queue, crawler pool, proxy layer, parser, storage, and monitoring. Production-ready Python code with architecture diagrams.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Freliable-scraping-architecture-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Freliable-scraping-architecture-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Freliable-scraping-architecture-og.webp","2026-02-24T06:55:16+00:00","2026-10-03T08:21:20+00:00",68,{"name":40,"slug":41,"bio":42,"avatar_url":14,"website_url":14,"social_links":14},[86],{"id":45,"slug":46,"name":47,"description":14,"meta_title":48,"meta_description":49,"parent_id":14},[88,89],{"id":38,"slug":56,"name":57},{"id":52,"slug":53,"name":54},{"id":91,"slug":92,"title":93,"excerpt":94,"featured_image_url":95,"featured_image_alt":14,"card_image_url":96,"og_image_url":97,"published_at":98,"updated_at":34,"content_updated_at":99,"reading_time_minutes":100,"is_featured":32,"indexable":32,"views":101,"author":102,"categories":103,"tags":105},41,"monitoring-proxy-performance","Monitoring Proxy Performance: Latency, Success Rate, and Alerts","Learn how to instrument, monitor, and alert on proxy performance — track latency percentiles, success rates, error patterns, and bandwidth. Code examples in Python, Node.js, and Go.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fmonitoring-proxy-performance-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fmonitoring-proxy-performance-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fmonitoring-proxy-performance-og.webp","2026-02-15T00:39:23+00:00","2026-10-03T08:21:37+00:00",11,75,{"name":40,"slug":41,"bio":42,"avatar_url":14,"website_url":14,"social_links":14},[104],{"id":45,"slug":46,"name":47,"description":14,"meta_title":48,"meta_description":49,"parent_id":14},[106,107],{"id":38,"slug":56,"name":57},{"id":52,"slug":53,"name":54},{"id":109,"slug":110,"title":111,"excerpt":112,"featured_image_url":113,"featured_image_alt":14,"card_image_url":114,"og_image_url":115,"published_at":116,"updated_at":34,"content_updated_at":117,"reading_time_minutes":118,"is_featured":32,"indexable":32,"views":119,"author":120,"categories":121,"tags":125},36,"scale-scraping-infrastructure","How to Scale Scraping Infrastructure","Architecture patterns for scaling web scraping: queue-based systems, pipeline design, horizontal scaling with containers, and proxy management at scale. Code in Python, Node.js, and Go.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fscale-scraping-infrastructure-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fscale-scraping-infrastructure-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fscale-scraping-infrastructure-og.webp","2026-02-09T14:42:34+00:00","2026-02-25T23:52:12+00:00",10,49,{"name":40,"slug":41,"bio":42,"avatar_url":14,"website_url":14,"social_links":14},[122],{"id":52,"slug":53,"name":54,"description":14,"meta_title":123,"meta_description":124,"parent_id":14},"Web Scraping Guides & Tips | ProxyHat Blog","Learn web scraping techniques, proxy strategies, and data extraction best practices.",[126,127],{"id":52,"slug":53,"name":54},{"id":38,"slug":56,"name":57},{"id":129,"slug":130,"title":131,"excerpt":132,"featured_image_url":133,"featured_image_alt":14,"card_image_url":134,"og_image_url":135,"published_at":136,"updated_at":34,"content_updated_at":137,"reading_time_minutes":38,"is_featured":32,"indexable":32,"views":138,"author":139,"categories":140,"tags":142},35,"scaling-proxy-requests-concurrency","Scaling Proxy Requests with Concurrency Control","Master concurrency patterns for proxy-based scraping: asyncio semaphores, Promise pools, Go worker pools, rate limiters, and backpressure. Production code in Python, Node.js, and Go.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fscaling-proxy-requests-concurrency-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fscaling-proxy-requests-concurrency-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fscaling-proxy-requests-concurrency-og.webp","2026-02-08T11:16:13+00:00","2026-10-03T08:21:21+00:00",358,{"name":40,"slug":41,"bio":42,"avatar_url":14,"website_url":14,"social_links":14},[141],{"id":45,"slug":46,"name":47,"description":14,"meta_title":48,"meta_description":49,"parent_id":14},[143,144],{"id":38,"slug":56,"name":57},{"id":52,"slug":53,"name":54},[]]