Downstream Traffic Multipliers in a Service Graph

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A backend platform consists of named services connected by one-way RPC dependencies with no circular call chains (a Directed Acyclic Graph, or DAG). Whenever a service handles a single request, it can invoke each of its downstream dependencies a fixed number of times—possibly more than once (for batched fan-out), once, or a fraction of a time on average (when behind a cache or conditional branch).

You are given: - services: a list of distinct service names in the platform, - edges: a list of directed dependency triples (src, dst, multiplier), meaning every 1.0 request handled by src sends multiplier requests to dst (multiple edges between the same pair are allowed and each contributes independently), and - entry: the name of the ingress service that receives 1.0 external request.

Compute the resulting request volume (load factor) experienced by every service in services: - entry starts with a load factor of 1.0 from the external request. - Any service that cannot be reached along a directed path starting at entry has a load factor of 0.0 and forwards 0.0 traffic downstream. - Every other reachable service accumulates the sum of load(src) * multiplier across all incoming edges (src, dst, multiplier) whose caller src is reachable from entry.

Return a list of (service_name, load_factor) pairs covering all services in services, sorted in ascending lexicographical (ASCII) order by service_name. Floating-point values within 10^-6 relative or absolute error of the exact answer are accepted.

def compute_load_factors(
    services: List[str],
    edges: List[Tuple[str, str, float]],
    entry: str,
) -> List[Tuple[str, float]]:

Examples

Example 1

services = ["router", "catalog", "pricing", "cache"]
edges = [
    ("router", "catalog", 2.0),
    ("router", "pricing", 0.5),
    ("catalog", "cache", 1.5),
    ("pricing", "cache", 4.0),
]
entry = "router"

Output:

[("cache", 5.0), ("catalog", 2.0), ("pricing", 0.5), ("router", 1.0)]

Walk-through: router handles 1.0 incoming request and sends 1.0 * 2.0 = 2.0 calls to catalog plus 1.0 * 0.5 = 0.5 calls to pricing. Both downstream services call cache, which receives 2.0 * 1.5 = 3.0 requests from catalog and 0.5 * 4.0 = 2.0 requests from pricing, giving 3.0 + 2.0 = 5.0 in total. Sorting the pairs alphabetically by name yields the output list.

Example 2

services = ["checkout", "ledger", "cron_sync", "audit"]
edges = [
    ("checkout", "ledger", 2.5),
    ("cron_sync", "ledger", 10.0),
]
entry = "checkout"

Output:

[("audit", 0.0), ("checkout", 1.0), ("cron_sync", 0.0), ("ledger", 2.5)]

Walk-through: checkout starts at 1.0 and forwards 2.5 calls to ledger. Neither cron_sync nor the isolated audit service is reachable from checkout, so both stay at 0.0, and the (cron_sync -> ledger) edge adds 0.0 to ledger.

Constraints

  • 1 <= len(services) <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • Every name in services is unique, non-empty, and uses only lowercase ASCII letters, digits, and underscores ([a-z0-9_]).
  • Every edge (src, dst, multiplier) references valid names in services and satisfies 0.0 <= multiplier <= 1000.0.
  • edges forms a Directed Acyclic Graph (no directed cycles).
  • entry is guaranteed to appear in services.

