Backend & AI Engineer Guide: High-Throughput Async Web Crawlers with httpx, asyncio & Politeness

Building a data ingestion pipeline for enterprise RAG knowledge bases or market intelligence requires crawling tens of thousands of documentation pages cleanly. Firing 1,000 unbounded asyncio.gather() requests gets your IP blocked within seconds and exhausts local ephemeral sockets, while synchronous requests.get() loops crawl at a glacial 2 pages per second. As a backend engineer and AI application engineer, I architect polite, high-throughput asynchronous crawlers in Python using per-domain token buckets, connection pooling, and streaming content deduplication.

1. Per-Domain Semaphore & Adaptive Jitter Rate Limiting

To maximize global throughput while respecting individual origin servers, the crawler maintains a global concurrency limit alongside a per-hostname rate limiter and HTTP/2 connection pool:

# crawler/engine.py
import asyncio
import hashlib
import random
import time
from collections import defaultdict
from urllib.parse import urlparse
import httpx

class PoliteAsyncCrawler:
    def __init__(self, max_global_concurrency: int = 64, min_host_delay_sec: float = 0.5):
        self.global_sem = asyncio.Semaphore(max_global_concurrency)
        self.host_locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
        self.host_last_req: dict[str, float] = defaultdict(float)
        self.min_host_delay_sec = min_host_delay_sec
        self.seen_content_hashes: set[str] = set()

    async def fetch_url(self, client: httpx.AsyncClient, url: str) -> tuple[str, str | None]:
        host = urlparse(url).netloc
        async with self.global_sem:
            async with self.host_locks[host]:
                elapsed = time.monotonic() - self.host_last_req[host]
                wait_for = self.min_host_delay_sec - elapsed + random.uniform(0.05, 0.2)
                if wait_for > 0:
                    await asyncio.sleep(wait_for)
                self.host_last_req[host] = time.monotonic()

            resp = await client.get(url, follow_redirects=True, timeout=10.0)
            if resp.status_code == 429:
                retry_after = float(resp.headers.get("Retry-After", "5"))
                await asyncio.sleep(min(retry_after, 30.0))
                return url, None
            resp.raise_for_status()

            body = resp.text
            content_hash = hashlib.sha256(body.encode("utf-8", errors="ignore")).hexdigest()
            if content_hash in self.seen_content_hashes:
                return url, None  # Skip duplicate mirror page
            self.seen_content_hashes.add(content_hash)
            return url, body

2. Preventing Memory Bloating with Streaming & Content-Type Guards

Before reading a response body into RAM, always inspect Content-Type and Content-Length via client.stream("GET", url) so an unexpected 2GB ISO link or video archive never triggers an out-of-memory kill in your ingestion worker.

3. Related Data & AI Engineering Resources


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 25+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs