Skip to main content
← CONCEPTS / DISTRIBUTED SYSTEMS
An end-to-end domain learning journey

Distributed Web Crawler &
Mercator URL Frontier.

The Mercator URL Frontier separates crawl priority (Front Queues) from per-host politeness (Back Queues) so high-priority domains are crawled fast without DDoSing any single origin server.
Start the journey7 sections· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To bound blast radius during partial cluster failures, route each hostname deterministically to one Back Queue with a per-host politeness timer (`10x` last RTT) and cached `robots.txt` rules.

TL;DR30-second simplified summary
▾

A naive FIFO queue of discovered URLs fails catastrophically at web scale: links from wikipedia.org cluster together and flood one host with thousands of concurrent requests (violating politeness and getting IP-banned), while high-value news pages wait behind millions of low-value forum links.

The Mercator URL Frontier splits scheduling into two stages: K Front Queues ordered by PageRank/freshness priority, and M Back Queues where a consistent-hash router maps every URL's hostname to exactly one Back Queue.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Consistent Hashing & Virtual Nodes
Consistent hashing assigns data keys to servers in a way that limits how many keys move when servers are added or removed. This helps avoid widespread cache misses and sudden load on databases.
Bloom Filters, Counting Bloom & Cuckoo Filters
Bloom filters answer set membership in O(k) bit probes using ~10 bits per key at a 1% false-positive rate with zero false negatives, while Cuckoo filters store compact fingerprints in 2-choice hash buckets to support safe item deletion and better CPU cache loc...
Full walkthrough · 7 stages
01
STAGE 01 · CORE INTUITIONfoundation

Core Intuition & Failure Mode.

Why this matters: Decouple crawl importance from per-host politeness so fast workers never DDoS a single origin server.

Think of Core Intuition & Failure Mode as the intuition layer for Distributed Web Crawler & Mercator URL Frontier: Decouple crawl importance from per-host politeness so fast workers never DDoS a single origin server.

The Mercator URL Frontier separates crawl priority (Front Queues) from per-host politeness (Back Queues) so high-priority domains are crawled fast without DDoSing any single origin server.

STAGE 01 · CORE INTUITION

Core Intuition & Failure Mode

Discovered URLsIngress StreamK Front QueuesImportance OrderM Back QueuesPoliteness ShardsReady-Time HeapPolite Dispatchhashes host

1.Naive FIFO Trap: A single priority queue sends 500 workers simultaneously to wikipedia.org, triggering IP bans.

2.Mercator Two-Stage Split: Front Queues rank URL importance; Back Queues enforce 1 active request + crawl-delay per host.

3.Work Conservation: Workers stay 100% busy across millions of other hosts while any single host cools down.

The Mercator Frontier separates priority Front Queues from per-host Back Queues to maximize throughput without DDoSing origins.

02
STAGE 02 · CORE MECHANICSfoundation

Architectural Mechanics.

Why this matters: Route hostnames consistently to Back Queues and pop the earliest-ready host from a min-heap.

Think of Architectural Mechanics as the intuition layer for Distributed Web Crawler & Mercator URL Frontier: Route hostnames consistently to Back Queues and pop the earliest-ready host from a min-heap.

The Mercator URL Frontier splits scheduling into two stages: K Front Queues ordered by PageRank/freshness priority, and M Back Queues where a consistent-hash router maps every URL's hostname to exactly one Back Queue.

STAGE 02 · CORE MECHANICS

Architectural Mechanics

Biased SelectorFront-to-BackConsistent HashSticky HostMin-Heap (ready_at)O(log M) PopAsync FetcherPolite Crawltracks next_ts

1.Biased Front Drain: Higher-priority Front Queues are sampled more frequently without starving lower-priority tiers.

2.Sticky Host Mapping: Hashing hostname -> Back Queue ensures only one queue tracks a domain's crawl-delay.

3.Dynamic Backoff: Add crawl_delay + 2 * last_rtt after each fetch so slow origins automatically slow down.

Biased Front-Queue draining, consistent host hashing, and a ready-time min-heap enforce adaptive per-host politeness.

Engineering Decision Framework
Problem
How to implement Distributed Web Crawler & Mercator URL Frontier without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To bound blast radius during partial cluster failures, route each hostname deterministically to one Back Queue with a per-host politeness timer (10x last RTT) and cached robots.txt rules.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Distributed Web Crawler & Mercator URL Frontier experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · SAFE IMPLEMENTATIONintermediate

Mercator Politeness Heap Scheduler.

Why this matters: Implement PolitenessFrontier with per-host deques and a min-heap that never dispatches before ready_at.

import heapq
from collections import deque

class PolitenessFrontier:
    def __init__(self) -> None:
        self.back_queues: dict[str, deque[str]] = {}
        self.ready_heap: list[tuple[float, str]] = []

def push(self, host: str, url: str, now: float) -> None:
        if host not in self.back_queues:
            self.back_queues[host] = deque()
            heapq.heappush(self.ready_heap, (now, host))
        self.back_queues[host].append(url)
STAGE 03 · SAFE IMPLEMENTATION

Mercator Politeness Heap Scheduler

push(host, url)Enqueueready_heapSchedule Indexpop_ready(now)Polite Guardreschedule(delay)Cooldown Updatepops due

1.One Entry Per Host: Keep at most one heap entry per active host to prevent heap bloat when a domain has 1M URLs.

2.Empty Deque Cleanup: Only re-insert (next_ready, host) into ready_heap if back_queues[host] remains non-empty.

