Resilient HTTP Graph Crawler with Retries and Cycle Detection
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
An HTTP service hosts a directed graph of rooms starting at base_url. Every node either points to zero or more neighboring step IDs or holds the goal's secret text. Implement two functions—fetch_step and find_exit—that traverse this graph reliably despite transient server errors, cycles, and dead ends.
Endpoint Protocol
- Sending
GETtobase_urlqueries the starting node. - For each step ID string
s, its node URL is{base_url}/{escaped_s}, where trailing slashes onbase_urlare stripped andsis percent-encoded as a single path segment (urllib.parse.quote(s, safe="")). - A healthy (
200) JSON object follows one of two shapes:- Exit node: contains a non-null string
"message", e.g.{"message": "Gate unlocked"}. - Interior or dead-end node: contains
"next_steps"mapped to a list of string step IDs, e.g.{"next_steps": ["N10", "N20"]}or{"next_steps": []}(note that some schemas also include"message": nullon non-exit nodes, which must not be treated as an exit).
- Exit node: contains a non-null string
Functions to Implement
-
fetch_step(url, get, sleep, max_attempts=5, base_delay=0.5) -> Dict- Calls
get(url) -> (status_code, body_text)and returns the parsed JSON dictionary once a valid200exit ornext_stepspayload is received. - Retries transient failures for up to
max_attemptstotal requests, callingsleep(delay)with positive, nondecreasing exponential backoff delays starting atbase_delay(capped at10.0seconds) before each retry attempt:- HTTP status codes in
RETRYABLE_STATUSES({429, 500, 502, 503, 504}), OSErrorexceptions raised byget(timeouts, resets, cut-off transfers),- HTTP
200responses whose body is malformed JSON or lacks both a string"message"and a"next_steps"list of strings.
- HTTP status codes in
- Fails fast without sleeping or retrying by raising
FetchErroron any permanent HTTP status (such as404). - Raises
FetchErrorif allmax_attemptsattempts fail transiently.
- Calls
-
find_exit(base_url, get=http_get, sleep=time.sleep, max_attempts=5) -> str- Explores reachable nodes iteratively starting at
base_urland returns the exit node's"message"string. - Records each discovered URL immediately upon enqueueing so cycles, self-loops, and diamond paths fetch every step URL at most once (excluding internal retries inside
fetch_step). - If
fetch_stepraisesFetchErroron a branch, skips that broken node and continues searching remaining branches. - Raises
ExitNotFoundif every reachable branch finishes without uncovering an exit.
- Explores reachable nodes iteratively starting at
Examples
Example 1
Input:
base_url = "http://service.local/labyrinth"
Server responses:
GET /labyrinth -> 200 {"next_steps": ["N10", "N20"]}
GET /labyrinth/N10 -> 200 {"next_steps": []}
GET /labyrinth/N20 -> 503 (attempt 1), 503 (attempt 2),
200 {"next_steps": ["N10", "N30"]} (attempt 3)
GET /labyrinth/N30 -> 200 {"message": "Gate unlocked"}
Output:
"Gate unlocked"
Explanation: BFS fetches /labyrinth and queues N10 and N20. N10 is a dead end ([]). Fetching N20 encounters two 503 responses—sleeping 0.5s then 1.0s—before succeeding on its third attempt with ["N10", "N30"]. Because N10 was already seen, only N30 is queued, and fetching N30 returns "Gate unlocked".
Example 2
Input:
base_url = "http://service.local/labyrinth"
Server responses:
GET /labyrinth -> 200 {"next_steps": ["MISSING_9", "HALL_4"]}
GET /labyrinth/MISSING_9 -> 404 {"error": "not found"}
GET /labyrinth/HALL_4 -> 200 {"message": "Vault reached"}
Output:
"Vault reached"
Explanation: MISSING_9 responds with 404, which is permanent: fetch_step raises FetchError immediately without sleeping or retrying. find_exit skips MISSING_9, pops HALL_4 next, and returns "Vault reached".
Constraints
GETrequests are idempotent and do not mutate server state.- Reachable corridors may exceed
5,000hops (deeper than Python's default recursion limit). - Step IDs are arbitrary opaque strings that may contain reserved URL characters (
'/','?', spaces). 1 <= max_attempts <= 20,base_delay > 0.
Step-by-step walkthrough
Map the maze onto a graph and pin down failure rules
Treat the HTTP maze as a directed graph: - The nodes are URLs:
base_urlis the starting node, and each step IDsis a node at{base_url}/{s}. - The directed edges out of a node are the step IDs inside its"next_steps"list ([]is a dead end). - The goal node is whichever step responds with a string"message".In a live-coding interview against a flaky server, clarify edge-case policies early and commit to crisp rules:
Server behavior Transient or permanent? Action 503(plus429,500,502,504)Transient Retry up to max_attempts(5 total) with exponential backoffSocket timeout, connection reset, or cut-off body Transient Retry the same way ( GETdoes not mutate server state)200with truncated JSON or unexpected schemaTransient Retry—network proxies occasionally truncate bodies mid-stream 404or other4xx(except429)Permanent Raise FetchErrorimmediately without wasting retriesStep still fails after all 5 attempts Branch failure Skip that step, keep exploring other branches, log it for diagnostics base_urlitself returns"message"Valid exit Return "message"after 1 requestSeparate the program into three clean layers
Mixing
urllibexceptions, sleep timers, JSON checks, and graph search inside a singlewhileloop turns debugging into guesswork. Instead, stack three focused layers so the graph search never even knows503exists:+---------------------------------------------------------------+ | Layer 3: find_exit(base_url) | | Iterative BFS: FIFO queue, `seen` set, cycles & dead ends | +---------------------------------------------------------------+ | calls v +---------------------------------------------------------------+ | Layer 2: fetch_step(url, get, sleep) | | Retries transient errors with backoff + validates JSON | +---------------------------------------------------------------+ | calls v +---------------------------------------------------------------+ | Layer 1: get(url) -> (status_code, body_text) | | Raw HTTP transport (`http_get` in prod, fake dict in tests) | +---------------------------------------------------------------+Passing
getandsleepas arguments (defaulting tohttp_getandtime.sleep) gives you instant offline unit tests: a test with 20 simulated503retries finishes in under a millisecond because the fakesleepsimply appends the delay number to a list instead of pausing!Build the HTTP transport layer (`http_get`)
Python's built-in
urllib.request.urlopenhas three sharp edges that catch candidates off guard in live interviews:- No default timeout: Without
timeout=10.0, a half-open TCP connection hangs forever. HTTPErroron4xxand5xx: Unlike third-party libraries such asrequests,urlopenraisesurllib.error.HTTPErroron503or404. That exception object still contains.codeand.read(), so catch it and return(exc.code, body_text)normally.- Mid-stream cutoffs are not
OSError: When a flaky server drops the connection halfway through sending the response body,response.read()raiseshttp.client.IncompleteRead—a subclass ofHTTPException, notOSError! CatchHTTPExceptionand re-raise it asOSErrorso Layer 2 retries it cleanly alongside socket timeouts and resets.
import http.client import urllib.error import urllib.request from typing import Tuple def http_get(url: str, timeout: float = 10.0) -> Tuple[int, str]: """GET `url` and return (status_code, body_text). Network failures raise OSError.""" request = urllib.request.Request(url, headers={"Accept": "application/json"}) try: with urllib.request.urlopen(request, timeout=timeout) as response: body_text = response.read().decode("utf-8", errors="replace") return response.status, body_text except urllib.error.HTTPError as exc: body_text = exc.read().decode("utf-8", errors="replace") return exc.code, body_text except http.client.HTTPException as exc: raise OSError(f"broken HTTP response: {exc!r}") from exc- No default timeout: Without
Parse strictly and retry transient errors with exponential backoff
Because HTTP
GETis idempotent (repeating the exact same call has no side effects on the server), we can safely retry network errors, retryable HTTP codes (429,500,502,503,504), and corrupted200bodies.In
parse_step, validate the exact shape before handing data to the graph search. Watch out for a common real-world API quirk: typed backend frameworks often serialize every step using one shared struct such as{"next_steps": ["N10"], "message": null}. Checking"message" in datawould mistake"message": nullfor the exit and returnNone! Checkdata.get("message") is not Noneand verify it is astr.When a retry is needed, pause using exponential backoff—doubling the wait after each failed attempt (
0.5s, 1.0s, 2.0s, 4.0s, capped at10.0s) so we give an overloaded server breathing room instead of hammering it immediately:import json from typing import Callable, Dict, Tuple RETRYABLE_STATUSES = {429, 500, 502, 503, 504} MAX_DELAY = 10.0 class FetchError(Exception): """One step could not be fetched and parsed, even after retries.""" def parse_step(body: str) -> Dict: """Validate and return a step JSON dict, or raise ValueError on malformed JSON or wrong shape.""" data = json.loads(body) if not isinstance(data, dict): raise ValueError("response is not a JSON object") if data.get("message") is not None: if not isinstance(data["message"], str): raise ValueError("exit 'message' field must be a string") return data next_steps = data.get("next_steps") if not isinstance(next_steps, list): raise ValueError("response has neither a string 'message' nor a 'next_steps' list") for step_id in next_steps: if not isinstance(step_id, str): raise ValueError(f"step id {step_id!r} is not a string") return data def fetch_step(url: str, get: Callable[[str], Tuple[int, str]], sleep: Callable[[float], None], max_attempts: int = 5, base_delay: float = 0.5) -> Dict: """Fetch and parse one step URL, retrying transient failures with exponential backoff.""" last_problem = "no attempt made" delay = min(MAX_DELAY, base_delay) for attempt in range(max_attempts): if attempt > 0: sleep(delay) delay = min(MAX_DELAY, delay * 2) try: status, body = get(url) except OSError as exc: last_problem = f"network error ({exc})" continue if status in RETRYABLE_STATUSES: last_problem = f"HTTP {status}" continue if status != 200: raise FetchError(f"{url}: HTTP {status}") try: return parse_step(body) except ValueError as exc: last_problem = f"bad body ({exc})" raise FetchError(f"{url}: gave up after {max_attempts} attempts; last problem: {last_problem}")Traverse with iterative BFS and mark nodes seen on discovery
Explore the graph with iterative breadth-first search (BFS) using
collections.deque(popping from the left withpopleft()and pushing new neighbors on the right withappend()). Iterative BFS solves two problems at once: 1. Unlike recursive depth-first search, it never hits Python's 1,000-call recursion limit on a 5,000-step corridor. 2. It explores steps in order of distance frombase_url, finding the closest exit first.When should a URL be added to
seen—when popped or when discovered? Look at a diamond graph whereAandBboth point toC:start / \ If marked only when popped: A B - Fetching A queues C; fetching B queues C a SECOND time! \ / If marked on discovery (when queued): C - Fetching A adds C to `seen` and queues C once; - Fetching B sees C in `seen` and skips it immediately!Marking URLs in
seenat discovery time guarantees every reachable URL enters the queue at most once and is fetched at most once. Percent-encodestep_idwithurllib.parse.quote(step_id, safe="")so opaque IDs containing/,?, or spaces stay a single URL path segment.from collections import deque import time import urllib.parse from typing import Callable, Deque, List, Set, Tuple class ExitNotFound(Exception): """Every reachable step was explored and none of them was the exit.""" def step_url(base_url: str, step_id: str) -> str: """Build `{base_url}/{escaped_step_id}` safely even if `step_id` contains '/', '?', or spaces.""" escaped_id = urllib.parse.quote(step_id, safe="") return base_url.rstrip("/") + "/" + escaped_id def find_exit(base_url: str, get: Callable[[str], Tuple[int, str]] = http_get, sleep: Callable[[float], None] = time.sleep, max_attempts: int = 5) -> str: """Explore the maze with iterative breadth-first search and return the exit message.""" queue: Deque[str] = deque([base_url]) seen: Set[str] = {base_url} failed: List[str] = [] while queue: url = queue.popleft() try: data = fetch_step(url, get, sleep, max_attempts) except FetchError as exc: failed.append(str(exc)) continue if isinstance(data.get("message"), str): return data["message"] for step_id in data["next_steps"]: next_url = step_url(base_url, step_id) if next_url not in seen: seen.add(next_url) queue.append(next_url) raise ExitNotFound( f"explored {len(seen)} steps without finding the exit; " f"{len(failed)} could not be fetched: {failed}" )Trace Example 1 step by step
Suppose
base(http://service.local/labyrinth) leads toN10(a dead end) andN20(which links back toN10and forward to exitN30), andN20returns503twice before succeeding:Queue before pop HTTP call & server reply Action --------------------------------------------------------------------------------------------------- [base] GET base -> 200 {"next_steps": seen = {base, N10, N20} ["N10", "N20"]} [N10, N20] GET /N10 -> 200 {"next_steps": []} dead end; queue nothing [N20] GET /N20 #1 -> 503 sleep(0.5s), retry GET /N20 #2 -> 503 sleep(1.0s), retry GET /N20 #3 -> 200 {"next_steps": N10 already in seen; ["N10", "N30"]} seen += {N30}, queue N30 [N30] GET /N30 -> 200 {"message": return "Gate unlocked" "Gate unlocked"}Total cost: 6 HTTP requests and
0.5 + 1.0 = 1.5sof backoff sleep, whilefind_exitstayed a textbook 15-line BFS loop.Complete solution
from typing import Callable, Deque, Dict, List, Set, Tuple from collections import deque import http.client import json import time import urllib.error import urllib.parse import urllib.request # HTTP status codes meaning "server busy or temporarily failing; safe to retry after a pause" RETRYABLE_STATUSES = {429, 500, 502, 503, 504} # Upper bound (in seconds) on a single retry sleep so large max_attempts cannot stall for minutes MAX_DELAY = 10.0 class FetchError(Exception): """One step could not be fetched and parsed, even after retries.""" class ExitNotFound(Exception): """Every reachable step was explored and none of them was the exit.""" def http_get(url: str, timeout: float = 10.0) -> Tuple[int, str]: """GET `url` and return (status_code, body_text). Network failures raise OSError.""" request = urllib.request.Request(url, headers={"Accept": "application/json"}) try: # Always pass an explicit timeout; urllib defaults to waiting forever on a hung socket with urllib.request.urlopen(request, timeout=timeout) as response: body_text = response.read().decode("utf-8", errors="replace") return response.status, body_text except urllib.error.HTTPError as exc: # urlopen raises HTTPError on 4xx/5xx, but fetch_step needs the status code to decide retries body_text = exc.read().decode("utf-8", errors="replace") return exc.code, body_text except http.client.HTTPException as exc: # IncompleteRead (connection closed mid-body) inherits from HTTPException, not OSError raise OSError(f"broken HTTP response: {exc!r}") from exc def parse_step(body: str) -> Dict: """Validate and return a step JSON dict, or raise ValueError on malformed JSON or wrong shape.""" # json.JSONDecodeError is a subclass of ValueError, so callers only need `except ValueError` data = json.loads(body) if not isinstance(data, dict): raise ValueError("response is not a JSON object") # Treat "message" as an exit only when non-null string (ignores {"message": null, "next_steps": [...]}) if data.get("message") is not None: if not isinstance(data["message"], str): raise ValueError("exit 'message' field must be a string") return data next_steps = data.get("next_steps") if not isinstance(next_steps, list): raise ValueError("response has neither a string 'message' nor a 'next_steps' list") for step_id in next_steps: if not isinstance(step_id, str): raise ValueError(f"step id {step_id!r} is not a string") return data def fetch_step(url: str, get: Callable[[str], Tuple[int, str]], sleep: Callable[[float], None], max_attempts: int = 5, base_delay: float = 0.5) -> Dict: """Fetch and parse one step URL, retrying transient failures with exponential backoff.""" last_problem = "no attempt made" delay = min(MAX_DELAY, base_delay) for attempt in range(max_attempts): # Attempt 0 runs immediately; retries sleep 0.5s, 1.0s, 2.0s, 4.0s... up to MAX_DELAY if attempt > 0: sleep(delay) delay = min(MAX_DELAY, delay * 2) try: status, body = get(url) except OSError as exc: last_problem = f"network error ({exc})" continue if status in RETRYABLE_STATUSES: last_problem = f"HTTP {status}" continue if status != 200: # Permanent client errors like 404 Not Found will not succeed on retry; fail fast raise FetchError(f"{url}: HTTP {status}") try: return parse_step(body) except ValueError as exc: # GET is idempotent, so a truncated or garbled 200 body can be safely retried last_problem = f"bad body ({exc})" raise FetchError(f"{url}: gave up after {max_attempts} attempts; last problem: {last_problem}") def step_url(base_url: str, step_id: str) -> str: """Build `{base_url}/{escaped_step_id}` safely even if `step_id` contains '/', '?', or spaces.""" escaped_id = urllib.parse.quote(step_id, safe="") return base_url.rstrip("/") + "/" + escaped_id def find_exit(base_url: str, get: Callable[[str], Tuple[int, str]] = http_get, sleep: Callable[[float], None] = time.sleep, max_attempts: int = 5) -> str: """Explore the maze with iterative breadth-first search and return the exit message.""" # queue: FIFO queue of step URLs waiting to be fetched, e.g. deque(["http://.../maze"]) queue: Deque[str] = deque([base_url]) # seen: URLs marked as soon as discovered so diamonds/cycles never queue or fetch a URL twice seen: Set[str] = {base_url} # failed: error summaries for unreachable branches, included if no exit is ever found failed: List[str] = [] while queue: url = queue.popleft() try: data = fetch_step(url, get, sleep, max_attempts) except FetchError as exc: # Skip permanently broken branches because another path may still reach the exit failed.append(str(exc)) continue if isinstance(data.get("message"), str): return data["message"] for step_id in data["next_steps"]: next_url = step_url(base_url, step_id) if next_url not in seen: seen.add(next_url) queue.append(next_url) raise ExitNotFound( f"explored {len(seen)} steps without finding the exit; " f"{len(failed)} could not be fetched: {failed}" ) if __name__ == "__main__": import sys if len(sys.argv) == 2: print(find_exit(sys.argv[1]))✅ Submit now — all tests should pass.
Intuition & how it works
Picture exploring a museum of numbered rooms where each room contains either a slip of paper listing neighboring doors (next_steps) or the exit prize (message), while an overworked guard occasionally asks you to step back and wait a moment (503 Service Temporarily Unavailable). Two simple rules keep you from ever getting lost or stuck: write every room number onto your seen notepad the instant you first read it on a slip so circular hallways never make you visit a room twice, and delegate knocking, waiting, and re-knocking at a busy door to a dedicated helper (fetch_step) so your exploration loop only ever deals with clean room slips.
A naive crawler that mixes HTTP requests directly into a recursive function fails in four ways against a real server: Python's urlopen raises HTTPError on 503 and crashes the run, retrying immediately in a while True loop floods an overloaded server and hangs forever if one node stays down, cycles cause infinite loops without a visited set, and long corridors crash Python's call stack (the fixed-depth list of active function frames, capped at 1,000 by default in CPython). Instead, we pair:
- Breadth-first search (BFS)—a graph traversal that visits nodes wave by wave in order of distance from the start using a FIFO queue (first-in, first-out queue, collections.deque), marking URLs in seen on discovery.
- Bounded exponential backoff—doubling the pause between retries (0.5s, 1.0s, 2.0s, 4.0s, capped at 10s) on transient errors because HTTP GET is idempotent (safe to repeat multiple times with the exact same server state).
Walk through Example 1 where base points to ["N10", "N20"], N10 is a dead end [], N20 fails twice with 503 before pointing to ["N10", "N30"], and N30 holds the exit:
1. Start with queue = [base] and seen = {base}. Pop base, fetch ["N10", "N20"], add both URLs to seen, and append both to queue.
2. Pop N10, fetch [] (dead end), append nothing.
3. Pop N20: attempts 1 and 2 get 503 (sleeping 0.5s then 1.0s), and attempt 3 returns ["N10", "N30"]. Because N10 is already in seen, only N30 is added to seen and queue.
4. Pop N30, fetch {"message": "Gate unlocked"}, and return "Gate unlocked".
Complexity
Let V be the number of reachable step URLs from base_url and E be the total number of next_steps links across all fetched steps.
- Network requests: At most
Vrequests when every call succeeds on the first try (and fewer when the exit is found early), because marking URLs inseenwhen queued ensures each reachable URL is popped at most once. In the worst case where every step fails repeatedly,fetch_stepsends at mostV * max_attemptsrequests total. - CPU time:
O(V + E)total hash-set lookups anddequepushes/pops across the search, plus linear work in the byte length of the JSON responses to parse and validate them. - Retry and network wait time: Dominated by network round-trips. With
max_attempts = 5andbase_delay = 0.5, a single failing step adds at most0.5 + 1.0 + 2.0 + 4.0 = 7.5sof backoff sleep (plus up to5 * 10s = 50sif every socket call hangs untiltimeout). - Space:
O(V)memory forseenandqueue(plusO(V)at worst forfailed). Storing 1,000,000 30-character URL strings in a 64-bit CPythonsetuses roughly~110 MB(~80 bytes per Python string object plus ~34 MB for the hash table slots).
Edge cases
base_urlis already the exit: The very firstfetch_step(base_url, ...)returns a"message"string andfind_exitfinishes after 1 request.- Cycles, self-loops, and duplicate IDs in one list: Because
seenis checked and updated beforequeue.append,["A", "A"]orA -> B -> Astill fetches each step once. - Schemas that include
"message": nullon normal steps: Many typed HTTP servers return{"next_steps": ["A"], "message": null}on intermediate nodes; checkingdata.get("message") is not None(and requiring astr) prevents mistakingnullfor an exit. - Permanent
404vs. transient503: A404raisesFetchErroron attempt 1 with zero sleeps, whereas503,429,OSError,IncompleteRead, and truncated200JSON bodies retry up tomax_attempts. - Permanently down branch alongside a healthy exit branch: Catching
FetchErrorinsidefind_exitskips the dead branch and still discovers the exit along any working path; if no exit is reachable anywhere,ExitNotFoundsurfaces the list of skipped branches. - Very deep corridors (
> 1,000steps) and special characters in step IDs: Iterativedequesearch handles arbitrary path depths in heap memory, andurllib.parse.quote(step_id, safe="")escapes/,?,#, and spaces safely.
Common mistakes
- Forgetting that
urllib.request.urlopenraises on503: Withoutexcept urllib.error.HTTPError, the very first503crashes the crawler instead of entering the retry loop. - Missing
http.client.IncompleteRead: A server that drops the TCP connection mid-body raisesIncompleteRead(anHTTPException, not anOSError), crashing callers that only catchOSError. - Calling
json.loadsbefore checkingstatus == 200: Load balancers usually return HTML error pages on502/503, which misleads debugging logs into reporting JSON syntax errors instead of HTTP503s. - Checking
"message" in datainstead of checking for a string value: If an API returns{"next_steps": ["X"], "message": null},"message" in dataevaluates toTrueand exits prematurely withNone. - Unbounded retries, zero delay, or retrying
404s: Infinite loops hang on dead nodes, instant retries worsen a503outage, and retrying a404wastes 7.5 seconds per dead link. - Marking nodes visited only when popped: Without adding URLs to
seenat enqueue time (or re-checking at pop time), diamond paths fetch the same URL multiple times and blow up queue size fromO(V)toO(E). - Omitting
timeoutonurlopen: Python's default socket timeout isNone(wait forever), allowing a single black-holed packet to freeze the entire program.
Follow-up questions
- How would you modify the traversal to return a minimum-hop list of step IDs from the entry URL to the exit? Because BFS explores the graph in increasing number of hops from
base_url, the first exit it pops is already guaranteed to have the fewest steps (among reachable, non-failing nodes). Replace theseenset with aparent: Dict[str, Optional[str]] = {base_url: None}dictionary (recordingparent[next_url] = urlandstep_name[next_url] = step_idwhen enqueuing), then walk backward from the exit URL throughparentuntilbase_urland reverse the collected step IDs. - Suppose the graph contains a million nodes and the server permits up to 10 in-flight requests at once. How would you parallelize the crawl without worsening server overload? Keep a single coordinator loop owning
seenand the frontier queue (so visited checks need no locks) and dispatch up to 10 in-flightfetch_steptasks at once viaThreadPoolExecutor(max_workers=10)orasynciowithasyncio.Semaphore(10), shrinking a 14-hour sequential crawl (1M steps × 50 ms) by roughly 10×. Add random jitter (multiplying each backoff sleep by a random factor like0.5to1.5so 10 workers don't retry at the exact same millisecond) and adaptive concurrency control that temporarily lowers the in-flight cap whenever a burst of503s indicates server-wide overload. - If a single node continues returning 503 after exhausting its retry budget, should the crawler abort immediately, ignore that node, or revisit it later? Never abort the whole search immediately, because the graph may have another healthy path to the exit—and never retry one URL forever, because the program must terminate. The best practical strategy is two-phase: skip the failing step during the main BFS while saving its URL in a
deferredlist, and only if the main queue empties without finding the exit, run one slower recovery pass overdeferredwith longer backoff before raisingExitNotFoundwith the exact URLs that remained unreachable. - Why does a recursive depth-first implementation crash on a deep linear chain of nodes, and how do you eliminate that limit? Every recursive call pushes a frame onto Python's call stack, which defaults to 1,000 frames (
sys.getrecursionlimit()) and raisesRecursionErroron a 5,000-step corridor; raisingsetrecursionlimitrisks crashing the C interpreter process with a stack overflow on server-controlled input. Fix it by storing pending nodes explicitly on the heap: acollections.dequepopped from the left (popleft()) gives iterative BFS, while a plain Pythonlistpopped from the right (pop()) gives iterative depth-first search.
Follow-up questions
- How would you modify the traversal to return a minimum-hop list of step IDs from the entry URL to the exit?
- Suppose the graph contains a million nodes and the server permits up to 10 in-flight requests at once. How would you parallelize the crawl without worsening server overload?
- If a single node continues returning 503 after exhausting its retry budget, should the crawler abort immediately, ignore that node, or revisit it later?
- Why does a recursive depth-first implementation crash on a deep linear chain of nodes, and how do you eliminate that limit?
Similar questions
- Color-Coded Word Guess Scorer
- Fault-Tolerant Multi-Hop HTTP Chain Client
- Five-Letter Guess Sanitizer and Color Scorer
- Word-Grid Puzzle Reducer and React Board
- Thread-Safe Bank Account Class with Transfers and Merges
- Configurable Subscription Stream Detector for Card Logs
More Ramp interview questions
- Sliding-Window Request Throttler by Client IP Medium
- Exit Discovery in a Locked Web Graph Medium
- Adaptive-Timeout Web Graph Search with Deferred Retries Medium Pro
- Shortest Exit Route Through an Unreliable HTTP Maze Medium Pro
- Linear HTTP Endpoint Chain Traversal Medium Pro
- Rolling One-Minute Website Traffic Counter Hard Pro
- Traveler Airport Lookup Across Flight Schedules Medium Pro
- Stateful 3x3 Tic-Tac-Toe Rules Engine Medium Pro
- Versioned Recipe Catalog Service Medium Pro
- Deduplicate and Reconcile Person Records Hard Pro