Step-by-step walkthrough

  1. Understand the goal and how loads combine

    We are given a Directed Acyclic Graph (DAG) of services — one-way call edges with no loops. When 1.0 request enters entry:

    • entry starts with load 1.0.
    • Along each edge (src, dst, multiplier), src forwards load(src) * multiplier requests to dst.
    • When multiple services call dst, dst's load is the sum of incoming traffic from reachable callers.
    • Services that cannot be reached from entry have load 0.0 and contribute 0.0 downstream.
      Example 1 (converging paths):            Example 2 (unreachable & isolated):
               router (1.0)                     checkout (1.0)    cron_sync (0.0)   audit (0.0)
               /          \                             \               /
           x2.0            x0.5                        x2.5           x10.0
             v              v                             v           v
       catalog (2.0)   pricing (0.5)                    ledger (2.5 + 0.0 = 2.5)
             \              /
            x1.5          x4.0
               v          v
           cache (3.0 + 2.0 = 5.0)
    

    Finally, we return (service_name, load_factor) for every service in services, sorted alphabetically by service_name.

  2. Why tracing every path from entry is too slow

    It is true that load(v) equals the sum, over every directed path from entry to v, of the product of multipliers along that path. Walking every path from entry with depth-first search works on tiny graphs (and makes a great brute-force oracle for testing), but a chain of k diamond shapes doubles the path count at every diamond:

      s0 ---> a1 ---> s1 ---> a2 ---> s2 ... ---> sk
         \--> b1 --/     \--> b2 --/
    
      k = 1 diamond:  2 paths
      k = 2 diamonds: 4 paths
      k = 30 diamonds (only 91 services!): 2^30 > 1,000,000,000 paths!
    

    With up to 100,000 services and 200,000 edges, enumerating paths can take exponential time. Instead of walking shared subpaths repeatedly, we want s1 to combine a1 and b1's traffic once and push that single combined number forward.

  3. Key idea: wait for all callers using Kahn's topological order

    Why can't we run a plain breadth-first search from entry and push load[c] to d the moment we first discover c? Look at what goes wrong when two paths of different lengths meet at c:

      entry --(x1)--> c --(x2)--> d
        \                         ^
         --(x2)--> a --(x3)--> b -| (x1)
    

    c is reached immediately from entry with 1.0, while b has not been processed yet (b will later send 6.0 to c). If c pushes to d too early, d only receives 1.0 * 2 = 2.0 instead of (1.0 + 6.0) * 2 = 14.0!

    We must process a service only after all of its incoming edges have been processed. That ordering is called a topological order, and Kahn's algorithm computes it with a queue and an in_degree counter per service:

    1. in_degree[v] counts how many incoming edges into v have not been processed yet.
    2. Put every service with in_degree == 0 into ready_queue (nobody calls them, so their loads are already final).
    3. Pop current from ready_queue, forward load[current] * multiplier along each outgoing edge (current, dst), and subtract 1 from in_degree[dst]. The moment in_degree[dst] hits 0, all callers of dst are done — enqueue dst!
  4. How unreachable callers are handled without a separate pass

    What about services that entry cannot reach, like cron_sync and audit in Example 2, or even a service u that calls entry (u -> entry)?

    We get the right answer in one single pass over the whole graph by combining two rules:

    1. Initialize load[entry] = 1.0 and 0.0 for every other service (do not initialize all in_degree == 0 services to 1.0, which would invent phantom load at cron_sync).
    2. Run Kahn's algorithm starting from all in_degree == 0 services, and always decrement in_degree[dst] even when load[current] == 0.0.

    Why does this work in every case?

    • Any service unreachable from entry only has unreachable callers, so it receives 0.0, keeps load == 0.0, and still decrements in_degree on its children so reachable services like ledger are never stuck waiting!
    • Any upstream caller of entry (u -> entry) cannot be reached from entry (otherwise entry -> ... -> u -> entry would form a cycle, which is impossible in a DAG). So u has load[u] == 0.0, adds nothing to entry, and unlocks entry's in_degree right on schedule.
  5. Code Step 1: build the adjacency list and in-degree map

    We create an empty outgoing list and 0 in-degree for every service in services (including isolated services with no edges at all). Notice that if the input contains duplicate edges between the same (src, dst) pair, appending both to outgoing[src] and incrementing in_degree[dst] twice handles them naturally.

    from typing import Dict, List, Tuple
    
    
    def build_graph(
        services: List[str],
        edges: List[Tuple[str, str, float]],
    ) -> Tuple[Dict[str, List[Tuple[str, float]]], Dict[str, int]]:
        outgoing: Dict[str, List[Tuple[str, float]]] = {}
        in_degree: Dict[str, int] = {}
        for name in services:
            outgoing[name] = []
            in_degree[name] = 0
    
        for src, dst, multiplier in edges:
            outgoing[src].append((dst, multiplier))
            in_degree[dst] += 1
    
        return outgoing, in_degree
    
  6. Code Step 2: propagate loads with a queue and sort the result

    Because we use an iterative deque rather than recursive depth-first search, a linear chain of 100,000 services runs smoothly without hitting Python's 1,000-call recursion limit. At the end, sorted(services) orders names in standard ASCII lexicographical order.

    from typing import Dict, List, Tuple
    from collections import deque
    
    
    def compute_load_factors(
        services: List[str],
        edges: List[Tuple[str, str, float]],
        entry: str,
    ) -> List[Tuple[str, float]]:
        outgoing: Dict[str, List[Tuple[str, float]]] = {}
        in_degree: Dict[str, int] = {}
        for name in services:
            outgoing[name] = []
            in_degree[name] = 0
    
        for src, dst, multiplier in edges:
            outgoing[src].append((dst, multiplier))
            in_degree[dst] += 1
    
        load: Dict[str, float] = {}
        for name in services:
            load[name] = 0.0
        load[entry] = 1.0
    
        ready_queue: deque = deque()
        for name in services:
            if in_degree[name] == 0:
                ready_queue.append(name)
    
        while ready_queue:
            current = ready_queue.popleft()
            current_load = load[current]
    
            for dst, multiplier in outgoing[current]:
                if current_load > 0.0 and multiplier > 0.0:
                    load[dst] += current_load * multiplier
    
                in_degree[dst] -= 1
                if in_degree[dst] == 0:
                    ready_queue.append(dst)
    
        sorted_results: List[Tuple[str, float]] = []
        for name in sorted(services):
            sorted_results.append((name, load[name]))
        return sorted_results
    
  7. Trace both example graphs step by step

    Example 1 (entry = "router"):

    Start:
      in_degree   = {router: 0, catalog: 1, pricing: 1, cache: 2}
      load        = {router: 1.0, catalog: 0.0, pricing: 0.0, cache: 0.0}
      ready_queue = [router]
    
    Pop "router" (load 1.0):
      -> catalog: load[catalog] += 1.0 * 2.0 = 2.0; in_degree[catalog] = 0 -> enqueue "catalog"
      -> pricing: load[pricing] += 1.0 * 0.5 = 0.5; in_degree[pricing] = 0 -> enqueue "pricing"
    
    Pop "catalog" (load 2.0):
      -> cache:   load[cache] += 2.0 * 1.5 = 3.0;   in_degree[cache] = 1 (still waiting for "pricing"!)
    
    Pop "pricing" (load 0.5):
      -> cache:   load[cache] += 0.5 * 4.0 = 5.0;   in_degree[cache] = 0 -> enqueue "cache"
    
    Pop "cache" (load 5.0): no outgoing edges.
    Sorted output: [("cache", 5.0), ("catalog", 2.0), ("pricing", 0.5), ("router", 1.0)]
    

    Example 2 (entry = "checkout", unreachable "cron_sync" and "audit"):

    Start:
      in_degree   = {checkout: 0, ledger: 2, cron_sync: 0, audit: 0}
      load        = {checkout: 1.0, ledger: 0.0, cron_sync: 0.0, audit: 0.0}
      ready_queue = [checkout, cron_sync, audit]
    
    Pop "checkout" (load 1.0):
      -> ledger: load[ledger] += 1.0 * 2.5 = 2.5; in_degree[ledger] = 1
    
    Pop "cron_sync" (load 0.0):
      -> ledger: current_load is 0.0 (adds nothing); in_degree[ledger] = 0 -> enqueue "ledger"
    
    Pop "audit" (load 0.0): no outgoing edges.
    Pop "ledger" (load 2.5): no outgoing edges.
    Sorted output: [("audit", 0.0), ("checkout", 1.0), ("cron_sync", 0.0), ("ledger", 2.5)]
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def compute_load_factors(
        services: List[str],
        edges: List[Tuple[str, str, float]],
        entry: str,
    ) -> List[Tuple[str, float]]:
        # Phase 1: Build the graph and count incoming edges per service.
        # outgoing: {"router": [("catalog", 2.0), ("pricing", 0.5)], ...}
        # in_degree: {"router": 0, "catalog": 1, "pricing": 1, "cache": 2, ...}
        outgoing: Dict[str, List[Tuple[str, float]]] = {}
        in_degree: Dict[str, int] = {}
        for name in services:
            outgoing[name] = []
            in_degree[name] = 0
    
        for src, dst, multiplier in edges:
            outgoing[src].append((dst, multiplier))
            in_degree[dst] += 1
    
        # Phase 2: Initialize loads.
        # Only `entry` starts at 1.0; every other service starts at 0.0 so unreachable
        # services (including any upstream callers of `entry`) keep 0.0 and push 0.0.
        load: Dict[str, float] = {}
        for name in services:
            load[name] = 0.0
        load[entry] = 1.0
    
        # Phase 3: Kahn's topological sweep over the full DAG.
        # ready_queue holds services whose callers have ALL finished pushing load,
        # guaranteeing load[current] is final when `current` is popped.
        ready_queue: deque = deque()
        for name in services:
            if in_degree[name] == 0:
                ready_queue.append(name)
    
        while ready_queue:
            current = ready_queue.popleft()
            current_load = load[current]
    
            for dst, multiplier in outgoing[current]:
                if current_load > 0.0 and multiplier > 0.0:
                    load[dst] += current_load * multiplier
    
                # Always decrement in_degree even when current_load == 0.0 so reachable
                # services with an unreachable caller are not blocked from entering ready_queue.
                in_degree[dst] -= 1
                if in_degree[dst] == 0:
                    ready_queue.append(dst)
    
        # Phase 4: Format (service_name, load_factor) sorted lexicographically by name.
        sorted_results: List[Tuple[str, float]] = []
        for name in sorted(services):
            sorted_results.append((name, load[name]))
        return sorted_results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture water flowing downhill through a network of one-way splitter and amplifier pipes (a Directed Acyclic Graph, or DAG — a graph of one-way arrows with no closed loops). Exactly 1.0 liter enters at the entry valve, each pipe scales the flow passing through it by multiplier, and whenever multiple pipes converge at a junction service, you must wait until every incoming pipe has poured in its share before sending that service's combined total onward.