3.O(log M) Scheduling: Heap size M equals active hosts—not total URLs—keeping pops fast even at 1B URLs.

Maintaining one heap entry per active host keeps scheduling O(log M) while strictly enforcing per-host cooldowns.

04
STAGE 04 · SCALING & TRADE-OFFSintermediate

Throughput & Latency Trade-Offs.

Why this matters: Scale URL deduplication and DNS resolution across 10,000+ pages/sec using Bloom filters and local DNS caches.

Think of Throughput & Latency Trade-Offs as the intuition layer for Distributed Web Crawler & Mercator URL Frontier: Scale URL deduplication and DNS resolution across 10,000+ pages/sec using Bloom filters and local DNS caches.

Evaluate asymptotic bounds, cache locality, and tail-latency impact under peak load.

STAGE 04 · SCALING & TRADE-OFFS

Throughput & Latency Trade-Offs

URL CanonicalizerDedup PrepPartitioned BloomSeen-URL FilterLocal DNS ResolverAvoid UDP Stall10K+ Pages / SecHigh Throughputresolves

1.URL Seen Set: A hash set of 10B URLs needs ~640 GB RAM; a partitioned Bloom/Cuckoo filter fits in ~12-18 GB.

2.DNS Bottleneck: Synchronous gethostbyname() blocks worker threads; use async c-ares/Unbound with local caching.

3.Disk Spillover: Back-queue tails spill to RocksDB/disk so billions of queued URLs never OOM frontier RAM.

URL canonicalization, partitioned Bloom filters, and async DNS caching sustain 10K+ pages/sec within bounded RAM.

05
STAGE 05 · FAULT ISOLATIONadvanced

Blast-Radius & Failure Isolation.

Why this matters: Quarantine crawler traps, infinite calendars, and tarpits with per-host depth caps and robots.txt caches.

Think of Blast-Radius & Failure Isolation as the intuition layer for Distributed Web Crawler & Mercator URL Frontier: Quarantine crawler traps, infinite calendars, and tarpits with per-host depth caps and robots.txt caches.

Isolate shared resources, apply bounded queues, and prevent retry amplification.

STAGE 05 · FAULT ISOLATION

Blast-Radius & Failure Isolation

robots.txt CacheCompliance GateTrap DetectorInfinite Loop CutTarpit TimeoutWorker ShieldHost QuarantineBlast-Radius Stopbounds fetch

1.Crawler Traps: Infinite calendar links (/2026/11/24/...) or session-ID URLs exhaust frontier queues unless depth-capped.

2.Strict Timeouts: Cap TCP connect, TLS handshake, and body size (e.g., 10 MB) so tarpits cannot pin workers.

3.5xx / 429 Backoff: Exponentially back off hosts returning 429/503 and cap consecutive failures per domain.

robots.txt caching, URL depth caps, and strict read timeouts isolate crawler traps and slow tarpits.

06
STAGE 06 · RECOVERY & CONSISTENCYadvanced

Durability, Consistency & Recovery.

Why this matters: Checkpoint frontier queues, seen-URL Bloom filters, and host cooldowns for crash-safe restarts.

Think of Durability, Consistency & Recovery as the intuition layer for Distributed Web Crawler & Mercator URL Frontier: Checkpoint frontier queues, seen-URL Bloom filters, and host cooldowns for crash-safe restarts.

Use idempotent state transitions, atomic commits, and deterministic replay.

STAGE 06 · RECOVERY & CONSISTENCY

Durability, Consistency & Recovery

Frontier WAL /RocksDBQueue PersistenceBloom + HeapSnapshotState BackupCrash RecoveryPolite RestartSimHash ContentDedupStorage Hygienerestores

1.Politeness Across Restarts: Persisting next_ready_ts prevents a restarted crawler from bursting all hosts at t=0.

2.In-Flight Lease: Mark popped URLs in-flight with a lease so crashed workers' URLs re-enter after timeout.

3.Content Deduplication: SimHash/MinHash fingerprints skip near-duplicate mirrors before indexing.

RocksDB-backed queues and persisted host cooldowns preserve crawl state and politeness across worker restarts.

07
STAGE 07 · OBSERVABILITY & GUARDRAILSadvanced

Telemetry, Circuit Breakers & Failure Modes.

Why this matters: Monitor frontier queue depth, 429/5xx block rates, DNS latency, and crawler-trap rejections.

Think of Telemetry, Circuit Breakers & Failure Modes as the intuition layer for Distributed Web Crawler & Mercator URL Frontier: Monitor frontier queue depth, 429/5xx block rates, DNS latency, and crawler-trap rejections.

Track p99 latency, retry/conflict ratios, and saturation metrics; fail fast with bounded retries and circuit breakers whenever invariants degrade.

STAGE 07 · OBSERVABILITY & GUARDRAILS

Telemetry, Circuit Breakers & Failure Modes

Front/Back QueueDepthCapacity Signal429 / 503 RatePoliteness SignalDNS Cache Hit RatioLatency SignalAuto-ThrottleGuardrail Actiondiagnoses

1.Politeness Feedback: Automatically double crawl-delay for any ASN or domain exceeding 2% 429 responses.

2.Trap Telemetry: Track URLs dropped by path-segment repetition rules to tune trap heuristics.

3.Worker Utilization: Alert if worker idle time rises while Front Queues are full—indicating Back-Queue starvation.

Tracking 429 rates, DNS hit ratios, and Back-Queue starvation keeps large-scale crawls fast and polite.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does Mercator split the URL Frontier into Front Queues and Back Queues?

Recommended Learning Flow