Crawl a Web-Served Labyrinth Through Unreliable Responses
Trees & GraphsModel answerLast updated
Write a crawler that explores a maze of HTTP endpoints to find the exit, coping with cycles, transient 503 errors and malformed JSON, while guaranteeing termination.
You are handed the entrance URL of a maze that is served over HTTP. Each location in the maze is its own endpoint. Sending a GET request to a location returns a JSON object with a next_stops key holding a list of paths you can move to, for example (illustrative paths):
{"next_stops": ["/rooms/17", "/rooms/42"]}
To reach a neighbouring location, join each path onto the host of the entrance URL and request the result. The exit is the location whose response body is:
{"message": "congrats"}
Write a program that accepts the entrance URL and finds the exit.
Ground rules
- No one will explain how the service behaves. You are expected to call it, look at what comes back, and infer the rules yourself. In particular, nobody will tell you what a
503means or how to treat a body that is not valid JSON. - The maze can contain cycles, and many routes may lead to the same URL.
- Responses can be HTTP errors (such as
503) or bodies that fail JSON parsing. You decide, based on experimentation, how each is handled. - You may send as many requests as you like, but the program must always terminate.
What to deliver
Describe and implement your approach, and be ready to explain:
- How you avoid revisiting locations and looping forever.
- How you build each next URL from the host and a path.
- How you classify and respond to each kind of failure, including how many retries you allow.
- How you learn the service's behaviour rather than assume it.
- What your program does if no exit can be found, and what it costs in requests.
Hints
Hint 1
Model the maze as a directed graph whose nodes are URLs. Use a visited set (or a set of 'seen' URLs added when enqueued) so cycles and repeated routes cost nothing.
Hint 2
Do not treat every failure the same. A 503 that succeeds on a second try is transient and deserves a bounded retry with backoff; a body that is still unparseable after a few tries is likely permanent, so log it and skip that node instead of retrying forever.
Hint 3
Before finalising the logic, write a small probe that logs status code, headers and raw body for the first few hundred calls. Use what you see to decide retry counts and whether paths are always host-relative, and add a global request budget so the program always terminates.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the maze as a directed graph in which each URL is a node and each entry in next_stops is an outgoing edge. The job is graph search for a node whose response is {"message": "congrats"}, with an HTTP client that is defensive about failures.
I would use BFS with a queue and a seen set. BFS finds the exit with the fewest hops, which is useful if we also want to report a shortest route. DFS would work too, but in a deep maze it can wander very far from a nearby exit and risks recursion limits if written recursively. Either way, the cost is O(V + E) successful fetches plus retries.
Key design decisions
1. Deduplication. Mark a URL as seen when it is enqueued, not when it is dequeued. This prevents the same URL from being queued many times through different parents and handles cycles. Normalise URLs before inserting them (strip fragments, resolve duplicate slashes) so that two spellings of one location do not count as distinct.
2. Building URLs. Use a proper URL join (urllib.parse.urljoin(start_url, path)) rather than string concatenation. This correctly handles leading slashes and would also cope with an absolute URL appearing in next_stops. Keep the host fixed to the start URL's host and ignore anything pointing elsewhere unless probing shows otherwise.
3. Failure taxonomy. Because no one documents the errors, classify them:
- Transient (
503,429, connection reset, timeout): retry with exponential backoff plus jitter, for example 3 to 5 attempts at 0.2 s, 0.4 s, 0.8 s and so on. Honour aRetry-Afterheader if present. - Permanent (
404, other4xx): do not retry. Log and skip. - Malformed body (200 but invalid JSON, or JSON missing both
next_stopsandmessage): first retry a small number of times, since flaky servers sometimes return truncated bodies. If it persists, treat the node as dead and skip it. - Unexpected shape (for instance
next_stopsis not a list): log and skip.
A node that exhausts its retries should be recorded as failed, not silently dropped, so the final report can say how many nodes were unreachable. If any node failed, a "no exit found" result is only "not found among reachable nodes", not proof that no exit exists.
4. Learning the behaviour. Start with a probe that prints status, headers and raw body for the first N calls. Then check: does the same failing URL succeed on a retry? Are paths always host-relative? Is there rate limiting? The observed answers set the retry count and delay instead of guesses.
5. Termination. Termination is guaranteed by three things: the finite seen set (each URL is expanded at most once), a bounded retry count per URL, and a global request budget (for example 10,000 requests) or wall-clock timeout as a backstop in case the maze is effectively infinite. When the budget runs out, report failure clearly.
Code (Python)
import json
import random
import time
from collections import deque
from urllib.parse import urljoin, urlparse, urldefrag
import requests
MAX_RETRIES = 4
MAX_REQUESTS = 10_000
def fetch(session, url, budget):
"""Return parsed JSON dict, or None if the node should be skipped."""
for attempt in range(MAX_RETRIES + 1):
if budget["left"] <= 0:
raise RuntimeError("request budget exhausted")
budget["left"] -= 1
try:
r = session.get(url, timeout=5)
except requests.RequestException:
r = None
if r is not None:
if r.status_code == 200:
try:
data = r.json()
if isinstance(data, dict):
return data
except ValueError:
pass # malformed body: retry a few times
elif 400 <= r.status_code < 500 and r.status_code != 429:
return None # permanent
# transient or malformed: back off and retry
time.sleep(min(2.0, 0.2 * 2 ** attempt) * (0.5 + random.random()))
return None
def find_exit(start_url):
host = urlparse(start_url)
base = f"{host.scheme}://{host.netloc}"
session = requests.Session()
budget = {"left": MAX_REQUESTS}
seen = {start_url}
parent = {start_url: None}
queue = deque([start_url])
failed = 0
while queue:
url = queue.popleft()
data = fetch(session, url, budget)
if data is None:
failed += 1
continue
if data.get("message") == "congrats":
path = []
while url is not None:
path.append(url)
url = parent[url]
return path[::-1] # route from entrance to exit
stops = data.get("next_stops")
if not isinstance(stops, list):
continue
for p in stops:
if not isinstance(p, str):
continue
nxt, _ = urldefrag(urljoin(base, p))
if nxt not in seen:
seen.add(nxt)
parent[nxt] = url
queue.append(nxt)
return None # exhausted reachable nodes without finding the exit
Complexity
- Time: O(V + E) successful fetches, multiplied by at most (MAX_RETRIES + 1) for failing nodes. Network latency dominates.
- Space: O(V) for
seen,parentand the queue. - Concurrency can cut wall-clock time substantially (a thread pool or
asynciowith a bounded worker count), at the cost of more complex bookkeeping and the risk of triggering rate limits.
Common mistakes
- Marking visited on dequeue, which lets duplicates pile up in the queue.
- Concatenating strings for URLs and producing
//or missing slashes. - Retrying forever on a persistently bad response, so the program never terminates.
- Treating a 503 as permanent and so skipping the only path to the exit.
- Letting one JSON parse error crash the whole crawl.
- Using recursion for DFS and hitting the recursion limit.
- Hammering the server without backoff.
Follow-ups to be ready for
- Return the route as well as the exit (the
parentmap above does this). - Parallelise requests while keeping
seenthread-safe and respecting a rate limit. - Add a per-host rate limiter and a circuit breaker if the error rate spikes.
- Make it resumable by persisting
seenand the queue.