A naive approach traces every path from entry and multiplies along each path separately, which blows up exponentially (2^k paths across k diamond splits) because shared subpaths get re-traversed over and over. On the flip side, a plain breadth-first search that forwards a service's load the first time it is discovered sends an incomplete number downstream whenever another caller arrives later via a longer path.

We get each edge processed once in the right order using Kahn's algorithm, which visits services in topological order (an ordering where every caller appears before every service it calls) by tracking each service's remaining unprocessed incoming edges (in_degree) and only queuing a service once in_degree hits 0. By initializing load[entry] = 1.0 and 0.0 everywhere else across the whole graph, unreachable services stay at 0.0 while still counting down their children's in_degree. Walk through Example 1 (router -> catalog (x2.0), router -> pricing (x0.5), catalog -> cache (x1.5), pricing -> cache (x4.0)):

  1. in_degree starts as {router: 0, catalog: 1, pricing: 1, cache: 2} and load[router] = 1.0. Only router enters ready_queue.
  2. Pop router: catalog gets 2.0 (in_degree becomes 0, queued) and pricing gets 0.5 (in_degree becomes 0, queued).
  3. Pop catalog: cache gets 2.0 * 1.5 = 3.0, and in_degree[cache] drops from 2 to 1 (cache waits because pricing hasn't finished yet).
  4. Pop pricing: cache adds 0.5 * 4.0 = 2.0 (total 5.0), and in_degree[cache] hits 0, so cache is queued with its exact final load 5.0.

Complexity

Let V be the number of services (len(services)) and E be the number of dependency edges (len(edges)).

  • Time: O(V + E + V log V) (or O(V log V + E) assuming bounded-length service names). Initializing dictionaries over V services and scanning E edges takes O(V + E) time; Kahn's queue loop pops each of the V services once and traverses each of the E outgoing edges once in O(V + E) time; and sorting the V service names at the end takes O(V log V) string comparisons.
  • Space: O(V + E) auxiliary memory. outgoing stores V lists totaling E (dst, multiplier) tuples, while in_degree, load, ready_queue, and sorted_results each hold at most V entries.

Edge cases

  • Single isolated entry service (edges = []): returns [(entry, 1.0)] directly.
  • Upstream callers pointing into entry (a -> entry -> c): because the graph is a DAG, a cannot be reached from entry, so a keeps load = 0.0, adds nothing to entry, and entry stays 1.0.
  • Unreachable caller pointing into a reachable service (cron_sync -> ledger): cron_sync has load = 0.0, contributes nothing to ledger, and still decrements in_degree["ledger"] so ledger can advance.
  • Zero multiplier (multiplier == 0.0): dst is structurally reachable, receives 0.0 from that edge, and still gets its in_degree decremented.
  • Parallel / duplicate edges between the same (src, dst) pair: each edge increments in_degree[dst] and appends to outgoing[src], so their load contributions sum together accurately.
  • 100,000-service linear chain: iterative queue processing avoids Python's 1,000-call recursion limit completely.
  • Lexicographical sorting with digits and underscores: standard ASCII string sorting orders '0'..'9' before '_' before 'a'..'z', matching Python's built-in sorted(services).

Common mistakes

  • Initializing every in_degree == 0 service to 1.0: only entry receives the incoming 1.0 request; giving 1.0 to all root nodes injects phantom load from disconnected services like cron_sync.
  • Seeding the queue with [entry] while computing in_degree over the entire graph: if entry itself has an upstream caller (a -> entry), in_degree[entry] is non-zero; or if a reachable service also has an unreachable caller (cron_sync -> ledger), in_degree["ledger"] never drops to 0 and traffic stops dead!
  • Plain BFS that pushes load on first discovery: fails whenever two paths of unequal hop count converge at a node that has further downstream children.
  • Recursive DFS without an explicit stack: exceeds Python's recursion limit on deep chains of up to 10^5 services.
  • Omitting unreachable services from the output: every service in services must appear in the sorted result list with 0.0 if unreachable.

Alternative approaches

  • Two-pass reachable-subgraph Kahn's algorithm: first run a queue-based BFS starting from entry to find the set reachable of services reachable from entry; then compute in_degree counting only edges (src, dst) where src in reachable, and run Kahn's algorithm starting from [entry]. This also runs in O(V + E) time and avoids touching large unreachable subgraphs during load propagation.
  • Iterative post-order DFS from entry: reversing the post-order of a depth-first search from entry produces a valid topological order of just the reachable services in O(V + E) time, after which one forward loop pushes loads along outgoing edges.

Follow-up questions

  • What changes if automatic retries or mutual service calls introduce cycles into the call graph? Kahn's algorithm detects cycles automatically: if the number of popped services at the end of the while loop is less than V, every remaining service with in_degree > 0 lies on a cycle or downstream of one. Mathematically, if a cycle of services has combined loop gain < 1 (for instance, a service retries itself with probability r = 0.1), total load converges to a geometric series (1 / (1 - r)), governed by the linear system L = e_entry + M^T L, which has a finite non-negative solution when the spectral radius (the largest magnitude among the eigenvalues of the reachable cycle matrix) is strictly < 1. In production, you would condense cycles into strongly connected components (SCCs) — maximal groups of mutually reachable services — process the DAG of SCCs in topological order, solve each cyclic SCC via linear equations or bounded iteration, and flag an infinite-amplification alert if spectral radius >= 1 (or model capped retries explicitly as K unrolled DAG layers).
  • How could you evaluate these multipliers across a massive graph partitioned on a cluster using Spark or MapReduce? Represent the edges as a partitioned table (src, dst, multiplier) and maintain an active frontier table delta(service, new_load) initialized to [(entry, 1.0)], alongside an accumulated total_load(service, load) table. In each distributed round, inner-join delta (filtering out zero loads) with edges on src, emit (dst, new_load * multiplier), group and sum by dst to form next round's delta, and add delta into total_load. Round k propagates traffic across all paths of exact length k, so the job terminates after D shuffle rounds (where D is the longest path length from entry) once delta becomes empty, followed by a left join with services to fill 0.0 for unreached services.
  • Suppose each edge's call count follows a probability distribution instead of a fixed constant—how would your calculation change? If you only need the expected (mean) load on every service, linearity of expectation (the rule that E[X + Y] = E[X] + E[Y] even when X and Y are correlated!) means our exact same O(V + E) Kahn's algorithm gives exact expected loads simply by replacing each edge's distribution with its mean mu (assuming each call's multiplier draw is independent of upstream volume). However, variance and tail percentiles (p95, p99) cannot be summed independently at converging nodes like cache because catalog and pricing share upstream randomness from router, making their bursts correlated. Instead, use Monte Carlo simulation — running thousands of randomized end-to-end trials from entry in topological order and reading empirical p95/p99 values per service — taking care to clarify whether each individual call draws independently from the edge distribution (summing N draws when N calls arrive) or one edge-wide random factor scales all calls on that edge per ingress request.

Follow-up questions

Similar questions

More Robinhood interview questions

All 60 Robinhood questions →