Sub topic 5
Avoiding repeat visits with a seen set
This chapter assumes you can read short Python programs, know how hash sets and queues work, and have read the chapter on URL normalization. A crawler that visits the same page twice wastes bandwidth and puts extra load on the site. Worse, a cycle of links can keep it running forever. A seen set is the structure that prevents this.
Why a crawler needs a seen set
The web is a graph, not a tree. Page A links to B, B links back to A, and the home page is linked from nearly every page. Without a record of past visits, a crawl would fetch the home page thousands of times.
The seen set holds every URL the crawler has already queued or fetched. Before a URL enters the frontier, the crawler checks the set. If the URL is present, it is dropped. If not, the crawler adds it to the set and to the frontier.
Mark URLs as seen when queued, not when fetched
There are two possible moments to record a URL as seen: when it is added to the frontier, or when it is fetched. Marking at fetch time is a common mistake. A URL linked from 500 pages would be queued 500 times before the first copy is fetched. The frontier would grow far larger than needed, and the same page would be fetched repeatedly.
The Frontier class from the earlier chapter marks at queue time:
def add(self, url):
if url in self.seen:
return
self.seen.add(url)
# ... queue the URL for its hostThe set therefore means "this URL has been scheduled at some point". That includes URLs that later fail, are blocked by robots.txt, or are never fetched because the page budget ran out.
The seen set depends on normalization
A set compares strings exactly. These URLs point to one page, but a set sees three different strings:
http://Example.com:80/ahttp://example.com/ahttp://example.com/a#section
The normalize function from the previous chapter maps all three to http://example.com/a. Always normalize first, then test the set. If the order is reversed, duplicates slip through.
Normalization cannot catch everything. These pairs still differ after it:
| URLs | Same page? | Handled by |
|---|---|---|
| `/a?x=1&y=2` and `/a?y=2&x=1` | Usually | Sorting query parameters, if you choose to |
| `/a` and `/a/` | Often | Site-specific rules |
| `/a?session=abc` and `/a?session=def` | Yes | Stripping known session parameters |
| `/a` and `/a?utm_source=mail` | Yes | Stripping tracking parameters |
Each extra rule risks merging two URLs that really are different pages. Add rules only when you see the duplication in real crawl data. Pages that look identical despite different URLs are handled later by content deduplication.
Choosing a data structure
How you store the seen set depends on how many URLs you expect.
In-memory set
A Python set of strings is the simplest option and is fast. It costs memory, though. A typical URL of 80 characters takes roughly 130 bytes as a Python string plus set overhead. One million URLs need on the order of 150 to 200 MB. At 100 million URLs, a single machine's memory is exhausted.
Hashing URLs to save memory
Store a fixed-size hash of each URL instead of the string. A 64-bit hash takes 8 bytes of payload, and a 128-bit hash takes 16.
import hashlib
def url_key(url):
return hashlib.blake2b(url.encode('utf-8'), digest_size=8).digest()
seen = set()
def is_new(url):
key = url_key(url)
if key in seen:
return False
seen.add(key)
return True
print(is_new('http://example.com/a')) # True
print(is_new('http://example.com/a')) # FalseHashing introduces a small chance of a collision, where two different URLs get the same key. The crawler would then wrongly skip one of them. With a 64-bit hash and n URLs, the probability of at least one collision is roughly n² / 2⁶⁵. For 100 million URLs (about 10⁸) that is 10¹⁶ / 3.7×10¹⁹, which is under 0.03 percent. For a larger crawl, use 128 bits.
Do not use Python's built-in hash() for this. For strings it is randomized per process, so the keys change on every run and cannot be saved to disk or shared between machines.
Bloom filter
A Bloom filter is a bit array plus several hash functions. To add an item, you set the bits at the positions its hashes point to. To test an item, you check whether all those bits are set. It uses far less memory than a set, often about 10 bits per URL for a 1 percent error rate.
It has one-sided errors:
- If it says "not seen", the URL is definitely new.
- If it says "seen", the URL is probably seen, but may be a false positive.
A false positive means the crawler skips a page it never fetched. Many large crawlers accept this, because losing 1 percent of pages is cheaper than the memory. The filter also cannot list or remove its contents, so it cannot answer "which URLs have we seen?".
On-disk or database storage
When the set outgrows memory, keep it in a key-value store or database table with a unique index on the URL or its hash. Each lookup costs a disk read, so crawlers usually put a small in-memory cache in front, or batch lookups. This option also survives a restart, which matters for checkpointing, covered in a later chapter.
Comparison
| Structure | Memory per URL | False positives | Survives restart | Typical use |
|---|---|---|---|---|
| Set of strings | 100+ bytes | None | No | Small crawls, teaching code |
| Set of 64-bit hashes | About 8 bytes plus overhead | Very rare | If saved | Medium crawls |
| Bloom filter | About 1 byte | Tunable, commonly 1% | If saved | Very large crawls |
| Database with unique index | Disk | None | Yes | Long-running or resumable crawls |
Edge cases
- Redirects. If
/oldredirects to/new, mark both as seen. Otherwise the crawler fetches/newthrough the redirect, then again when it finds a direct link. - Failures. A URL that failed with a timeout is already in the seen set, so it will not be queued again by a later link. Retries must be handled by a separate mechanism that re-enqueues it on purpose, not by the discovery path.
- Case in paths. Hosts are case-insensitive, but paths usually are not. Do not lowercase the path.
- Concurrency. With several threads, "check, then add" can race: two threads both see a URL as new. Either guard the check with a lock or use an atomic operation such as the return value of a database insert.
Putting it together
This version of the seen check stores hashes and is safe for use from several threads:
import hashlib
import threading
class SeenSet:
def __init__(self):
self._keys = set()
self._lock = threading.Lock()
@staticmethod
def _key(url):
return hashlib.blake2b(url.encode('utf-8'), digest_size=8).digest()
def add_if_new(self, url):
key = self._key(url)
with self._lock:
if key in self._keys:
return False
self._keys.add(key)
return True
def __len__(self):
return len(self._keys)
seen = SeenSet()
for link in ['http://example.com/', 'http://example.com/a', 'http://example.com/']:
print(link, seen.add_if_new(link))
print(len(seen)) # 2The method returns True only for the first caller, so the frontier can use it directly: if seen.add_if_new(url): queue.append(url).
Exercise
A crawler marks URLs as seen only after fetching them. A popular page is linked from 300 pages that are in the frontier at the same time. What goes wrong, and where should the mark move to?
Show answer
Each of the 300 pages queues the popular URL, because it is not yet in the seen set. The URL ends up in the frontier 300 times and is fetched repeatedly until the first fetch completes and marks it. The mark should happen when the URL is added to the frontier, so the second and later discoveries are dropped immediately.
Exercise
You crawl 2 billion URLs and use 64-bit hashes in a set. The collision probability is roughly n² / 2⁶⁵. Estimate it, and say whether you would switch to 128-bit hashes.
Show answer
n² is 4×10¹⁸. Dividing by 2⁶⁵ (about 3.7×10¹⁹) gives about 0.11, so there is around a 11 percent chance that at least one pair of URLs collides. That means one wrongly skipped page, which is usually tolerable, but the memory cost of 128-bit keys (16 bytes instead of 8) is also modest, so switching is a reasonable choice if you want no wrongly skipped pages.