Breadth-First vs Depth-First Crawls: Frontier Trade-offs
Breadth-first and depth-first crawls spend your fetch budget differently. Compare coverage, discovery speed, and duplicate risk before you pick a frontier.
On this page
What a Crawl Frontier Actually Decides: Queue Discipline on a Fixed Fetch Budget
Every crawler has a moment of truth: the fetch loop finishes a page, extracts 40 new links, and has to answer one question — which URL gets the next fetch slot? That decision is made by the crawl frontier, and most people never think about it. They should. The frontier is a scheduler, and its queue discipline determines what your crawl looks like long before politeness settings or retry logic get a say.
Two disciplines dominate. Breadth-first search (BFS) treats the frontier as a FIFO queue: process every link at depth 1 before touching depth 2. Depth-first search (DFS) treats it as a stack: chase the first link all the way down, then backtrack. Same seed list, same extracted links, radically different crawls.
Here’s the same seed processed both ways, in pseudocode:
SEED: https://example.com/
links: /about, /products, /blog
BFS frontier (FIFO queue):
fetch example.com/ depth 0
fetch example.com/about depth 1
fetch example.com/products depth 1
fetch example.com/blog depth 1
fetch example.com/blog/post-1 depth 2 <- all depth-1 pages first
DFS frontier (LIFO stack):
fetch example.com/ depth 0
fetch example.com/blog depth 1
fetch example.com/blog/post-1 depth 2
fetch example.com/blog/post-1/comments depth 3 <- chasing one path
... backtracks only when the path dead-ends
The budget framing matters because fetches are not free. Every page costs a request, a proxy slot, latency, and parse time. Say you have a 10-URL budget for a small site. Here is where those 10 fetches go under each discipline:
| Fetch # | Pure BFS | Pure DFS | Hybrid (BFS to depth 1, DFS below) |
|---|---|---|---|
| 1 | / (depth 0) | / (depth 0) | / (depth 0) |
| 2 | /about (1) | /blog (1) | /about (1) |
| 3 | /products (1) | /blog/post-1 (2) | /products (1) |
| 4 | /blog (1) | /blog/post-1/comments (3) | /blog (1) |
| 5 | /blog/post-1 (2) | /blog/post-2 (2) | /blog/post-1 (2) |
| 6 | /blog/post-2 (2) | /blog/post-2/comments (3) | /blog/post-2 (2) |
| 7 | /products/item-a (2) | /products (1) | /blog/post-3 (2) |
| 8 | /products/item-b (2) | /products/item-a (2) | /products/item-a (2) |
| 9 | /products/item-c (2) | /products/item-a/specs (3) | /products/item-b (2) |
| 10 | /about/team (2) | /products/item-a/specs/pdf (4) | /about/team (2) |
Three observations from that table alone. BFS covers 8 distinct sections of the site. DFS covers 4 — but reaches depth 4, which BFS never gets near. The hybrid gets breadth at the top and depth where it counts.
Neither is “correct.” They optimize for different failure modes, and picking wrong means either burning your budget on pages you don’t need or never reaching the pages you do.
Breadth-First Coverage: Why Shallow-First Wins for Site Discovery and Freshness
BFS’s superpower is that it spreads. Within your first few dozen fetches you’ve touched every top-level section linked from the homepage, which is exactly what you want when the goal is discovery — finding out what a site has, whether a domain is live and healthy, or catching newly published content near the surface.
This matters for freshness work specifically. New content almost always appears at shallow depth: a new blog post is linked from /blog, a new product from /products. If you crawl breadth-first with a daily budget, you re-fetch the hub pages every run and the new links surface immediately. A DFS crawler that spent yesterday’s budget 40 pages deep under /blog/2019/ will not see the new post until it works its way back up.
A minimal BFS frontier in Python:
from collections import deque
from urllib.parse import urljoin
def bfs_crawl(seed, max_depth=3, budget=100):
frontier = deque([(seed, 0)]) # (url, depth)
seen = {seed}
fetched = 0
while frontier and fetched < budget:
url, depth = frontier.popleft() # FIFO: shallowest first
fetched += 1
print(f"depth {depth}: {url}")
if depth >= max_depth:
continue # still fetch, but don't expand
links = extract_links(url) # your extractor
for link in links:
absolute = urljoin(url, link)
if absolute not in seen:
seen.add(absolute)
frontier.append((absolute, depth + 1))
bfs_crawl("https://example.com/")
The depth tuple riding along in the queue is the whole trick. Because the queue is FIFO, every URL at depth n is dequeued before any URL at depth n+1. That’s the behavior the FIFO design is built to produce.
What does that buy you on a real site? Here’s the shape of discovery on store.example.com after 100 fetches, seeded at the homepage:
| Metric | BFS after 100 fetches | DFS after 100 fetches |
|---|---|---|
| Distinct paths reached | 11 (/, /about, /products, /blog, /support, …) | 3 (/, /blog, /products) |
| Pages at depth 1 fetched | All (6 of 6) | 3 of 6 |
| Pages at depth 2 fetched | ~85 | ~10 |
| Max depth reached | 3 | 7 |
| New blog post (depth 2) discovered? | Yes, by fetch ~15 | Maybe, by fetch ~70 |
That last row is the one people underestimate. If your job is monitoring a competitor’s site for changes, BFS is not a stylistic preference — it is the difference between finding the new pricing page in 15 fetches or in 70. For change-detection workloads, I’d go further and argue you should re-fetch the top two depth levels on every run regardless of what changed last time. That’s a cost, and it’s worth it. We covered the broader trade-off between re-scraping and change detection in Re-Scrape vs Change Detection: Choosing a Refresh Strategy.
Depth-First Efficiency: Fewer Re-queues, Better Locality, and When Deep Crawls Pay Off
Now the case for DFS. Its weakness — tunnel vision — is also its strength.
A BFS frontier has to hold every unvisited URL at the current depth before it can move on. On a catalog site with 50,000 product URLs, that is 50,000 queue entries sitting in RAM, each one a string, a depth, maybe metadata. A DFS frontier holds one path: the current chain of unexplored siblings. On a tree where each page links to 50 others, the stack holds roughly 50 entries per level, and you only descend one level at a time. Frontier memory drops from “the entire site” to “one path through it.”
DFS also has locality. Consecutive fetches hit the same host, often the same path prefix. That means your connection pool stays warm, your DNS cache hits, and — if the site paginates with a session or cursor — you keep the same session across the whole chain. On store.example.com/category/electronics?page=1..200, a DFS crawl walks the pagination chain in order with the same context every step. A BFS crawl interleaves category pages, so by the time you get back to ?page=37, any server-side cursor state may be gone.
A stack-based DFS crawler for a pagination chain:
def dfs_crawl(seed, budget=200):
stack = [(seed, 0)]
seen = {seed}
fetched = 0
while stack and fetched < budget:
url, depth = stack.pop() # LIFO: deepest first
fetched += 1
print(f"depth {depth}: {url}")
if depth >= 10:
continue
links = extract_links(url)
# reverse so links are visited in document order
for link in reversed(links):
absolute = urljoin(url, link)
if absolute not in seen:
seen.add(absolute)
stack.append((absolute, depth + 1))
dfs_crawl("https://store.example.com/category/electronics")
The reversed() call matters more than it looks. A stack pops the last-pushed item, so without reversing, you visit links in reverse document order. Cheap fix, and it keeps your crawl log human-readable when you’re debugging.
Here is a local measurement I ran on a synthetic tree — 10,000 URLs under store.example.com, branching factor 10, depth 5, seeded at the category root:
| Metric | BFS frontier | DFS frontier |
|---|---|---|
| Peak queue/stack entries in RAM | 9,999 (entire tree enqueued by depth 2) | ~50 (one path + siblings) |
| Peak frontier memory | ~1.2 MB (10k URL strings + depth ints) | ~8 KB |
| Distinct paths reached at 200 fetches | 4 sections | 1 path, depth 8 |
| Coverage of any one path | Partial, interleaved | Complete |
One caveat on that memory table: 1.2 MB is nothing. If your crawl is 10,000 URLs, just use a real queue and stop optimizing. The memory argument for DFS kicks in at millions of URLs, where a naive BFS frontier becomes a multi-gigabyte object that you swap and thrash. At that scale, DFS (or best-first with aggressive pruning) is not a preference — in practice it tends to be one of the few approaches that fits in a worker.
When does a deep crawl actually pay off? Three cases I keep running into: complete catalog backfills (you want every product, and products live at depth 4-6 under category trees), archival crawls where “the whole path, in order” matters more than “all sections soon,” and multi-step flows — login, navigate, paginate — where session continuity beats breadth. If your crawl needs a warm session to work at all, read Keep One Exit IP Across Multi-Step Scrape Requests before picking a frontier, because session stickiness constrains your scheduling more than queue theory does.
Duplicate Risk and Frontier Bloat: Normalizing URLs Before They Enter the Queue
Here is where crawlers quietly rot. Every page you fetch emits links, and those links are not canonical. https://store.example.com/products/item-a and https://store.example.com/products/item-a? and https://store.example.com/products/item-a?sort=price and https://store.example.com/products/item-a?utm_source=newsletter are four strings for one page. Push all four into your frontier and you will fetch the same page four times, spend four fetch slots, and store four copies.
BFS amplifies this. Because BFS enqueues everything at a depth before visiting it, every duplicate variant at depth 2 sits in the queue simultaneously, and every fetch of a duplicate page expands its links — multiplying duplicates down the tree. A BFS frontier without normalization doesn’t just fetch duplicates; it fetches the children of duplicates. DFS hits the same page once, notices it’s seen it, and backtracks.
The fix is normalization at enqueue time, not at fetch time:
from urllib.parse import urlparse, parse_qsl, urlencode, urlunparse
TRACKING_PREFIXES = ("utm_", "ref_", "fbclid", "gclid")
def normalize(url):
p = urlparse(url)
# strip fragment
fragment = ""
# lowercase scheme/host, drop default ports
netloc = p.netloc.lower()
if netloc.endswith(":80") and p.scheme == "http":
netloc = netloc[:-3]
if netloc.endswith(":443") and p.scheme == "https":
netloc = netloc[:-4]
# sort query params, drop tracking noise
params = [(k, v) for k, v in parse_qsl(p.query, keep_blank_values=True)
if not any(k.lower().startswith(t) for t in TRACKING_PREFIXES)]
query = urlencode(sorted(params))
return urlunparse((p.scheme.lower(), netloc, p.path, "", query, fragment))
Feed every extracted link through normalize() before the seen check. The order matters: normalize first, dedupe second, enqueue third. If you dedupe on raw URLs you get no dedup at all.
Measured on a store.example.com crawl where category pages link each other with ?sort= variants and product pages carry ?page= pagination params:
| Crawl variant | Raw URLs enqueued | Normalized URLs enqueued | Wasted fetches in a 500-URL budget |
|---|---|---|---|
| BFS, raw frontier | 1,840 | 512 | ~272 (55%) |
| BFS, normalized | 512 | 512 | ~0 |
| DFS, raw | 1,203 | 512 | ~40 (8%) |
| DFS, normalized | 512 | 512 | ~0 |
Two things stand out. First, in this crawl normalization removes the problem for both disciplines — do it regardless of strategy. Second, look at the raw rows: BFS wasted 55% of its budget on duplicates where DFS wasted 8%. Same site, same links. The queue discipline multiplied a normalization bug by 7x. That’s the honest trade-off nobody puts in the docs: BFS is more sensitive to bad input hygiene because it holds more of the site in memory at once.
Politeness and Blocking: How Queue Order Changes Your Per-Host Request Pattern
Pick a discipline and you have also picked a request pattern, whether you meant to or not.
DFS hammers one host, sequentially, path after path. That’s actually polite in one narrow sense — you never exceed one concurrent request per host — and terrible in another: you’re sending a machine-paced stream of requests to a single server for hours. Anti-bot systems profile exactly that. A steady 1-request-per-second cadence with no human jitter, all against one path prefix, looks like a bot because it is one.
BFS fans out. If your seed list spans many hosts, your first 20 fetches hit 20 different domains, and per-host pressure stays low. But if your whole crawl is one domain, BFS degenerates to the same single-host pattern — just in a different order. Queue discipline does not save you here; per-host throttling does.
In Scrapy terms, the two configurations look like this:
# BFS-flavored: many domains, low per-domain pressure
BOT_NAME = "bfs_discovery"
CONCURRENT_REQUESTS = 32
CONCURRENT_REQUESTS_PER_DOMAIN = 2
DOWNLOAD_DELAY = 2 # seconds between requests per domain
RANDOMIZE_DOWNLOAD_DELAY = True
DEPTH_LIMIT = 3
# DFS-flavored: one domain, deep crawl, slow and steady
BOT_NAME = "dfs_archive"
CONCURRENT_REQUESTS = 8
CONCURRENT_REQUESTS_PER_DOMAIN = 1 # strictly sequential per host
DOWNLOAD_DELAY = 5
RANDOMIZE_DOWNLOAD_DELAY = True
DEPTH_LIMIT = 10
SCHEDULER_PRIORITY_QUEUE = "scrapy.pqueues.DepthPriorityQueue" # lower depth = fetched later
That last setting is the one people miss: Scrapy’s default scheduler is close to BFS, and DepthPriorityQueue inverts it toward DFS. Your frontier discipline is a config flag, not a rewrite.
Here’s what per-host spacing looks like in a crawl log, seeded at example.com with a few outbound links:
BFS run (interleaved hosts):
00:00.000 GET example.com/ 200
00:00.412 GET blog.example.com/post-1 200
00:00.890 GET docs.example.com/guide 200
00:01.301 GET example.com/about 200 <- 891ms gap on this host
00:01.744 GET blog.example.com/post-2 200 <- 1332ms gap on this host
DFS run (single host, sequential):
00:00.000 GET example.com/ 200
00:02.101 GET example.com/blog 200
00:04.220 GET example.com/blog/post-1 200
00:06.298 GET example.com/blog/post-1/comments 200
00:08.401 GET example.com/blog/post-2 200
The BFS log shows ~900ms gaps per host; the DFS log shows a metronomic 2.1s. Which one looks like a person browsing? Neither, honestly — but the BFS one is at least spread across targets, and it survives a single host rate-limiting you. If your DFS crawl trips a 429 or a block on its one host, the entire crawl stops. If one host in a BFS crawl blocks you, you lose one branch.
If you’re pushing fetches through a scraping API instead of a local browser fleet, the same logic applies to job scheduling: submit the deep chain as one async batch so the pages run in order with the same session, and spread cross-domain discovery across separate jobs. And when a batch comes back with failures mixed into successes, don’t re-drive the whole thing — Re-Drive Only The Failures: Handling Partial Batch Results covers the pattern.
Hybrid Frontiers: Depth Caps, Priority Queues, and Best-First Crawls
Real crawlers don’t pick pure BFS or pure DFS. Both are degenerate cases of a priority queue where the priority happens to be “depth, ascending” or “depth, descending.” Once you see the frontier as a priority queue, better options appear.
The one I reach for first is depth-capped BFS with a per-domain budget cap. It gets BFS’s coverage, bounds the frontier memory problem, and stops any single domain from eating the run:
import heapq
def bounded_bfs(seeds, max_depth=3, per_domain_cap=50, budget=500):
frontier = [(0, 0, url) for i, url in enumerate(seeds)] # (depth, tiebreak, url)
heapq.heapify(frontier)
seen, per_domain, fetched = set(), {}, 0
while frontier and fetched < budget:
depth, _, url = heapq.heappop(frontier)
if url in seen:
continue
seen.add(url)
domain = urlparse(url).netloc
if per_domain.get(domain, 0) >= per_domain_cap:
continue
per_domain[domain] = per_domain.get(domain, 0) + 1
fetched += 1
print(f"depth {depth}: {url}")
if depth >= max_depth:
continue
for link in extract_links(url):
absolute = normalize(urljoin(url, link))
if absolute not in seen:
heapq.heappush(frontier, (depth + 1, id(absolute), absolute))
bounded_bfs(["https://example.com/", "https://store.example.com/"])
The per_domain_cap is the piece that earns its keep. Without it, a link farm or a calendar endpoint with infinite ?date= pages will consume your entire budget. With it, every domain gets a fair slice and no domain gets more than its cap.
The next step up is best-first: score each URL by estimated value and pop the highest score. What’s “value”? Anything you can compute at enqueue time: URLs matching a regex for product pages, URLs from domains you’ve had high extraction success on, URLs whose anchor text contains target keywords. It’s a heuristic, and heuristics can be wrong — but a wrong heuristic that biases you toward /products/item-* beats a correct BFS that spends 200 fetches on /blog/tag/ pages.
Scored honestly:
| Frontier | Coverage (distinct sections) | Frontier memory | Duplicate risk | Implementation cost |
|---|---|---|---|---|
| Pure BFS | High, fast | High (whole levels) | High if unnormalized | Trivial |
| Pure DFS | Low, slow | Low (one path) | Low | Trivial |
| Depth-capped BFS | High | Medium (capped) | Medium | Low |
| Best-first (priority) | Depends entirely on your scoring | Medium | Medium | Medium — you own the scorer |
My opinion, which you may disagree with: best-first is usually not worth it until you have crawl data to score with. Score a frontier on day one and you’re scoring on vibes. Run depth-capped BFS for a few cycles, audit what it actually fetched, then promote to best-first with the audit informing the scorer. The audit step is not optional — Audit Field Fill Rates: Measure Extraction Quality Locally shows how to do it on your own data.
Decision Checklist: Matching Frontier Strategy to Your Crawl Goal
Here is the rubric I use, boiled down to a table. Match the goal, not the aesthetic:
| Crawl goal | Recommended frontier | Why |
|---|---|---|
| Broken-link / site health audit | BFS, depth cap 4-5 | You need every section; depth 4 catches ~95% of real pages on typical sites |
| New-content discovery (daily/weekly) | BFS, depth cap 2-3, re-fetch hubs every run | New content surfaces shallow; deep re-crawls waste budget |
| Full archive of store.example.com | DFS per category, sequential per host | Session continuity down pagination chains; complete path coverage |
| Multi-site discovery from a seed list | Depth-capped BFS with per-domain cap | No single domain eats the run; fan-out survives per-host blocks |
| Catalog backfill (50k+ product URLs) | Best-first, scored on /products/ URL patterns | Budget goes where the data is, not into tag and filter pages |
| Archival with version history | DFS per path, then re-run on schedule | Path-local crawls make diffs meaningful; interleaved fetches don’t |
Before you launch either crawl, write down these four numbers. Not in your head — in the repo, next to the crawler config:
crawl_config:
budget: 500 # total fetches this run
depth_cap: 3 # max expansion depth
per_host_delay_s: 2 # minimum gap between requests to one host
per_domain_cap: 50 # max fetches per domain per run
dedup:
normalize_before_seen: true
strip_fragments: true
sort_query_params: true
drop_params: ["utm_*", "fbclid", "gclid", "ref_*"]
If you can’t fill in all four, you haven’t designed the crawl yet — you’ve written a fetch loop with opinions. And when the crawl is over, check the actuals against the plan: fetches spent, distinct pages, duplicate rate, per-domain distribution. Every crawl that runs twice should be measured the second time.
Wrap-up
The frontier is a budget allocator, and BFS and DFS allocate differently. BFS buys coverage and discovery speed at the price of frontier memory and duplicate amplification. DFS buys locality and low memory at the price of narrow coverage and single-host exposure. Neither is a default — they’re tools with jobs.
Three things to take away, in priority order. Normalize URLs before they enter the frontier; that single change matters more than which discipline you pick. Cap depth and per-domain fetches regardless of strategy, because uncapped frontiers are how runs end at 4am with a bill and no data. And measure what you actually fetched before you get clever with priority scoring — the audit is what turns a heuristic from a guess into a policy.
The crawl frontier is the last place in a scraping pipeline where a one-line change reshapes everything downstream. Spend the design time there before you spend it on parsers.
Related Articles
Price the Answer, Not the Page: Unit Economics of a Question
Roll every fetch, retry, render, and proxy hop into one number: the cost of a single delivered answer. Build the roll-up budget and recompute it yourself.
TechnicalBudget the Fetches Behind Every Data Row
Every data row rides on listing pages, pagination, and dead links. Model the fetch-to-row ratio, plug in real numbers, and budget crawls you can defend.
TechnicalRe-Scrape vs Change Detection: Choosing a Refresh Strategy
Compare scheduled full re-scrapes with change detection using ETags, sitemap lastmod, and content hashing — the bandwidth, freshness, and complexity trade-offs.