Your crawler worked fine on two hundred URLs last Tuesday. You pointed a Python script at a seed page, pulled out the links, and dumped the HTML into a folder. Then you pointed it at fifty domains overnight, and by morning one slow server had stalled your entire queue, three sites had rate-limited your IP address, and half your database held duplicate copies of the same product page under different tracking strings.
That gap between a working script and a reliable system is where most engineers get stuck when learning how to build a crawler. Fetching HTML over HTTP is the easy part. Keeping a crawl healthy across thousands or millions of URLs requires a different mental model: politeness, deduplication, and JavaScript rendering cost are scheduler inputs from day one, not patches you bolt on after your pipeline misbehaves.
If you design around those constraints early, even a single-machine prototype can grow into a distributed pipeline without a rewrite.
Crawler Components and What Each One Stores
Say you're building a price tracker that crawls 50 retail domains every day. If you run that job as a single loop pulling from one shared queue, one sluggish storefront taking ten seconds to respond will starve your workers while fast domains sit idle. A naive retry loop makes it worse by re-fetching broken links over and over, and without structured fetch logs, you won't know whether a missing price came from a timeout, a redirect, or a changed HTML layout.
Web-scale operators solve this by treating crawling as a distributed data pipeline rather than an HTTP script. Common Crawl illustrates why that architecture matters: its open repository has collected web data since 2008, holds more than 10 petabytes, and publishes crawls roughly once per month that each typically exceed 2 billion web pages. Its early 2008 architecture paired a custom Hadoop-based crawler with PageRank, proving a principle that still holds at smaller scales: link discovery and prioritization are data-processing problems, not just network calls.
Five Subsystems and One Clear Owner
Splitting your crawler into five explicit components gives every failure mode a single owner. Even if you start on one machine with an in-memory queue, a visited-URL set, per-domain scheduling, retry logic, and a local content database, preserving these boundaries lets you swap out individual backends later without rewriting your fetch logic.
| Component | Job | What to Record |
|---|---|---|
| URL frontier | Prioritizes and deduplicates discovered URLs | URL, host, priority, state |
| Fetch workers | Resolve DNS, honor delays and retrieve pages | Status code, final URL, timestamp, content type, response size |
| Robots.txt cache | Holds crawl rules for each origin | Rules, fetch time, fetch status |
| Parsers | Extract links and content from responses | Extracted fields, normalized links, extraction errors |
| Storage | Keeps raw and normalized results | Raw response (WARC or object storage), content hash, normalized record |
Recording the status code, final URL, timestamp, content type, response size, content hash, and extraction errors for every fetch turns silent failures into observable metrics. Those exact fields also enable incremental recrawling, letting you skip unchanged pages instead of downloading them repeatedly.
Lock In Storage and Frontier Design First
Architecture rule: Choose your storage format and frontier backend before writing a single line of fetch code, because migrating millions of URL states and raw captures mid-project is far more expensive than swapping an HTTP client.
When you plan the tables or document collections that back your frontier and content store, sound database schema design prevents write bottlenecks once concurrent workers start updating URL states at high speed. The engineering milestone isn't how many threads you can spin up; it's maintaining reliable frontier state, reproducible parsing, and predictable storage growth as you move from thousands of pages to millions.
Respect robots.txt and Crawl Politely
A robots.txt file is a request to automated clients, not an access-control or authorization system. Treat it as your scheduler's primary input anyway. Ignoring crawl directives creates unnecessary load on origin servers, introduces legal exposure, and produces patchy datasets once site operators start blocking your IP ranges.
The mechanism dates back to 1994 as the Robots Exclusion Protocol, and in September 2022 the Internet Engineering Task Force published RFC 9309 to standardize and extend it. Under that specification, rules live at the lowercase top-level path /robots.txt for each origin, and crawlers must evaluate Allow and Disallow directives to decide whether a URI can be fetched. Understanding how site administrators approach blocking crawlers with robots.txt also helps you anticipate edge cases like wildcard path rules and user-agent-specific overrides.
Protocol Rules Your Scheduler Must Enforce
Fetch and cache robots.txt separately for every origin (scheme, host, and port). Match candidate URLs against the most specific applicable Allow or Disallow rule, respect any crawl delay the site specifies in its policy or guidance, and apply a conservative default rate limit whenever no delay is listed. Always send a transparent User-Agent header containing a contact URL or email address so an operator experiencing unexpected load can reach you before banning your network.
Just as critical is separating policy failures from transport failures. Every response your fetch layer receives should trigger a deterministic scheduling action rather than a blind retry.
| Response | Meaning | Crawler Action |
|---|---|---|
| 200 with content | Page available | Parse and store; flag consent walls, login pages and empty shells |
| 403 or robots denial | Access refused or disallowed | Record the denial and do not retry |
| 429 | Rate limited | Back off exponentially and lower per-host concurrency |
| 5xx | Server error | Retry with exponential backoff up to a cap |
| Timeout or DNS error | Transport failure | Retry later; do not treat it as permission to crawl unrestricted |
| robots.txt returns 5xx | Policy unknown | Treat the host as fully disallowed until the file returns |
Handling Live Rate Limits Without Panicking
Say your daily retail crawl hits a sudden wave of 429 responses on one merchant's catalog during a flash sale. A naive crawler keeps retrying on a fixed timer and gets its IP permanently dropped. A polite scheduler doubles the wait interval on each consecutive 429, cuts per-host concurrency down to one active request, and gradually restores throughput only after several clean cycles.
Never interpret a timeout, DNS lookup failure, or server error on a robots.txt check as an open invitation. If fetching /robots.txt returns a 5xx error, your default rule is simple: treat that entire host as fully disallowed until you can successfully retrieve the policy file again.
Build the Pipeline Step by Step
A production crawler runs as a staged pipeline where every stage reads from durable state and writes its result before handing off work. Grouping your frontier into two levels is the design choice that keeps traffic balanced, because per-host queues stop one massive site from monopolizing all your workers.
The diagram below shows how seed URLs enter a persistent frontier and split into per-host queues at the start of every crawl cycle.

