[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-post-en-reliable-scraping-architecture":3},{"success":4,"payload":5,"related":78,"errors":151},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":32,"allow_index":38,"noindex_google_only":38,"allow_follow":4,"published_at":39,"updated_at":40,"content_updated_at":41,"featured_image_url":42,"featured_image_alt":14,"card_image_url":43,"reading_time_minutes":44,"author":45,"categories":49,"tags":56,"alternates":64,"locale_paths":76,"views":77},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.","\u003Ch2>Beyond Scripts: Why Architecture Matters\u003C\u002Fh2>\n\u003Cp>A single-file scraper works fine for a hundred pages. But when you need to collect millions of data points across dozens of target sites on a recurring schedule, you need a system — not a script. A reliable scraping architecture separates concerns into independent components that can be scaled, monitored, and recovered independently.\u003C\u002Fp>\n\u003Cp>This guide walks through the design of a production scraping system, from URL scheduling through proxy management to data storage. Every component is illustrated with code and connected to the \u003Ca href=\"\u002Fblog\u002Fbest-proxies-for-web-scraping-2026\">ProxyHat proxy infrastructure\u003C\u002Fa>.\u003C\u002Fp>\n\u003Cblockquote>A well-architected scraper treats data collection as an engineering problem, not a hacking problem. Each component has a single responsibility, clear interfaces, and observable behavior.\u003C\u002Fblockquote>\n\u003Ch2>System Architecture Overview\u003C\u002Fh2>\n\u003Cp>A production scraping system consists of six core components:\u003C\u002Fp>\n\u003Cpre>\u003Ccode>┌─────────────┐     ┌──────────────┐     ┌─────────────────┐\n│  Scheduler   │────▶│  URL Queue   │────▶│  Crawler Pool   │\n│  (cron\u002FAPI)  │     │  (Redis)     │     │  (workers)      │\n└─────────────┘     └──────────────┘     └────────┬────────┘\n                                                   │\n                                          ┌────────▼────────┐\n                                          │  Proxy Layer     │\n                                          │  (ProxyHat)      │\n                                          └────────┬────────┘\n                                                   │\n                                          ┌────────▼────────┐\n                                          │  Parser          │\n                                          │  (extract data)  │\n                                          └────────┬────────┘\n                                                   │\n                    ┌──────────────┐      ┌────────▼────────┐\n                    │  Monitoring  │◀─────│  Storage         │\n                    │  (metrics)   │      │  (DB \u002F files)    │\n                    └──────────────┘      └─────────────────┘\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ctable>\n\u003Ccaption>System Architecture Overview\u003C\u002Fcaption>\n\u003Cthead>\n\u003Ctr>\u003Cth>Component\u003C\u002Fth>\u003Cth>Responsibility\u003C\u002Fth>\u003Cth>Technology\u003C\u002Fth>\u003C\u002Ftr>\n\u003C\u002Fthead>\n\u003Ctbody>\n\u003Ctr>\u003Ctd>Scheduler\u003C\u002Ftd>\u003Ctd>Decides what to scrape and when\u003C\u002Ftd>\u003Ctd>Cron, Celery Beat, Bull\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>URL Queue\u003C\u002Ftd>\u003Ctd>Buffers URLs with priority and deduplication\u003C\u002Ftd>\u003Ctd>Redis, RabbitMQ, SQS\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Crawler Pool\u003C\u002Ftd>\u003Ctd>Fetches pages concurrently\u003C\u002Ftd>\u003Ctd>asyncio, goroutines, worker threads\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Proxy Layer\u003C\u002Ftd>\u003Ctd>Routes requests through rotating proxies\u003C\u002Ftd>\u003Ctd>ProxyHat gateway\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Parser\u003C\u002Ftd>\u003Ctd>Extracts structured data from HTML\u002FJSON\u003C\u002Ftd>\u003Ctd>BeautifulSoup, cheerio, goquery\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Storage\u003C\u002Ftd>\u003Ctd>Persists extracted data\u003C\u002Ftd>\u003Ctd>PostgreSQL, MongoDB, S3\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Monitoring\u003C\u002Ftd>\u003Ctd>Tracks health and performance\u003C\u002Ftd>\u003Ctd>Prometheus, logging, alerts\u003C\u002Ftd>\u003C\u002Ftr>\n\u003C\u002Ftbody>\n\u003C\u002Ftable>\n\u003Ch2>Component 1: Scheduler\u003C\u002Fh2>\n\u003Cp>The scheduler decides which URLs to crawl and when. It manages crawl frequency, priority levels, and ensures no URL is scraped more often than necessary.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>import redis\nimport json\nimport time\nfrom datetime import datetime, timedelta\nclass CrawlScheduler:\n    \"\"\"Manages crawl schedules and feeds URLs to the queue.\"\"\"\n    def __init__(self, redis_url: str = \"redis:\u002F\u002Flocalhost:6379\"):\n        self.redis = redis.from_url(redis_url)\n        self.queue_key = \"scraper:url_queue\"\n        self.schedule_key = \"scraper:schedules\"\n        self.seen_key = \"scraper:seen_urls\"\n    def add_schedule(self, name: str, urls: list[str], interval_hours: int, priority: int = 5):\n        \"\"\"Register a recurring crawl job.\"\"\"\n        self.redis.hset(self.schedule_key, name, json.dumps({\n            \"urls\": urls,\n            \"interval_hours\": interval_hours,\n            \"priority\": priority,\n            \"last_run\": None,\n        }))\n    def tick(self):\n        \"\"\"Check all schedules and enqueue URLs that are due.\"\"\"\n        schedules = self.redis.hgetall(self.schedule_key)\n        enqueued = 0\n        for name, data in schedules.items():\n            schedule = json.loads(data)\n            last_run = schedule.get(\"last_run\")\n            interval = timedelta(hours=schedule[\"interval_hours\"])\n            if last_run and datetime.fromisoformat(last_run) + interval > datetime.utcnow():\n                continue\n            for url in schedule[\"urls\"]:\n                self.enqueue(url, priority=schedule[\"priority\"])\n                enqueued += 1\n            schedule[\"last_run\"] = datetime.utcnow().isoformat()\n            self.redis.hset(self.schedule_key, name, json.dumps(schedule))\n        return enqueued\n    def enqueue(self, url: str, priority: int = 5):\n        \"\"\"Add a URL to the crawl queue with deduplication.\"\"\"\n        # Skip if recently seen (within 1 hour)\n        if self.redis.sismember(self.seen_key, url):\n            return False\n        self.redis.zadd(self.queue_key, {\n            json.dumps({\"url\": url, \"enqueued_at\": time.time()}): priority\n        })\n        self.redis.sadd(self.seen_key, url)\n        self.redis.expire(self.seen_key, 3600)  # 1-hour dedup window\n        return True\n    def dequeue(self, batch_size: int = 10) -> list[dict]:\n        \"\"\"Pull the highest-priority URLs from the queue.\"\"\"\n        items = self.redis.zpopmax(self.queue_key, batch_size)\n        return [json.loads(item) for item, score in items]\n    @property\n    def queue_size(self) -> int:\n        return self.redis.zcard(self.queue_key)\n# Usage\nscheduler = CrawlScheduler()\nscheduler.add_schedule(\n    name=\"product_prices\",\n    urls=[f\"https:\u002F\u002Fexample.com\u002Fproduct\u002F{i}\" for i in range(1, 1001)],\n    interval_hours=6,\n    priority=8,\n)\nscheduler.add_schedule(\n    name=\"competitor_pages\",\n    urls=[\"https:\u002F\u002Fcompetitor.com\u002Fpricing\", \"https:\u002F\u002Fcompetitor.com\u002Ffeatures\"],\n    interval_hours=24,\n    priority=5,\n)\n# Run every minute via cron\nenqueued = scheduler.tick()\nprint(f\"Enqueued {enqueued} URLs, queue size: {scheduler.queue_size}\")\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Component 2: URL Queue\u003C\u002Fh2>\n\u003Cp>The queue decouples scheduling from crawling. It provides priority ordering, backpressure, and persistence — so no URLs are lost if a crawler crashes.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>\u002F\u002F Node.js queue with Bull\nconst Queue = require('bull');\nconst crawlQueue = new Queue('crawl', 'redis:\u002F\u002Flocalhost:6379', {\n  defaultJobOptions: {\n    attempts: 3,\n    backoff: { type: 'exponential', delay: 2000 },\n    removeOnComplete: 100,\n    removeOnFail: 500,\n  },\n});\n\u002F\u002F Add URLs with priority (lower number = higher priority)\nasync function enqueueUrls(urls, priority = 5) {\n  const jobs = urls.map(url =>\n    crawlQueue.add(\n      { url, enqueuedAt: Date.now() },\n      { priority, jobId: url } \u002F\u002F jobId for deduplication\n    )\n  );\n  await Promise.all(jobs);\n  console.log(`Enqueued ${urls.length} URLs`);\n}\n\u002F\u002F Worker processes URLs\ncrawlQueue.process(10, async (job) => {\n  const { url } = job.data;\n  \u002F\u002F Crawl logic here (see Crawler Pool below)\n  return { url, status: 'completed' };\n});\ncrawlQueue.on('failed', (job, err) => {\n  console.error(`Job ${job.id} failed: ${err.message}`);\n});\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Component 3: Crawler Pool\u003C\u002Fh2>\n\u003Cp>The crawler pool fetches pages concurrently through the \u003Ca href=\"\u002Fblog\u002Fproxy-middleware-layer\">proxy middleware layer\u003C\u002Fa>. It manages \u003Ca href=\"\u002Fblog\u002Fscaling-proxy-requests-concurrency\">concurrency limits\u003C\u002Fa>, handles retries, and passes raw responses to the parser.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>import asyncio\nimport aiohttp\nimport uuid\nimport time\nfrom typing import Optional\nclass CrawlerPool:\n    \"\"\"Concurrent crawler with proxy rotation and retry logic.\"\"\"\n    def __init__(\n        self,\n        concurrency: int = 30,\n        max_retries: int = 3,\n        timeout: int = 30,\n    ):\n        self.concurrency = concurrency\n        self.max_retries = max_retries\n        self.timeout = aiohttp.ClientTimeout(total=timeout)\n        self.semaphore = asyncio.Semaphore(concurrency)\n        self.stats = {\"success\": 0, \"failed\": 0, \"retries\": 0}\n    def _get_proxy(self, country: Optional[str] = None) -> str:\n        session_id = uuid.uuid4().hex[:8]\n        username = f\"USERNAME-sid-{session_id}\"\n        if country:\n            username += f\"-country-{country}\"\n        return f\"http:\u002F\u002F{username}:PASSWORD@gate.proxyhat.com:8080\"\n    async def fetch(\n        self,\n        session: aiohttp.ClientSession,\n        url: str,\n        country: Optional[str] = None,\n    ) -> dict:\n        async with self.semaphore:\n            for attempt in range(self.max_retries + 1):\n                proxy = self._get_proxy(country)\n                start = time.time()\n                try:\n                    async with session.get(\n                        url, proxy=proxy, timeout=self.timeout,\n                        headers={\n                            \"User-Agent\": \"Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) \"\n                                          \"AppleWebKit\u002F537.36 Chrome\u002F131.0.0.0 Safari\u002F537.36\",\n                            \"Accept\": \"text\u002Fhtml,application\u002Fxhtml+xml,*\u002F*;q=0.8\",\n                        },\n                    ) as response:\n                        body = await response.text()\n                        latency = time.time() - start\n                        if response.status in (403, 429, 503) and attempt \u003C self.max_retries:\n                            self.stats[\"retries\"] += 1\n                            await asyncio.sleep(2 ** attempt)\n                            continue\n                        if response.status \u003C 400:\n                            self.stats[\"success\"] += 1\n                        else:\n                            self.stats[\"failed\"] += 1\n                        return {\n                            \"url\": url,\n                            \"status\": response.status,\n                            \"body\": body,\n                            \"latency\": latency,\n                            \"success\": response.status \u003C 400,\n                        }\n                except Exception as e:\n                    if attempt \u003C self.max_retries:\n                        self.stats[\"retries\"] += 1\n                        await asyncio.sleep(2 ** attempt)\n                        continue\n                    self.stats[\"failed\"] += 1\n                    return {\n                        \"url\": url,\n                        \"error\": str(e),\n                        \"latency\": time.time() - start,\n                        \"success\": False,\n                    }\n    async def crawl(self, urls: list[str], country: Optional[str] = None) -> list[dict]:\n        async with aiohttp.ClientSession() as session:\n            tasks = [self.fetch(session, url, country) for url in urls]\n            return await asyncio.gather(*tasks)\n# Usage\ncrawler = CrawlerPool(concurrency=30, max_retries=3)\nurls = [f\"https:\u002F\u002Fexample.com\u002Fproduct\u002F{i}\" for i in range(500)]\nresults = asyncio.run(crawler.crawl(urls, country=\"us\"))\nprint(f\"Success: {crawler.stats['success']}, Failed: {crawler.stats['failed']}\")\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Component 4: Parser\u003C\u002Fh2>\n\u003Cp>The parser transforms raw HTML into structured data. Keep parsing logic separate from crawling — this makes it testable, reusable, and easy to update when target sites change.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>from dataclasses import dataclass\nfrom typing import Optional\nfrom bs4 import BeautifulSoup\nimport json\n@dataclass\nclass ProductData:\n    url: str\n    title: Optional[str] = None\n    price: Optional[float] = None\n    currency: Optional[str] = None\n    availability: Optional[str] = None\n    rating: Optional[float] = None\n    review_count: Optional[int] = None\n    parsed_at: Optional[str] = None\nclass ProductParser:\n    \"\"\"Extracts structured product data from HTML.\"\"\"\n    def parse(self, url: str, html: str) -> ProductData:\n        soup = BeautifulSoup(html, \"html.parser\")\n        data = ProductData(url=url)\n        try:\n            data.title = self._extract_text(soup, \"h1.product-title\")\n            data.price = self._extract_price(soup)\n            data.currency = self._extract_currency(soup)\n            data.availability = self._extract_text(soup, \".availability-status\")\n            data.rating = self._extract_rating(soup)\n            data.review_count = self._extract_review_count(soup)\n            data.parsed_at = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n        except Exception as e:\n            logger.error(f\"Parse error for {url}: {e}\")\n        return data\n    def _extract_text(self, soup, selector: str) -> Optional[str]:\n        el = soup.select_one(selector)\n        return el.get_text(strip=True) if el else None\n    def _extract_price(self, soup) -> Optional[float]:\n        el = soup.select_one(\"[data-price], .price, .product-price\")\n        if not el:\n            return None\n        price_text = el.get(\"data-price\") or el.get_text(strip=True)\n        # Remove currency symbols and parse\n        cleaned = \"\".join(c for c in price_text if c.isdigit() or c == \".\")\n        return float(cleaned) if cleaned else None\n    def _extract_currency(self, soup) -> Optional[str]:\n        el = soup.select_one(\"[data-currency], .currency\")\n        return el.get(\"data-currency\") or el.get_text(strip=True) if el else None\n    def _extract_rating(self, soup) -> Optional[float]:\n        el = soup.select_one(\"[data-rating], .rating-value\")\n        if el:\n            val = el.get(\"data-rating\") or el.get_text(strip=True)\n            try:\n                return float(val)\n            except ValueError:\n                return None\n        return None\n    def _extract_review_count(self, soup) -> Optional[int]:\n        el = soup.select_one(\".review-count, [data-reviews]\")\n        if el:\n            text = el.get(\"data-reviews\") or el.get_text(strip=True)\n            digits = \"\".join(c for c in text if c.isdigit())\n            return int(digits) if digits else None\n        return None\n# Usage\nparser = ProductParser()\nfor result in results:\n    if result[\"success\"]:\n        product = parser.parse(result[\"url\"], result[\"body\"])\n        print(f\"{product.title}: ${product.price}\")\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Component 5: Storage\u003C\u002Fh2>\n\u003Cp>Persist parsed data with versioning and deduplication. Use upserts to handle re-crawls gracefully.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>import psycopg2\nfrom psycopg2.extras import execute_values\nfrom datetime import datetime\nclass DataStore:\n    \"\"\"Persists scraped data with upsert and versioning.\"\"\"\n    def __init__(self, dsn: str):\n        self.conn = psycopg2.connect(dsn)\n        self._ensure_tables()\n    def _ensure_tables(self):\n        with self.conn.cursor() as cur:\n            cur.execute(\"\"\"\n                CREATE TABLE IF NOT EXISTS products (\n                    url TEXT PRIMARY KEY,\n                    title TEXT,\n                    price NUMERIC(10,2),\n                    currency VARCHAR(3),\n                    availability TEXT,\n                    rating NUMERIC(3,2),\n                    review_count INTEGER,\n                    first_seen_at TIMESTAMPTZ DEFAULT NOW(),\n                    last_updated_at TIMESTAMPTZ DEFAULT NOW()\n                );\n                CREATE TABLE IF NOT EXISTS price_history (\n                    id SERIAL PRIMARY KEY,\n                    url TEXT REFERENCES products(url),\n                    price NUMERIC(10,2),\n                    recorded_at TIMESTAMPTZ DEFAULT NOW()\n                );\n            \"\"\")\n            self.conn.commit()\n    def upsert_products(self, products: list[ProductData]):\n        \"\"\"Insert or update products, recording price changes.\"\"\"\n        with self.conn.cursor() as cur:\n            for product in products:\n                if product.price is None:\n                    continue\n                # Check if price changed\n                cur.execute(\n                    \"SELECT price FROM products WHERE url = %s\",\n                    (product.url,)\n                )\n                row = cur.fetchone()\n                # Upsert product\n                cur.execute(\"\"\"\n                    INSERT INTO products (url, title, price, currency, availability,\n                                          rating, review_count, last_updated_at)\n                    VALUES (%s, %s, %s, %s, %s, %s, %s, NOW())\n                    ON CONFLICT (url) DO UPDATE SET\n                        title = EXCLUDED.title,\n                        price = EXCLUDED.price,\n                        currency = EXCLUDED.currency,\n                        availability = EXCLUDED.availability,\n                        rating = EXCLUDED.rating,\n                        review_count = EXCLUDED.review_count,\n                        last_updated_at = NOW()\n                \"\"\", (\n                    product.url, product.title, product.price,\n                    product.currency, product.availability,\n                    product.rating, product.review_count,\n                ))\n                # Record price history if changed\n                if row is None or float(row[0]) != product.price:\n                    cur.execute(\n                        \"INSERT INTO price_history (url, price) VALUES (%s, %s)\",\n                        (product.url, product.price)\n                    )\n            self.conn.commit()\n    @property\n    def product_count(self) -> int:\n        with self.conn.cursor() as cur:\n            cur.execute(\"SELECT COUNT(*) FROM products\")\n            return cur.fetchone()[0]\n# Usage\nstore = DataStore(\"postgresql:\u002F\u002Fuser:pass@localhost:5432\u002Fscraper\")\nstore.upsert_products(parsed_products)\nprint(f\"Total products: {store.product_count}\")\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Component 6: Monitoring\u003C\u002Fh2>\n\u003Cp>Tie all components together with centralized monitoring. For detailed proxy-specific monitoring patterns, see our \u003Ca href=\"\u002Fblog\u002Fmonitoring-proxy-performance\">Monitoring Proxy Performance\u003C\u002Fa> guide.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>import time\nimport json\nimport logging\nfrom datetime import datetime\nclass PipelineMonitor:\n    \"\"\"Monitors the entire scraping pipeline.\"\"\"\n    def __init__(self):\n        self.logger = logging.getLogger(\"pipeline\")\n        self.stage_times = {}\n        self.stage_counts = {}\n    def start_stage(self, stage: str):\n        self.stage_times[stage] = time.time()\n    def end_stage(self, stage: str, item_count: int = 0):\n        elapsed = time.time() - self.stage_times.get(stage, time.time())\n        self.stage_counts[stage] = item_count\n        self.logger.info(json.dumps({\n            \"timestamp\": datetime.utcnow().isoformat(),\n            \"stage\": stage,\n            \"duration_seconds\": round(elapsed, 2),\n            \"items_processed\": item_count,\n            \"items_per_second\": round(item_count \u002F elapsed, 1) if elapsed > 0 else 0,\n        }))\n    def report(self) -> dict:\n        return {\n            \"stages\": {\n                stage: {\n                    \"items\": self.stage_counts.get(stage, 0),\n                }\n                for stage in self.stage_counts\n            },\n            \"timestamp\": datetime.utcnow().isoformat(),\n        }\n# Usage within the full pipeline\nmonitor = PipelineMonitor()\n# Stage 1: Schedule\nmonitor.start_stage(\"schedule\")\nurls = scheduler.dequeue(batch_size=500)\nmonitor.end_stage(\"schedule\", len(urls))\n# Stage 2: Crawl\nmonitor.start_stage(\"crawl\")\nresults = asyncio.run(crawler.crawl([u[\"url\"] for u in urls]))\nmonitor.end_stage(\"crawl\", len(results))\n# Stage 3: Parse\nmonitor.start_stage(\"parse\")\nproducts = [parser.parse(r[\"url\"], r[\"body\"]) for r in results if r[\"success\"]]\nmonitor.end_stage(\"parse\", len(products))\n# Stage 4: Store\nmonitor.start_stage(\"store\")\nstore.upsert_products(products)\nmonitor.end_stage(\"store\", len(products))\nprint(json.dumps(monitor.report(), indent=2))\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Putting It All Together\u003C\u002Fh2>\n\u003Cp>Here is the complete pipeline that connects all six components into a single, runnable scraping system.\u003C\u002Fp>\n\u003Cpre>\u003Ccode>import asyncio\nimport logging\nlogging.basicConfig(level=logging.INFO)\nasync def run_pipeline():\n    # Initialize components\n    scheduler = CrawlScheduler()\n    crawler = CrawlerPool(concurrency=30, max_retries=3)\n    parser = ProductParser()\n    store = DataStore(\"postgresql:\u002F\u002Fuser:pass@localhost:5432\u002Fscraper\")\n    monitor = PipelineMonitor()\n    # Schedule crawls\n    scheduler.add_schedule(\n        name=\"daily_products\",\n        urls=[f\"https:\u002F\u002Fexample.com\u002Fproduct\u002F{i}\" for i in range(1, 501)],\n        interval_hours=24,\n        priority=8,\n    )\n    # Main loop\n    while True:\n        # 1. Check schedules and enqueue URLs\n        monitor.start_stage(\"schedule\")\n        scheduler.tick()\n        batch = scheduler.dequeue(batch_size=100)\n        monitor.end_stage(\"schedule\", len(batch))\n        if not batch:\n            await asyncio.sleep(60)\n            continue\n        # 2. Crawl\n        monitor.start_stage(\"crawl\")\n        urls = [item[\"url\"] for item in batch]\n        results = await crawler.crawl(urls, country=\"us\")\n        successful = [r for r in results if r.get(\"success\")]\n        monitor.end_stage(\"crawl\", len(successful))\n        # 3. Parse\n        monitor.start_stage(\"parse\")\n        products = []\n        for result in successful:\n            try:\n                product = parser.parse(result[\"url\"], result[\"body\"])\n                products.append(product)\n            except Exception as e:\n                logging.error(f\"Parse error: {e}\")\n        monitor.end_stage(\"parse\", len(products))\n        # 4. Store\n        monitor.start_stage(\"store\")\n        store.upsert_products(products)\n        monitor.end_stage(\"store\", len(products))\n        # 5. Report\n        logging.info(f\"Pipeline: {monitor.report()}\")\n        logging.info(f\"Crawler stats: {crawler.stats}\")\n        # Wait before next batch\n        await asyncio.sleep(5)\nasyncio.run(run_pipeline())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2>Production Deployment Patterns\u003C\u002Fh2>\n\u003Ch3>Horizontal Scaling\u003C\u002Fh3>\n\u003Cp>Scale crawlers independently from schedulers and parsers. Run multiple crawler instances consuming from the same Redis queue.\u003C\u002Fp>\n\u003Ctable>\n\u003Ccaption>Horizontal Scaling\u003C\u002Fcaption>\n\u003Cthead>\n\u003Ctr>\u003Cth>Component\u003C\u002Fth>\u003Cth>Scaling Strategy\u003C\u002Fth>\u003Cth>Typical Scale\u003C\u002Fth>\u003C\u002Ftr>\n\u003C\u002Fthead>\n\u003Ctbody>\n\u003Ctr>\u003Ctd>Scheduler\u003C\u002Ftd>\u003Ctd>Single instance (leader election)\u003C\u002Ftd>\u003Ctd>1 instance\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>URL Queue\u003C\u002Ftd>\u003Ctd>Redis cluster or managed queue\u003C\u002Ftd>\u003Ctd>1 cluster\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Crawler Pool\u003C\u002Ftd>\u003Ctd>Horizontal pod scaling\u003C\u002Ftd>\u003Ctd>2-20 instances\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Proxy Layer\u003C\u002Ftd>\u003Ctd>Managed by ProxyHat\u003C\u002Ftd>\u003Ctd>N\u002FA (external)\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Parser\u003C\u002Ftd>\u003Ctd>Co-located with crawler or separate\u003C\u002Ftd>\u003Ctd>1:1 with crawlers\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Storage\u003C\u002Ftd>\u003Ctd>Database replication\u003C\u002Ftd>\u003Ctd>1 primary + replicas\u003C\u002Ftd>\u003C\u002Ftr>\n\u003Ctr>\u003Ctd>Monitoring\u003C\u002Ftd>\u003Ctd>Centralized aggregation\u003C\u002Ftd>\u003Ctd>1 instance\u003C\u002Ftd>\u003C\u002Ftr>\n\u003C\u002Ftbody>\n\u003C\u002Ftable>\n\u003Ch3>Error Recovery\u003C\u002Fh3>\n\u003Cul>\n\u003Cli>\u003Cstrong>Crawler crash:\u003C\u002Fstrong> URLs remain in Redis queue. New crawler picks them up automatically.\u003C\u002Fli>\n\u003Cli>\u003Cstrong>Proxy failures:\u003C\u002Fstrong> The \u003Ca href=\"\u002Fblog\u002Fproxy-middleware-layer\">middleware layer\u003C\u002Fa> retries with fresh IPs. Sustained failures trigger alerts.\u003C\u002Fli>\n\u003Cli>\u003Cstrong>Parser failures:\u003C\u002Fstrong> Raw HTML is stored in a dead-letter queue for manual inspection and parser updates.\u003C\u002Fli>\n\u003Cli>\u003Cstrong>Database failures:\u003C\u002Fstrong> Parsed data buffers in memory\u002Fdisk with write-ahead logging until the DB recovers.\u003C\u002Fli>\n\u003C\u002Ful>\n\u003Ch3>Data Quality Checks\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>class DataQualityChecker:\n    \"\"\"Validates parsed data before storage.\"\"\"\n    def check(self, product: ProductData) -> list[str]:\n        issues = []\n        if not product.title:\n            issues.append(\"missing_title\")\n        if product.price is not None and product.price \u003C= 0:\n            issues.append(\"invalid_price\")\n        if product.price is not None and product.price > 100000:\n            issues.append(\"suspicious_price\")\n        if product.rating is not None and (product.rating \u003C 0 or product.rating > 5):\n            issues.append(\"invalid_rating\")\n        return issues\n    def filter_valid(self, products: list[ProductData]) -> list[ProductData]:\n        valid = []\n        for product in products:\n            issues = self.check(product)\n            if issues:\n                logger.warning(f\"Data quality issues for {product.url}: {issues}\")\n            else:\n                valid.append(product)\n        return valid\n# Integrate into pipeline\nchecker = DataQualityChecker()\nvalid_products = checker.filter_valid(products)\nstore.upsert_products(valid_products)\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cblockquote>The best scraping architecture is one you can reason about. Every component should answer three questions: What does it do? How does it fail? How does it recover?\u003C\u002Fblockquote>\n\u003Cp>For the proxy layer component, see \u003Ca href=\"\u002Fblog\u002Fproxy-middleware-layer\">Building a Proxy Middleware Layer\u003C\u002Fa>. For optimizing crawler throughput, read \u003Ca href=\"\u002Fblog\u002Fscaling-proxy-requests-concurrency\">Scaling Proxy Requests with Concurrency Control\u003C\u002Fa>. For browser-based crawling, see \u003Ca href=\"\u002Fblog\u002Frotating-proxies-with-playwright\">Rotating Proxies with Playwright\u003C\u002Fa>. For anti-detection strategies, explore \u003Ca href=\"\u002Fblog\u002Fscrape-websites-without-getting-blocked\">how to scrape without getting blocked\u003C\u002Fa>.\u003C\u002Fp>\n\u003Cp>Get started with \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 proxy integration. Explore \u003Ca href=\"\u002Fpricing\">ProxyHat pricing\u003C\u002Fa> and \u003Ca href=\"https:\u002F\u002Fdocs.proxyhat.com\u002F\">documentation\u003C\u002Fa> to power your scraping architecture.\u003C\u002Fp>","Reliable Scraping Architecture","Design a reliable scraping architecture with scheduler, crawler pool, proxy layer, parser, and storage. Production code and architecture patterns for scalable scraping.","\u002Fblog\u002Freliable-scraping-architecture",null,"https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Freliable-scraping-architecture-og.webp",[17,20,23,26,29],{"question":18,"answer":19},"What queue system should I use for scraping?","Redis is the most common choice for scraping queues due to its speed, built-in sorted sets for priority, and simplicity. For larger deployments requiring message acknowledgment and dead-letter queues, use RabbitMQ or Amazon SQS. Bull (Node.js) and Celery (Python) provide high-level abstractions over Redis.",{"question":21,"answer":22},"How do I handle target sites that change their HTML structure?","Separate parsing from crawling so you can update parsers without modifying crawlers. Store raw HTML in a dead-letter queue when parsing fails, implement CSS selector fallback chains, and use data quality checks to detect parser breakage before it corrupts your database.",{"question":24,"answer":25},"How many crawler instances do I need?","Start with one crawler instance running 20-50 concurrent requests. Scale horizontally when the URL queue grows faster than one instance can drain it. Each crawler instance with 30 concurrent connections and ProxyHat proxies can typically process 500-2,000 pages per minute depending on target site response times.",{"question":27,"answer":28},"Should I use a database or files for storing scraped data?","Use a database (PostgreSQL) for structured data that needs querying, deduplication, and price history tracking. Use file storage (S3, local files) for raw HTML archives. Many production systems use both — structured data in PostgreSQL and raw responses in object storage for reprocessing.",{"question":30,"answer":31},"How do I prevent duplicate scraping of the same URL?","Use Redis sets for short-term deduplication (within a crawl session) and database upserts for long-term deduplication. The scheduler tracks when each URL was last crawled and skips URLs that were scraped within the configured interval.",[33,34,35,36,37],"A production scraping system needs six core components: scheduler, URL queue, crawler pool, proxy layer, parser, and storage.","Separate parsing logic from crawling to make it testable, reusable, and easy to update when target sites change.","Use a priority-based URL queue with deduplication to decouple scheduling from crawling and prevent data loss on crashes.","Implement concurrency limits, retries with exponential backoff, and rotating proxies in the crawler pool for reliable fetching.","Persist parsed data with upserts and versioning to handle re-crawls gracefully and track changes like price history.",false,"2026-02-24T06:55:16+00:00","2026-07-19T03:13:07+00:00","2026-10-03T08:21:20+00:00","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Freliable-scraping-architecture-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Freliable-scraping-architecture-card.webp",12,{"name":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},"ProxyHat Team","proxyhat-team","The ProxyHat editorial team covers proxies, web scraping, and data extraction.",[50],{"id":51,"slug":52,"name":53,"description":14,"meta_title":54,"meta_description":55,"parent_id":14},4,"developer-guides","Developer Guides","Developer Guides | ProxyHat Blog","Code tutorials and SDK guides for integrating proxies into your applications.",[57,61],{"id":58,"slug":59,"name":60},1,"web-scraping","Web Scraping",{"id":44,"slug":62,"name":63},"sdk","SDK",{"en":13,"zh":65,"tr":66,"ru":67,"de":68,"pt":69,"it":70,"es":71,"ja":72,"pl":73,"ko":74,"fr":75,"x-default":13},"\u002Fcn\u002Fblog\u002Fsheji-kekaode-caiji-jiagou","\u002Ftr\u002Fblog\u002Fguvenilir-scraping-mimarisi-tasarlama","\u002Fru\u002Fblog\u002Fproektirovanie-nadezhnoj-arhitektury-skrapinga","\u002Fde\u002Fblog\u002Fzuverlaessige-scraping-architektur","\u002Fpt\u002Fblog\u002Farquitetura-de-scraping-confiavel","\u002Fit\u002Fblog\u002Fprogettazione-di-unarchitettura-di-scraping-affidabile","\u002Fes\u002Fblog\u002Fdiseno-arquitectura-scraping-fiable","\u002Fja\u002Fblog\u002Fshinraisei-no-takai-sukureipingu-aakitekucha","\u002Fpl\u002Fblog\u002Fprojektowanie-niezawodnej-architektury-skraplania","\u002Fko\u002Fblog\u002Fanjeongjeok-scraping-akitecheo","\u002Ffr\u002Fblog\u002Fconcevoir-une-architecture-de-scraping-fiable",{"en":13,"zh":65,"tr":66,"ru":67,"de":68,"pt":69,"it":70,"es":71,"ja":72,"pl":73,"ko":74,"fr":75},68,[79,97,117,134],{"id":80,"slug":81,"title":82,"excerpt":83,"featured_image_url":84,"featured_image_alt":14,"card_image_url":85,"og_image_url":86,"published_at":87,"updated_at":40,"content_updated_at":88,"reading_time_minutes":89,"is_featured":38,"indexable":38,"views":90,"author":91,"categories":92,"tags":94},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":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},[93],{"id":51,"slug":52,"name":53,"description":14,"meta_title":54,"meta_description":55,"parent_id":14},[95,96],{"id":44,"slug":62,"name":63},{"id":58,"slug":59,"name":60},{"id":98,"slug":99,"title":100,"excerpt":101,"featured_image_url":102,"featured_image_alt":14,"card_image_url":103,"og_image_url":104,"published_at":105,"updated_at":40,"content_updated_at":106,"reading_time_minutes":107,"is_featured":38,"indexable":38,"views":108,"author":109,"categories":110,"tags":114},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":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},[111],{"id":58,"slug":59,"name":60,"description":14,"meta_title":112,"meta_description":113,"parent_id":14},"Web Scraping Guides & Tips | ProxyHat Blog","Learn web scraping techniques, proxy strategies, and data extraction best practices.",[115,116],{"id":58,"slug":59,"name":60},{"id":44,"slug":62,"name":63},{"id":118,"slug":119,"title":120,"excerpt":121,"featured_image_url":122,"featured_image_alt":14,"card_image_url":123,"og_image_url":124,"published_at":125,"updated_at":40,"content_updated_at":126,"reading_time_minutes":44,"is_featured":38,"indexable":38,"views":127,"author":128,"categories":129,"tags":131},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":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},[130],{"id":51,"slug":52,"name":53,"description":14,"meta_title":54,"meta_description":55,"parent_id":14},[132,133],{"id":44,"slug":62,"name":63},{"id":58,"slug":59,"name":60},{"id":135,"slug":136,"title":137,"excerpt":138,"featured_image_url":139,"featured_image_alt":14,"card_image_url":140,"og_image_url":141,"published_at":142,"updated_at":40,"content_updated_at":143,"reading_time_minutes":44,"is_featured":38,"indexable":38,"views":144,"author":145,"categories":146,"tags":148},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.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fproxy-middleware-layer-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fproxy-middleware-layer-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fproxy-middleware-layer-og.webp","2026-02-02T07:15:32+00:00","2026-10-03T08:21:29+00:00",44,{"name":46,"slug":47,"bio":48,"avatar_url":14,"website_url":14,"social_links":14},[147],{"id":51,"slug":52,"name":53,"description":14,"meta_title":54,"meta_description":55,"parent_id":14},[149,150],{"id":44,"slug":62,"name":63},{"id":58,"slug":59,"name":60},[]]