Sub topic 11
Crawl traps, depth limits, and page budgets
This chapter assumes you have read the chapters on URL normalization, the seen set, and the URL frontier. You should be comfortable with Python dictionaries, Counter, and urllib.parse. The question here is what happens when a site produces far more distinct URLs than it has distinct pages.
What a crawl trap is
A crawl trap is a part of a site that generates an unbounded, or just enormous, number of distinct URLs. The seen set cannot help, because each URL really is different as a string. A crawler without limits keeps fetching until it runs out of memory, disk, or patience, while the useful parts of the web wait in the frontier.
Traps are rarely malicious. Most come from ordinary features:
| Source | Example URL | Why it never ends |
|---|---|---|
| Calendars | `/events/2031/04`, `/events/2031/05`, ... | A "next month" link exists for every month, forever. |
| Relative link loops | `/a/b/a/b/a/b/page` | A bad relative link appends a segment each time the page is resolved. |
| Session IDs | `/page?sid=8f3a...` | Every visit receives a fresh ID, so every link is new. |
| Faceted search | `/shop?color=red&size=m&sort=price` | Filter combinations multiply, and the order of parameters can vary. |
| Search or sort pages | `/search?q=a`, `/search?q=aa` | The page itself links to more generated queries. |
| Infinite pagination | `/feed?page=90000` | The server returns an empty or repeated page instead of a 404. |
| Soft 404s | `/missing/anything` | The server answers 200 with a "not found" page that still has links. |
Some traps are accidental, but you treat them all the same way. You cannot reliably detect a trap from one URL. You can only bound how much damage any single region of the web can do.
Three kinds of limit
Defenses fall into three groups, and a real crawler uses all of them.
- Depth limits cap the number of link hops from a seed. A seed has depth 0. A link found on a depth-0 page has depth 1, and so on. Most useful content sits within a few hops of a seed or of a well-linked page. A depth cap of 6 to 10 stops runaway chains such as
/a/b/a/b/.... - Page budgets cap the total work. A global budget (
max_pages) ends the crawl. A per-host budget keeps one large or broken site from consuming the whole crawl. - URL shape heuristics reject URLs that look generated: very long URLs, many query parameters, repeated path segments, or too many URLs sharing one pattern.
Depth limits are weak against traps that are shallow but wide, such as faceted search, where every combination is one hop from the listing page. Budgets are weak at telling good pages from junk, since they stop the crawl but don't choose what to keep. Shape heuristics can reject legitimate URLs. That is why you combine them and tune the thresholds.
Tracking depth
The frontier from the earlier chapter stores plain URLs. To enforce depth, record the depth of each URL when you first admit it. A dictionary works:
depth = {} # url -> hops from a seed
# when seeding
depth[seed_url] = 0
# when processing a fetched page at `url`
child_depth = depth[url] + 1Store the depth at first discovery. Because the seen set drops later duplicates, the recorded depth is the one from the first path that reached the URL. In a breadth-first style crawl that is also the shortest path, which is what you want. If your frontier is prioritized instead of FIFO, the first path found may not be the shortest, so you may want to keep the smaller depth if you see a URL again.
Counting by pattern
The most effective defense against wide traps is to group URLs by shape and cap each group. A calendar produces /cal/2024/01, /cal/2024/02, and so on. If you replace each run of digits with #, they all become /cal/#/#. Faceted search becomes one group once you keep only the sorted parameter names and drop the values. After a group has admitted a fixed number of URLs, further URLs of that shape are dropped.
This does not tell you whether the group is a trap. It limits the cost of being wrong. A site with 10,000 real product pages under /product/<id> will also hit a pattern cap, so the cap must be generous (hundreds, not tens), or you should raise it for hosts you trust.
A limits object
The class below combines all the checks. It runs the cheap, stateless checks first and updates the counters only when a URL passes everything, so rejected URLs do not use up budget.
import re
from collections import Counter
from urllib.parse import parse_qsl, urlsplit
class CrawlLimits:
def __init__(self, max_depth=8, max_pages_per_host=500,
max_per_pattern=200, max_url_length=2000,
max_query_params=6, max_path_segments=12):
self.max_depth = max_depth
self.max_pages_per_host = max_pages_per_host
self.max_per_pattern = max_per_pattern
self.max_url_length = max_url_length
self.max_query_params = max_query_params
self.max_path_segments = max_path_segments
self.host_counts = Counter()
self.pattern_counts = Counter()
@staticmethod
def pattern(parts, query):
path = re.sub(r'\d+', '#', parts.path)
keys = '&'.join(sorted(key for key, _ in query))
return f'{path}?{keys}'
def allow(self, url, depth):
if depth > self.max_depth or len(url) > self.max_url_length:
return False
parts = urlsplit(url)
segments = [s for s in parts.path.split('/') if s]
if len(segments) > self.max_path_segments:
return False
if segments and max(Counter(segments).values()) >= 3:
return False # a segment repeated 3+ times suggests a loop
query = parse_qsl(parts.query, keep_blank_values=True)
if len(query) > self.max_query_params:
return False
host = parts.netloc
key = (host, self.pattern(parts, query))
if self.host_counts[host] >= self.max_pages_per_host:
return False
if self.pattern_counts[key] >= self.max_per_pattern:
return False
self.host_counts[host] += 1
self.pattern_counts[key] += 1
return True
limits = CrawlLimits(max_depth=3, max_per_pattern=2)
print(limits.allow('http://a.com/cal/2024/01', 1)) # True
print(limits.allow('http://a.com/cal/2024/02', 1)) # True
print(limits.allow('http://a.com/cal/2024/03', 1)) # False: pattern cap reached
print(limits.allow('http://a.com/a/b/a/b/a', 1)) # False: repeated segments
print(limits.allow('http://a.com/x', 4)) # False: too deep
print(limits.allow('http://a.com/x', 3)) # TrueTo use it, call limits.allow(link, child_depth) in the crawl loop right after normalize and before frontier.add. Record depth[link] = child_depth only when both the seen check and allow pass.
Where to enforce each limit
The check can run when a link is discovered, when it is dequeued, or both. Checking at discovery keeps the frontier small, which saves memory and keeps the seen set from filling with junk. Checking only at dequeue time is simpler but lets a trap fill the queue with millions of entries before any limit applies. The class above counts at discovery, so a host budget caps the URLs queued from that host, not the pages actually fetched. That is slightly stricter than a fetch budget, and it is usually the better choice because it bounds memory as well as network use.
The global max_pages budget in the crawl loop is different. It counts successful fetches, because it exists to bound the cost of the run.
Edge cases and gotchas
- Legitimate deep content. Forums, archives, and documentation can be deeper than your limit. A flat depth cap hurts them. Per-host overrides or a depth limit measured from the nearest well-linked page help.
- Soft 404s. A server that returns 200 for any path hides its dead ends from status-code checks. Content deduplication, covered in a later chapter, catches many of these because the "not found" bodies are identical.
- Session IDs in the path. Stripping a
sidquery parameter during normalization is safe only if you know the name. Pattern counting still protects you when you don't. - Redirect loops and chains. Cap redirects per fetch. A loop that varies the URL slightly is a trap at the HTTP level.
- Counter memory. The pattern counter grows with the number of distinct patterns. Over a very large crawl, prune counters for finished hosts or move them to disk.
- Politeness still applies. A trap on one host does not slow other hosts, because the per-host queues keep serving them. The budget still matters, since otherwise the trap's host would receive requests for the life of the crawl.
Exercises
Exercise
A site has 40,000 real article pages at /article/<number>, and a crawl with max_per_pattern=200 collects only about 200 of them. Give two ways to fix this without removing trap protection for other sites.
Show answer
The cap treats /article/# as one pattern, so it stops after 200 URLs. One fix is a per-host override that raises the pattern cap for hosts you trust or have verified. Another is to exempt patterns whose pages pass a quality check, for example pages whose content is distinct under content deduplication, so the cap only applies to groups that produce repeated or empty content. A third option is to size the cap relative to the host's budget instead of using one global number.
Exercise
A crawler checks depth only when it dequeues a URL, not when it discovers one. A calendar trap generates 30 new links per page. Why can memory still grow without bound, and where should the check move?
Show answer
Links found on a page at depth 3 are added to the frontier and the seen set even if they will later be rejected as too deep. Each fetched page adds 30 entries, so the queue and seen set keep growing while pages are still being fetched. Move the check to discovery time, before frontier.add, so over-deep, malformed, or over-budget URLs never enter the frontier or the seen set.