Eight Steps for a Single Fetch Cycle
- Load seed URLs into a persistent frontier. Store an explicit state alongside every URL so a process crash never resets your crawl to zero. Engineers often skip persistence in early versions and end up re-crawling thousands of pages after every unhandled exception.
- Partition URLs into per-host queues feeding a global priority queue. Grouping by hostname ensures one high-volume domain can't swallow every fetch worker, while your global priority queue ranks which eligible host runs next. Start prioritization with business relevance and freshness before layering in graph signals; Common Crawl's operational crawler metrics note using PageRank alongside harmonic centrality to order URLs.
- Hold each host until its politeness delay expires. A host becomes eligible for dispatch only after its configured cooldown window passes. Skipping per-host delays is the fastest way to get an IP address blocked within minutes on commercial sites.
- Resolve DNS and verify cached robots.txt rules. Before opening an HTTP connection, check the host's cached directives and discard any blocked path. Always log blocked URLs as denied rather than dropping them without a record, or your reporting will show mysterious gaps between discovered and fetched pages.
- Fetch over HTTP with strict timeouts and per-host concurrency caps. Unbounded socket timeouts let hanging servers pin your worker pool indefinitely, so enforce both connect and read timeouts on every request.
- Parse responses, extract links, and normalize discovered URLs. Pull out structured fields and candidate links immediately, then normalize every link before passing it back into the frontier. Feeding raw relative paths or messy query strings directly into the queue creates crawl traps.
- Write raw captures to durable object storage and structured data to your database. Save the full raw HTTP payload in WARC format or object storage alongside the normalized record in your database. Keeping raw captures lets you fix a parser bug and reprocess pages offline without hitting the origin site a second time.
- Record every URL state transition. Persist transitions across queued, fetched, redirected, denied, failed, and duplicate states so interrupted jobs resume cleanly. Applying strong governance and reliability in pipelines ensures these state logs stay auditable as your team adds more downstream consumers.
Observability and a Minimal Starter Skeleton
HTTP status codes alone will lie to you. A 200 OK response that delivers a cookie consent wall, a login gate, a soft-404 error page, or an empty JavaScript shell is a failed capture and must be counted as one in your pipeline metrics.
Common Crawl's operational categories provide a reliable observability template: separate successful fetches, redirects, robots or 403 denials, failures, and skipped URLs caused by time limits or per-host caps. Track valid responses per scheduled URL alongside unique content yield, bytes per successful page, median latency, retry rate, robots denials, and per-host saturation.
For a deeper walkthrough of how crawling architecture fits together in practice, watch this overview before writing your first prototype.
Watch the video on YouTubeI'd start your first version as a single Python process rather than reaching for a distributed cluster on day one. Keep a dictionary of deque objects keyed by hostname, cache rules with urllib.robotparser, fetch with an HTTP client configured with explicit timeouts, and track one row per URL in a SQLite table storing its current state. On each iteration, pick the next host whose delay has expired, fetch one URL, and commit the updated state before moving on.
Deduplicate URLs and Page Content
Duplicate pages ruin crawlers from both ends. Weak deduplication wastes bandwidth, inflates storage bills, and skews downstream analytics when the same article gets captured under ten tracking parameters, a printer-friendly path, a paginated archive, and a syndicated copy. Aggressive deduplication is just as dangerous, because overzealous stripping rules can erase legitimate locale pages, regional inventory variants, or date-specific snapshots.
Even large open archives face this gap. According to the Common Crawl statistics documentation, duplicate captures pull unique URL counts and unique content digests noticeably below total page captures, which is why its CrawlDb tracks both completed URLs and the pending frontier.
Two Levels of Deduplication
Handle duplicates twice: once before a URL ever enters your queue, and again after you retrieve the page.
- Canonicalize URLs before enqueueing: Lowercase the hostname, strip default ports, resolve relative paths, collapse dot segments (
/.and/..), and filter query strings through a strict query-parameter allowlist that keeps only parameters proven to change page content (likepageorsku) while dropping marketing tags likeutm_source. - Fingerprint content after retrieval: Hash the normalized main text or key structured fields to catch exact duplicates hosted at different URLs. Add SimHash or MinHash fingerprinting when you need to detect near-duplicates caused by shifting sidebars, pagination chrome, or syndicated boilerplate.
- Preserve redirects and canonical links in your graph: Store redirect targets and
<link rel="canonical">targets instead of discarding the source URL. Keeping those edges intact protects your source attribution and tells your scheduler which canonical URL deserves future recrawl budget.
Storage Choices and Validation Loops
Back your pre-enqueue check with a distributed seen-URL store keyed by a hash of the normalized URL. A Bloom filter or HyperLogLog works well as a fast, low-memory preliminary filter in front of your frontier, but pair it with an authoritative key-value database whenever a false positive (accidentally skipping a valid, unseen URL) costs you business data.
Never guess at similarity thresholds in production. Sample several thousand fetched pages, label true duplicates by hand, tune your SimHash or MinHash cutoff against precision and recall, and alert on sudden duplicate-rate shifts by domain and page template.
Monitoring duplicate ratios per template catches site redesigns early. If a retail domain suddenly shifts from five percent near-duplicates to sixty percent overnight, a new session token probably leaked into their product URLs.
When to Render JavaScript and When Not To
Always default to raw HTTP requests and static HTML parsing. Fetching static markup handles most server-rendered pages at a fraction of the CPU, memory, and latency cost of running a browser. Escalating every URL to headless Chrome or Playwright is the fastest way to turn an affordable crawler into an infrastructure headache.
A real browser isn't just a heavier HTTP client. Launching one adds JavaScript execution, secondary network waterfalls, cookie state, timing variability, high RAM usage, and entirely new failure modes like crashed renderer processes. Modern crawlers need a hybrid router that inspects cheap static responses first and escalates only when page behavior proves it's necessary.

