Alphabet-Coverage Web Crawler with Rate Limiting
Data Structure DesignModel answerLast updated
Build a crawler that prioritizes unvisited first-letters across a link graph while respecting a configurable requests-per-second ceiling.
Alphabet-Coverage Web Crawler with Rate Limiting
You are building a focused crawler that walks a web of encyclopedia-style pages. Each page has a title and contains links to other pages by title. Your crawler must explore pages intelligently, track which starting letters it has already encountered, and stay within a configurable request rate.
What you are given
- A start title (e.g.
"Python") from which crawling begins. - A fetch helper you can treat as injected:
fetch(title) -> (canonical_title, [linked_titles]). It raisesPageNotFoundfor titles that do not exist, andTransientErrorfor recoverable failures (timeouts, server errors). - A rate limit
R: the crawler must make at mostRrequests per second. - A maximum page count
max_pages: stop after successfully crawling this many pages.
What you must implement
A Crawler class (or equivalent) with at minimum:
crawl(start_title) -> list[str] # returns titles successfully crawled, in order
Your implementation must satisfy the following requirements:
Deduplication. Never fetch the same title twice. A title should also not sit in the frontier more than once.
Letter tracking. Maintain a set of first-letters (A–Z, case-insensitive) seen among successfully crawled pages. Titles that do not start with a letter (e.g. "1984") are crawlable but never contribute a letter and are never prioritized.
Selection policy.
- While any unseen letter has at least one candidate in the frontier, pick the next page from that group (uniformly at random among unseen-letter candidates).
- Once all 26 letters have been seen, or no frontier page starts with an unseen letter, pick the next page uniformly at random from the full frontier.
Rate limiting. Every HTTP attempt — including retries — must consume one token from a token-bucket limiter configured to R tokens per second.
Error handling.
- Transient errors: retry up to a configurable maximum with exponential backoff; each retry still consumes a rate-limit token.
- Permanent errors (
PageNotFound): skip the page, do not count it towardmax_pages, do not record its letter. - Redirect (canonical title differs from requested title): mark both as visited.
- Empty frontier: terminate cleanly.
Constraints and clarifications
- Titles are normalized: collapse underscores to spaces, strip fragment identifiers (
#Section), capitalize the first character, drop namespaced titles (File:,Category:,Help:, etc.). - You may assume
fetchis the only network call you need; all other logic must be your own. - Focus on correctness of the priority logic, deduplication, and rate limiting. You are expected to be able to walk through the code and explain every design decision.
Example trace
start: "Python" # 'P' added to seen letters
frontier after first fetch might include:
"Guido van Rossum" # 'G' — unseen, prioritized
"Programming language" # 'P' — seen, not prioritized
"Amsterdam" # 'A' — unseen, prioritized
...
next pick: random choice among {'G...', 'A...', ...} unseen-letter candidates
What a complete answer looks like
- A working implementation in Python (or a language of your choice).
- Clear explanation of the data structures chosen and why.
- Time and space complexity analysis.
- A walkthrough of at least three edge cases.
Hints
Hint 1
The selection policy has two distinct phases. Think about what data structure lets you maintain per-letter buckets and a global pool simultaneously, so you can serve both phases in O(1) or O(26) without rebuilding anything.
Hint 2
A standard token bucket needs only two fields of state — current token count and last refill timestamp — plus a sleep call. Use a monotonic clock, not wall time, to avoid jumps from clock corrections.
Hint 3
Deduplication needs to happen in two places: when a title is enqueued (skip if already visited or already in the frontier) and when a canonical title comes back from fetch (mark it visited even if it differs from the title you requested).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has three mostly independent concerns — frontier management, rate limiting, and error handling — that compose cleanly if you separate them from the start.
Data structures
RandomSet is the core building block. It needs O(1) add, contains, remove, and uniform-random pop. A dict mapping item → index into a list achieves this: to remove an element, swap it with the last element, update the index map, and pop the list tail.
Frontier consists of:
- One
RandomSetper letter A–Z (26 buckets). - One global
RandomSetcontaining every frontier title.
Adding a title touches the global pool plus its letter's bucket. Popping touches the same two. Both are O(1). Selection logic only needs to scan 26 buckets to find non-empty unseen-letter ones, so it is O(26) = O(1).
Token-bucket rate limiter stores tokens (a float) and last_refill_time. On every acquire() call, refill tokens proportional to elapsed time, cap at capacity, consume one token if available, otherwise sleep the fractional wait. Use time.monotonic to avoid wall-clock jumps.
Selection policy in detail
unseen_candidates = [letter for letter in A–Z
if letter not in seen_letters
and bucket[letter] is non-empty]
if unseen_candidates:
letter = random.choice(unseen_candidates)
title = bucket[letter].pop_random()
pool.remove(title) # keep pool consistent
else:
title = pool.pop_random()
letter = letter_of(title)
if letter:
bucket[letter].remove(title) # keep bucket consistent
The key invariant: a title lives in exactly one bucket (or none, if its first character is not A–Z) and always in the pool. Popping from one side requires a removal from the other side, but both are O(1).
Complete Python implementation
import random, time
from typing import Callable, Dict, List, Optional, Set, Tuple
SKIP_NS = {"file","category","help","special","talk",
"template","wikipedia","portal","user","image"}
class PageNotFound(Exception): ...
class TransientError(Exception): ...
# ── O(1) add / remove / random-pop ──────────────────────────────────────
class RandomSet:
def __init__(self):
self._items: List[str] = []
self._idx: Dict[str, int] = {}
def add(self, x: str):
if x not in self._idx:
self._idx[x] = len(self._items)
self._items.append(x)
def remove(self, x: str):
i = self._idx.pop(x, None)
if i is None:
return
last = self._items.pop()
if i < len(self._items): # swap with tail
self._items[i] = last
self._idx[last] = i
def pop_random(self, rng: random.Random) -> str:
x = self._items[rng.randrange(len(self._items))]
self.remove(x)
return x
def __contains__(self, x): return x in self._idx
def __len__(self): return len(self._items)
# ── Token-bucket limiter ─────────────────────────────────────────────────
class RateLimiter:
def __init__(self, rate: float, capacity: float = 1.0):
self.rate, self.capacity = rate, capacity
self.tokens = capacity
self.last = time.monotonic()
def acquire(self):
while True:
now = time.monotonic()
self.tokens = min(self.capacity,
self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1.0:
self.tokens -= 1.0
return
time.sleep((1.0 - self.tokens) / self.rate)
# ── Helpers ───────────────────────────────────────────────────────────────
def normalize(raw: str) -> Optional[str]:
t = raw.split("#", 1)[0].replace("_", " ").strip()
t = " ".join(t.split())
if not t:
return None
if ":" in t and t.split(":", 1)[0].lower() in SKIP_NS:
return None
return t[0].upper() + t[1:]
def first_letter(title: str) -> Optional[str]:
c = title[0].upper()
return c if "A" <= c <= "Z" else None
# ── Crawler ───────────────────────────────────────────────────────────────
class Crawler:
def __init__(
self,
fetch: Callable[[str], Tuple[str, List[str]]],
rate: float,
max_pages: int = 100,
max_retries: int = 2,
backoff: float = 0.5,
seed: Optional[int] = None,
):
self.fetch = fetch
self.limiter = RateLimiter(rate)
self.max_pages = max_pages
self.max_retries = max_retries
self.backoff = backoff
self.rng = random.Random(seed)
def crawl(self, start: str) -> List[str]:
start = normalize(start)
if not start:
return []
visited: Set[str] = set()
seen_letters: Set[str] = set()
pool: RandomSet = RandomSet()
buckets: Dict[str, RandomSet] = {c: RandomSet()
for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
crawled: List[str] = []
def enqueue(title: str):
t = normalize(title)
if t and t not in visited and t not in pool:
pool.add(t)
ltr = first_letter(t)
if ltr:
buckets[ltr].add(t)
def pick_next() -> Optional[str]:
if not pool:
return None
unseen = [c for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if c not in seen_letters and len(buckets[c]) > 0]
if unseen:
ltr = self.rng.choice(unseen)
title = buckets[ltr].pop_random(self.rng)
pool.remove(title)
else:
title = pool.pop_random(self.rng)
ltr = first_letter(title)
if ltr:
buckets[ltr].remove(title)
return title
enqueue(start)
while crawled and len(crawled) >= self.max_pages:
break # handled below; loop starts with check
while len(crawled) < self.max_pages:
title = pick_next()
if title is None:
break # frontier exhausted
visited.add(title)
canonical, links = None, None
for attempt in range(self.max_retries + 1):
self.limiter.acquire()
try:
canonical, links = self.fetch(title)
break
except PageNotFound:
break # permanent — skip
except TransientError:
if attempt < self.max_retries:
time.sleep(self.backoff * (2 ** attempt))
# each retry already consumed a token via acquire()
if links is None: # fetch never succeeded
continue
# handle redirect
c = normalize(canonical) if canonical else title
if c and c != title:
visited.add(c)
pool.remove(c)
ltr_c = first_letter(c)
if ltr_c:
buckets[ltr_c].remove(c)
crawled.append(title)
ltr = first_letter(title)
if ltr:
seen_letters.add(ltr)
for raw in links:
enqueue(raw)
return crawled
Complexity
- Time: O(E + 26·V) where V = pages crawled, E = total links extracted. The O(26) factor is the unseen-letter scan per selection step. Wall-clock time is dominated by the rate limit: roughly V/R seconds.
- Space: O(V + F) where F = frontier size. Each title lives in the global pool and at most one bucket; both are string references, so there is no duplication of content.
Edge cases worth calling out
- Non-A–Z titles (
"1984","Ångström"): they enqueue and crawl normally but never enter a bucket and never add a letter toseen_letters. They are only reachable once all 26 letters are seen (random phase) or if they are the only things left in the frontier. - Redirect chains:
fetch("U.S.")might return canonical"United States". Both are marked visited immediately, and"United States"is removed from the frontier if it was already there. - All frontier pages share one letter before that letter is seen: the unseen-letter scan finds only that bucket non-empty, so the crawler still makes progress rather than stalling.
- Transient errors eat rate-limit tokens: this is intentional. "At most R requests per second" applies to every network attempt, not just successful ones.
Common mistakes
- Forgetting to remove a title from both the bucket and the pool when popping it — this leaves stale references and can cause double-crawling.
- Marking a letter seen on a failed fetch. The letter should only be recorded after a confirmed successful crawl.
- Using
time.time()in the rate limiter, which can jump backward under NTP corrections.time.monotonic()is the correct choice. - Checking
visitedonly at dequeue time rather than also at enqueue time, which lets the frontier balloon with duplicates.