Panduan Backend & AI Engineer: Perayap Web Asinkron Throughput Tinggi dengan httpx & asyncio

Membangun pipa ingesti data untuk basis pengetahuan RAG perusahaan atau intelijen pasar memerlukan perayapan puluhan ribu halaman dokumentasi secara bersih. Menembakkan 1.000 permintaan asyncio.gather() tanpa batas akan membuat IP Anda diblokir dalam hitungan detik dan menghabiskan soket efemeral lokal, sementara loop requests.get() sinkron merayap dengan sangat lambat pada 2 halaman per detik. Sebagai backend engineer dan AI application engineer, saya merancang perayap asinkron yang sopan dan ber-throughput tinggi dalam Python menggunakan ember token per domain, pengumpulan koneksi, dan deduplikasi konten streaming.

1. Semafor Per-Domain & Pembatasan Laju Jitter Adaptif

Untuk memaksimalkan throughput global sambil menghormati server asal masing-masing, perayap mempertahankan batas konkurensi global bersama pembatas laju per nama host dan kumpulan koneksi HTTP/2:

# 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
            self.seen_content_hashes.add(content_hash)
            return url, body

2. Mencegah Pembengkakan Memori dengan Penjaga Content-Type

Sebelum membaca badan respons ke dalam RAM, selalu periksa Content-Type dan Content-Length melalui client.stream("GET", url) sehingga tautan ISO 2GB atau arsip video yang tidak terduga tidak pernah memicu penghentian kehabisan memori pada pekerja ingesti Anda.

3. Referensi Data & AI Engineering Terkait


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