Signals That Justify Escalation
Three clear signals tell you raw HTML won't give you the data: an empty application root paired with a large JavaScript bundle (a client-side hydration shell), meaningful content that loads only after background XHR or Fetch calls, or items revealed solely through infinite scroll.
Before firing up a headless browser on those pages, open your browser's network tab and inspect the XHR traffic. Many single-page applications pull clean JSON from a backend endpoint that you can call directly over HTTP. Using a direct endpoint via web scraping with an API is faster, cheaper, and far less brittle than rendering the full DOM.
| Page Signal | Likely Meaning | Render Decision |
|---|---|---|
| Content present in raw HTML | Server-rendered page | Parse the HTML directly |
| Empty app root and large script bundle | Client-side hydration shell | Render, or look for the data API first |
| JSON request returns the needed data | API-backed content | Call the API directly |
| Content appears only after scrolling | Infinite scroll | Render with a fixed number of scroll actions |
| Login or consent wall in the response | Access barrier | Stop and log it; do not bypass authentication |
Controlling Browser Cost and Policy Risk
When a page requires browser execution, bound every interaction tightly. Replace open-ended waits with explicit waits for a target CSS selector, cap infinite scroll loops to a fixed number of actions, and verify that the rendered DOM yields materially better content than the raw HTML before you save it. Cache the winning strategy per URL pattern or page template so future crawl cycles skip detection and route straight to the cheapest path that works.
Checking your hybrid routing under realistic conditions matters just as much as writing the router itself. Reviewing Riff Analytics on crawler testing is a solid way to verify how your parser and browser fallback behave across layout variations before full deployment.
Policy awareness belongs in this routing layer too. Cloudflare's 2025 crawler analysis found that AI-related robots.txt directives appeared on roughly 14% of sampled leading domains in June 2025. Keeping your crawler lean, honoring host directives, and avoiding unnecessary browser page loads reduces origin strain and lowers your risk of triggering automated defenses. If a page hits an authentication gate or consent wall, log the barrier and move on rather than attempting to bypass it.
Pilot Small, Then Scale Your Crawler
Don't jump straight from a working prototype to crawling a million URLs. Your most impactful move is running a controlled pilot first. Pick a representative sample of about 1,000 URLs spread across the three most structurally different page templates in your target set, and run them through your full fetch pipeline with identical per-URL logging enabled.
Score the Pilot and Enforce Stop Checks
Evaluate your pilot against your observability baselines: valid responses per scheduled URL, unique content yield, bytes per successful page, median latency, retry rate, robots denials, and per-host saturation. Following disciplined performance benchmarking during this pilot gives you hard numbers for worker throughput and memory ceilings before you pay for extra servers.
Define automated circuit breakers before starting the run so a misbehaving job stops itself:
- Rising retry rates: Halt the crawl if your retry rate climbs across several consecutive cycles, which usually signals rate limiting, degraded proxies, or broken DNS resolution.
- Host concurrency saturation: Pause expansion if a single domain consumes most of your active worker pool, indicating a broken per-host queue or missing delay enforcement.
- Falling unique yield: Stop and inspect your parser if valid HTTP responses stay high while unique content yield drops, which points directly to soft errors, consent walls, or duplicate crawl traps.
Stage Your Growth and Weigh Build Versus Buy
Scale in deliberate steps from thousands to tens of thousands to millions of URLs, adding worker nodes and storage partitions only after the current tier runs cleanly across several full cycles. Once your baseline holds steady, flip on incremental recrawling using your stored content hashes so unchanged pages are skipped instead of re-downloaded on every pass.
Self-hosting a crawler gets exponentially more expensive when JavaScript rendering dominates your workload, because proxy rotation, browser memory, and anti-bot maintenance grow right alongside your URL count.
At that inflection point, weigh the engineering hours required to maintain a headless browser fleet against offloading the fetch tier. If browser rendering and proxy overhead start consuming your team's time, a managed scraping API like Scrappey can handle the browser and proxy layer while your frontier stays in-house, with 150 free scrapes to start and failed full-browser scrapes are free.
Your next move is concrete: assemble that 1,000-URL pilot across three distinct templates this week, wire up your per-host frontier, and record every core fetch field for every single URL before scaling up a single worker.
If JavaScript-heavy targets, residential proxy rotation, or browser maintenance are slowing down your crawler build, Scrappey gives you direct HTTP and full-browser endpoints (Chrome and Firefox) with built-in challenge handling and no browser infrastructure to manage. You can plug it straight into your existing frontier and pay only for successful scrapes. Start testing on your pilot URLs today at Scrappey.



