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 GET to base_url queries the starting node.
  • For each step ID string s, its node URL is {base_url}/{escaped_s}, where trailing slashes on base_url are stripped and s is 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": null on non-exit nodes, which must not be treated as an exit).

Functions to Implement

  1. 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 valid 200 exit or next_steps payload is received.
    • Retries transient failures for up to max_attempts total requests, calling sleep(delay) with positive, nondecreasing exponential backoff delays starting at base_delay (capped at 10.0 seconds) before each retry attempt:
      • HTTP status codes in RETRYABLE_STATUSES ({429, 500, 502, 503, 504}),
      • OSError exceptions raised by get (timeouts, resets, cut-off transfers),
      • HTTP 200 responses whose body is malformed JSON or lacks both a string "message" and a "next_steps" list of strings.
    • Fails fast without sleeping or retrying by raising FetchError on any permanent HTTP status (such as 404).
    • Raises FetchError if all max_attempts attempts fail transiently.
  2. find_exit(base_url, get=http_get, sleep=time.sleep, max_attempts=5) -> str

    • Explores reachable nodes iteratively starting at base_url and 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_step raises FetchError on a branch, skips that broken node and continues searching remaining branches.
    • Raises ExitNotFound if every reachable branch finishes without uncovering an exit.

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

  • GET requests are idempotent and do not mutate server state.
  • Reachable corridors may exceed 5,000 hops (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

  1. Map the maze onto a graph and pin down failure rules

    Treat the HTTP maze as a directed graph: - The nodes are URLs: base_url is the starting node, and each step ID s is 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 (plus 429, 500, 502, 504) Transient Retry up to max_attempts (5 total) with exponential backoff
    Socket timeout, connection reset, or cut-off body Transient Retry the same way (GET does not mutate server state)
    200 with truncated JSON or unexpected schema Transient Retry—network proxies occasionally truncate bodies mid-stream
    404 or other 4xx (except 429) Permanent Raise FetchError immediately without wasting retries
    Step still fails after all 5 attempts Branch failure Skip that step, keep exploring other branches, log it for diagnostics
    base_url itself returns "message" Valid exit Return "message" after 1 request
  2. Separate the program into three clean layers

    Mixing urllib exceptions, sleep timers, JSON checks, and graph search inside a single while loop turns debugging into guesswork. Instead, stack three focused layers so the graph search never even knows 503 exists:

    +---------------------------------------------------------------+
    | 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 get and sleep as arguments (defaulting to http_get and time.sleep) gives you instant offline unit tests: a test with 20 simulated 503 retries finishes in under a millisecond because the fake sleep simply appends the delay number to a list instead of pausing!

  3. Build the HTTP transport layer (`http_get`)

    Python's built-in urllib.request.urlopen has three sharp edges that catch candidates off guard in live interviews:

    1. No default timeout: Without timeout=10.0, a half-open TCP connection hangs forever.
    2. HTTPError on 4xx and 5xx: Unlike third-party libraries such as requests, urlopen raises urllib.error.HTTPError on 503 or 404. That exception object still contains .code and .read(), so catch it and return (exc.code, body_text) normally.
    3. Mid-stream cutoffs are not OSError: When a flaky server drops the connection halfway through sending the response body, response.read() raises http.client.IncompleteRead—a subclass of HTTPException, not OSError! Catch HTTPException and re-raise it as OSError so 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
    
  4. Parse strictly and retry transient errors with exponential backoff

    Because HTTP GET is 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 corrupted 200 bodies.

    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 data would mistake "message": null for the exit and return None! Check data.get("message") is not None and verify it is a str.

    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 at 10.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}")
    
  5. 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 with popleft() and pushing new neighbors on the right with append()). 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 from base_url, finding the closest exit first.

    When should a URL be added to seen—when popped or when discovered? Look at a diamond graph where A and B both point to C:

        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 seen at discovery time guarantees every reachable URL enters the queue at most once and is fetched at most once. Percent-encode step_id with urllib.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}"
        )
    
  6. Trace Example 1 step by step

    Suppose base (http://service.local/labyrinth) leads to N10 (a dead end) and N20 (which links back to N10 and forward to exit N30), and N20 returns 503 twice 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.5s of backoff sleep, while find_exit stayed a textbook 15-line BFS loop.

  7. 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 V requests when every call succeeds on the first try (and fewer when the exit is found early), because marking URLs in seen when queued ensures each reachable URL is popped at most once. In the worst case where every step fails repeatedly, fetch_step sends at most V * max_attempts requests total.
  • CPU time: O(V + E) total hash-set lookups and deque pushes/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 = 5 and base_delay = 0.5, a single failing step adds at most 0.5 + 1.0 + 2.0 + 4.0 = 7.5s of backoff sleep (plus up to 5 * 10s = 50s if every socket call hangs until timeout).
  • Space: O(V) memory for seen and queue (plus O(V) at worst for failed). Storing 1,000,000 30-character URL strings in a 64-bit CPython set uses roughly ~110 MB (~80 bytes per Python string object plus ~34 MB for the hash table slots).

Edge cases

  • base_url is already the exit: The very first fetch_step(base_url, ...) returns a "message" string and find_exit finishes after 1 request.
  • Cycles, self-loops, and duplicate IDs in one list: Because seen is checked and updated before queue.append, ["A", "A"] or A -> B -> A still fetches each step once.
  • Schemas that include "message": null on normal steps: Many typed HTTP servers return {"next_steps": ["A"], "message": null} on intermediate nodes; checking data.get("message") is not None (and requiring a str) prevents mistaking null for an exit.
  • Permanent 404 vs. transient 503: A 404 raises FetchError on attempt 1 with zero sleeps, whereas 503, 429, OSError, IncompleteRead, and truncated 200 JSON bodies retry up to max_attempts.
  • Permanently down branch alongside a healthy exit branch: Catching FetchError inside find_exit skips the dead branch and still discovers the exit along any working path; if no exit is reachable anywhere, ExitNotFound surfaces the list of skipped branches.
  • Very deep corridors (> 1,000 steps) and special characters in step IDs: Iterative deque search handles arbitrary path depths in heap memory, and urllib.parse.quote(step_id, safe="") escapes /, ?, #, and spaces safely.

Common mistakes

  • Forgetting that urllib.request.urlopen raises on 503: Without except urllib.error.HTTPError, the very first 503 crashes the crawler instead of entering the retry loop.
  • Missing http.client.IncompleteRead: A server that drops the TCP connection mid-body raises IncompleteRead (an HTTPException, not an OSError), crashing callers that only catch OSError.
  • Calling json.loads before checking status == 200: Load balancers usually return HTML error pages on 502/503, which misleads debugging logs into reporting JSON syntax errors instead of HTTP 503s.
  • Checking "message" in data instead of checking for a string value: If an API returns {"next_steps": ["X"], "message": null}, "message" in data evaluates to True and exits prematurely with None.
  • Unbounded retries, zero delay, or retrying 404s: Infinite loops hang on dead nodes, instant retries worsen a 503 outage, and retrying a 404 wastes 7.5 seconds per dead link.
  • Marking nodes visited only when popped: Without adding URLs to seen at enqueue time (or re-checking at pop time), diamond paths fetch the same URL multiple times and blow up queue size from O(V) to O(E).
  • Omitting timeout on urlopen: Python's default socket timeout is None (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 the seen set with a parent: Dict[str, Optional[str]] = {base_url: None} dictionary (recording parent[next_url] = url and step_name[next_url] = step_id when enqueuing), then walk backward from the exit URL through parent until base_url and 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 seen and the frontier queue (so visited checks need no locks) and dispatch up to 10 in-flight fetch_step tasks at once via ThreadPoolExecutor(max_workers=10) or asyncio with asyncio.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 like 0.5 to 1.5 so 10 workers don't retry at the exact same millisecond) and adaptive concurrency control that temporarily lowers the in-flight cap whenever a burst of 503s 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 deferred list, and only if the main queue empties without finding the exit, run one slower recovery pass over deferred with longer backoff before raising ExitNotFound with 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 raises RecursionError on a 5,000-step corridor; raising setrecursionlimit risks crashing the C interpreter process with a stack overflow on server-controlled input. Fix it by storing pending nodes explicitly on the heap: a collections.deque popped from the left (popleft()) gives iterative BFS, while a plain Python list popped from the right (pop()) gives iterative depth-first search.

Follow-up questions

Similar questions

More Ramp interview questions

All 42 Ramp questions →