Problem solving · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Recursion Depth Exceeded

mediumdebugging

Problem

A catalogue service keeps a map of deprecated product SKUs to the SKU that replaced them. Because products are replaced repeatedly, resolving a SKU means following the chain until it reaches one that is still current:

def resolve_sku(sku: str, replaced_by: dict[str, str]) -> str:
    """Follow the replacement chain until we reach a SKU that is still current."""
    if sku not in replaced_by:
        return sku
    return resolve_sku(replaced_by[sku], replaced_by)

Symptom: the nightly job that resolves every SKU in the catalogue has been fine for two years and now dies with RecursionError: maximum recursion depth exceeded on one product family. A separate, much rarer report is a job that dies with the same error on a SKU with only three known replacements. Explain both failures and fix the function.

Examples

  • replaced_by = {"A1": "A2", "A2": "A3"}, resolve_sku("A1") → "A3". Fine.
  • A family with 1,400 successive replacements (weekly revisions over many years) → RecursionError at around depth 1,000, the default CPython recursion limit. Expected: the current SKU.
  • replaced_by = {"B1": "B2", "B2": "B3", "B3": "B1"} (a data-entry loop) → RecursionError after roughly 1,000 calls. Expected: a clear error such as ValueError: replacement cycle at B1, not a crash that looks like the long-chain case.

Hints

  1. How deep can the call stack go before CPython refuses to grow it? sys.getrecursionlimit() tells you.
  2. Each recursive call here does no work after the callee returns. What does that tell you about whether the stack is needed at all?
  3. The three-SKU failure is not about depth. Trace it by hand.

Last reviewed 8 September 2026