Build a Polite Web Crawler with Letter-Coverage Ordering
Data Structure DesignModel answerLast updated
Design and implement a rate-limited article crawler that visits pages with unseen first letters before switching to random order, and explain how you would use an AI assistant to build it.
You have about 75 minutes, with an AI coding assistant available, to build a crawler for an online encyclopedia (for example, Wikipedia). The crawler starts from one seed article and follows links to other articles.
Ordering rule
The crawler tracks which letters A–Z have been "covered", meaning that a page whose title begins with that letter has been crawled.
- While some letters remain uncovered, the crawler prefers pages whose title starts with an uncovered letter. Pages whose initial is already covered are held back for now. For instance, if the seed is "Google", other pages starting with G are deferred.
- Once all 26 letters are covered, the crawler picks the remaining known pages at random.
- The crawler must obey a rate limit.
Questions to settle first
State your assumptions on each of these before coding:
- Is a letter covered when a page is discovered, or only after it is fetched successfully?
- How are titles starting with digits, punctuation or non-Latin characters handled? Is matching case-insensitive?
- What stops the crawl once all letters are covered (page budget, time budget, never)?
- How is the rate limit expressed, and does the server signal violations with error responses?
- Do you parse article HTML, or use an API that returns the links of a page?
Part 1: Crawl order
Implement the core: fetch a page, extract links to other articles, and choose the next page according to the coverage rule. Describe your frontier and visited-set design, how you normalize links and skip non-article pages, and what happens when no known page has an uncovered initial.
Part 2: Rate limiting
Make the crawler respect the limit and behave well when the server pushes back. Explain how your limiter can be tested without real waiting, how you handle rate-limit and transient errors (including retries), and what politeness measures you add beyond the limit itself.
Part 3: Working with the assistant
Explain how you would divide the work with the AI assistant during the 75 minutes, and how you keep the generated code understandable and correct.
Hints
Hint 1
Keep one bucket of pending titles per initial letter, plus a visited set. Picking the next page then becomes: choose from any bucket whose letter is uncovered, otherwise pick from all remaining pages.
Hint 2
Put the clock and the sleep function behind small interfaces so the limiter and the retry logic can be unit tested with a fake clock, and put the fetcher behind an interface so ordering can be tested on a fake link graph.
Hint 3
For the assistant, write the interfaces and a few failing tests yourself first, ask for one small component at a time, and read and run each piece before moving on.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify first (and state defaults)
I would settle these assumptions out loud before writing code:
- Covered means a page with that initial was fetched successfully. Discovery alone does not count, because a discovered page might fail or be skipped.
- Initial is the first character of the title, uppercased. Only A–Z count toward coverage. Titles starting with a digit, punctuation or a non-Latin letter go into an "other" bucket that is treated as covered from the start, so they are only reached in the random phase (or when no uncovered-letter page is known).
- Stopping: a maximum page count (for example 500) and an optional time limit. Without one, the random phase would never end.
- Rate limit: a configurable requests per second, for example 1 to 5.
- Data source: prefer the official API that returns a page's links over scraping HTML. It is more stable, cheaper, and easier to fake in tests.
Design
Components, each behind a small interface:
Fetcher.get_links(title) -> list[str](network, replaceable by a fake)Limiter.acquire()(paces requests, takes an injectable clock and sleeper)Frontier(what to crawl next)Crawler(the loop that ties these together)
Frontier
seen: set[str]holds normalized titles that were ever queued, so a page is never queued twice.buckets: dict[str, list[str]]maps each initial to a list of pending titles.covered: set[str]holds letters already fetched.
next() logic:
- Collect the letters with a non-empty bucket that are not covered. If any exist, pick one (smallest letter, or random) and pop a title from its bucket.
- If none exist but some letters are still uncovered, we have no preferred page. Fall back to any pending page (the crawl continues so that new links may reveal the missing letters). Document this choice: the alternative is to stop, but that would end most crawls early.
- If all 26 letters are covered, pick a random pending page. To get O(1) random pick and removal, keep pending items in a list and swap-remove a random index.
Mark the letter covered only after a successful fetch. Because a deferred page whose letter has since been covered stays in its bucket, it simply becomes eligible for the random phase.
Normalization and filtering
- Accept only main-namespace articles: skip titles with a namespace prefix such as
File:,Category:,Talk:,Special:,Help:. - Strip fragments (
#section) and query strings, decode percent-encoding, replace underscores with spaces (or the reverse, consistently), and capitalize the first character since titles are case-sensitive after the first character. - Resolve redirects when the API reports them, and store the canonical title in
seen. - Drop self-links.
Rate limiting
Use a token bucket or a simple "minimum interval" limiter: remember the time of the last request and sleep until last + 1/rate. With a single worker this is enough. With several workers, guard it with a lock, or use a token bucket with capacity equal to the allowed burst.
For testability, inject now() and sleep(). In tests, a fake clock records requested sleeps, and you assert that 10 requests at 2 rps ask for roughly 4.5 seconds of total waiting, without really waiting.
Server pushback
- On HTTP 429 or 503, honor
Retry-Afterif present, otherwise use exponential backoff with jitter (for example 1s, 2s, 4s, capped at 30s) with a retry limit of about 5. - Treat network timeouts and 5xx as transient and retry; treat 404 as permanent, record it and move on.
- After repeated 429s, lower the effective rate (adaptive slowdown).
Politeness beyond the limit
- Send a descriptive
User-Agentwith contact information. - Respect
robots.txtand use the API rather than hammering HTML pages. - Use a request timeout, keep connections alive, and avoid re-fetching pages (the
seenset). - Prefer a single worker or a very small pool; the rate limit applies globally, not per worker.
Crawl loop
def crawl(seed, fetcher, limiter, frontier, max_pages):
frontier.add(seed)
fetched = 0
while fetched < max_pages:
title = frontier.next()
if title is None:
break
links = fetch_with_retry(fetcher, limiter, title)
if links is None: # permanent failure
continue
frontier.mark_fetched(title) # marks the letter covered
fetched += 1
for link in links:
frontier.add(normalize(link))
Complexity: each page is added once, and next() costs O(26) to find an eligible bucket plus O(1) for the pop, so the crawler's own overhead is negligible compared with network time.
Testing
- Ordering: a fake
Fetcherover a small in-memory link graph, and a seeded random generator. Assert that an uncovered letter is always chosen before a covered one, and that the random phase begins only when all 26 are covered. - Limiter: fake clock as above.
- Retries: a fake fetcher that returns 429 twice and then succeeds; assert the backoff sleeps.
- Normalization: table-driven tests for fragments, namespaces, encoding and case.
Working with the AI assistant
- Plan before prompting (about 10 minutes): write the interfaces, the clarified rules and a short list of test cases myself. The assistant fills in implementations of components I have already specified.
- Small steps: ask for one component at a time (normalizer, then frontier, then limiter), each with tests. Run the tests before moving on.
- Review everything: read generated code line by line, delete anything I do not need, and ask for simplifications rather than accepting 300-line blocks I cannot explain.
- Use it for the boring parts: boilerplate, test tables, HTTP client wiring. Keep the ordering logic and the coverage rule in my own hands, since that is where subtle bugs live.
- Verify against the spec: finish with an end-to-end run against the fake graph, then a short, rate-limited run on the real site.
Common mistakes
- Marking a letter covered on discovery rather than on a successful fetch.
- Queuing the same article under several spellings (underscores, fragments, redirects).
- Ending the crawl when no uncovered-letter page is known, without defining the fallback.
- A limiter that uses real
sleepand cannot be tested. - Retrying without a cap or without jitter, which amplifies server overload.
- Accepting a large generated block without understanding it, then losing the remaining time debugging it.