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^50 <= len(edges) <= 2 * 10^5- Every name in
servicesis unique, non-empty, and uses only lowercase ASCII letters, digits, and underscores ([a-z0-9_]). - Every edge
(src, dst, multiplier)references valid names inservicesand satisfies0.0 <= multiplier <= 1000.0. edgesforms a Directed Acyclic Graph (no directed cycles).entryis guaranteed to appear inservices.
Step-by-step walkthrough
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.0request entersentry:entrystarts with load1.0.- Along each edge
(src, dst, multiplier),srcforwardsload(src) * multiplierrequests todst. - When multiple services call
dst,dst's load is the sum of incoming traffic from reachable callers. - Services that cannot be reached from
entryhave load0.0and contribute0.0downstream.
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 inservices, sorted alphabetically byservice_name.Why tracing every path from entry is too slow
It is true that
load(v)equals the sum, over every directed path fromentrytov, of the product of multipliers along that path. Walking every path fromentrywith depth-first search works on tiny graphs (and makes a great brute-force oracle for testing), but a chain ofkdiamond 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,000services and200,000edges, enumerating paths can take exponential time. Instead of walking shared subpaths repeatedly, we wants1to combinea1andb1's traffic once and push that single combined number forward.Key idea: wait for all callers using Kahn's topological order
Why can't we run a plain breadth-first search from
entryand pushload[c]todthe moment we first discoverc? Look at what goes wrong when two paths of different lengths meet atc:entry --(x1)--> c --(x2)--> d \ ^ --(x2)--> a --(x3)--> b -| (x1)cis reached immediately fromentrywith1.0, whilebhas not been processed yet (bwill later send6.0toc). Ifcpushes todtoo early,donly receives1.0 * 2 = 2.0instead 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_degreecounter per service:in_degree[v]counts how many incoming edges intovhave not been processed yet.- Put every service with
in_degree == 0intoready_queue(nobody calls them, so their loads are already final). - Pop
currentfromready_queue, forwardload[current] * multiplieralong each outgoing edge(current, dst), and subtract1fromin_degree[dst]. The momentin_degree[dst]hits0, all callers ofdstare done — enqueuedst!
How unreachable callers are handled without a separate pass
What about services that
entrycannot reach, likecron_syncandauditin Example 2, or even a serviceuthat callsentry(u -> entry)?We get the right answer in one single pass over the whole graph by combining two rules:
- Initialize
load[entry] = 1.0and0.0for every other service (do not initialize allin_degree == 0services to1.0, which would invent phantom load atcron_sync). - Run Kahn's algorithm starting from all
in_degree == 0services, and always decrementin_degree[dst]even whenload[current] == 0.0.
Why does this work in every case?
- Any service unreachable from
entryonly has unreachable callers, so it receives0.0, keepsload == 0.0, and still decrementsin_degreeon its children so reachable services likeledgerare never stuck waiting! - Any upstream caller of
entry(u -> entry) cannot be reached fromentry(otherwiseentry -> ... -> u -> entrywould form a cycle, which is impossible in a DAG). Souhasload[u] == 0.0, adds nothing toentry, and unlocksentry'sin_degreeright on schedule.
- Initialize
Code Step 1: build the adjacency list and in-degree map
We create an empty outgoing list and
0in-degree for every service inservices(including isolated services with no edges at all). Notice that if the input contains duplicate edges between the same(src, dst)pair, appending both tooutgoing[src]and incrementingin_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_degreeCode Step 2: propagate loads with a queue and sort the result
Because we use an iterative
dequerather than recursive depth-first search, a linear chain of100,000services 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_resultsTrace 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)]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)):
in_degreestarts as{router: 0, catalog: 1, pricing: 1, cache: 2}andload[router] = 1.0. Onlyrouterentersready_queue.- Pop
router:cataloggets2.0(in_degreebecomes0, queued) andpricinggets0.5(in_degreebecomes0, queued). - Pop
catalog:cachegets2.0 * 1.5 = 3.0, andin_degree[cache]drops from2to1(cachewaits becausepricinghasn't finished yet). - Pop
pricing:cacheadds0.5 * 4.0 = 2.0(total5.0), andin_degree[cache]hits0, socacheis queued with its exact final load5.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)(orO(V log V + E)assuming bounded-length service names). Initializing dictionaries overVservices and scanningEedges takesO(V + E)time; Kahn's queue loop pops each of theVservices once and traverses each of theEoutgoing edges once inO(V + E)time; and sorting theVservice names at the end takesO(V log V)string comparisons. - Space:
O(V + E)auxiliary memory.outgoingstoresVlists totalingE(dst, multiplier)tuples, whilein_degree,load,ready_queue, andsorted_resultseach hold at mostVentries.
Edge cases
- Single isolated
entryservice (edges = []): returns[(entry, 1.0)]directly. - Upstream callers pointing into
entry(a -> entry -> c): because the graph is a DAG,acannot be reached fromentry, soakeepsload = 0.0, adds nothing toentry, andentrystays1.0. - Unreachable caller pointing into a reachable service (
cron_sync -> ledger):cron_synchasload = 0.0, contributes nothing toledger, and still decrementsin_degree["ledger"]soledgercan advance. - Zero multiplier (
multiplier == 0.0):dstis structurally reachable, receives0.0from that edge, and still gets itsin_degreedecremented. - Parallel / duplicate edges between the same
(src, dst)pair: each edge incrementsin_degree[dst]and appends tooutgoing[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-insorted(services).
Common mistakes
- Initializing every
in_degree == 0service to1.0: onlyentryreceives the incoming1.0request; giving1.0to all root nodes injects phantom load from disconnected services likecron_sync. - Seeding the queue with
[entry]while computingin_degreeover the entire graph: ifentryitself 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 to0and 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^5services. - Omitting unreachable services from the output: every service in
servicesmust appear in the sorted result list with0.0if unreachable.
Alternative approaches
- Two-pass reachable-subgraph Kahn's algorithm: first run a queue-based BFS starting from
entryto find the setreachableof services reachable fromentry; then computein_degreecounting only edges(src, dst)wheresrc in reachable, and run Kahn's algorithm starting from[entry]. This also runs inO(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 fromentryproduces a valid topological order of just the reachable services inO(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
whileloop is less thanV, every remaining service within_degree > 0lies 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 probabilityr = 0.1), total load converges to a geometric series (1 / (1 - r)), governed by the linear systemL = 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 asKunrolled 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 tabledelta(service, new_load)initialized to[(entry, 1.0)], alongside an accumulatedtotal_load(service, load)table. In each distributed round, inner-joindelta(filtering out zero loads) withedgesonsrc, emit(dst, new_load * multiplier), group and sum bydstto form next round'sdelta, and adddeltaintototal_load. Roundkpropagates traffic across all paths of exact lengthk, so the job terminates afterDshuffle rounds (whereDis the longest path length fromentry) oncedeltabecomes empty, followed by a left join withservicesto fill0.0for 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 whenXandYare correlated!) means our exact sameO(V + E)Kahn's algorithm gives exact expected loads simply by replacing each edge's distribution with its meanmu(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 likecachebecausecatalogandpricingshare upstream randomness fromrouter, making their bursts correlated. Instead, use Monte Carlo simulation — running thousands of randomized end-to-end trials fromentryin topological order and reading empiricalp95/p99values per service — taking care to clarify whether each individual call draws independently from the edge distribution (summingNdraws whenNcalls arrive) or one edge-wide random factor scales all calls on that edge per ingress request.
Follow-up questions
- What changes if automatic retries or mutual service calls introduce cycles into the call graph?
- How could you evaluate these multipliers across a massive graph partitioned on a cluster using Spark or MapReduce?
- Suppose each edge's call count follows a probability distribution instead of a fixed constant—how would your calculation change?
Similar questions
- Group Activity Logs into Inactivity-Bounded Sessions
- Weekly Calendar State and Derived Grid
- Cumulative Task Loads Across a DAG
- Room-to-Gate Shortest Distances on a Grid
- DAG Task Propagation Counts
- Frequency-Ranked Word Extraction from Text
More Robinhood interview questions
- Distinct Downstream Reachability in a Referral DAG Hard
- DAG Task Propagation Counts Easy
- Surfacing Technical Complexity and Scaling Trade-Offs on a Whiteboard Hard Pro
- Whole-Share Inventory Sweeping for Fractional Orders Medium Pro
- Weekly Calendar State and Derived Grid Medium Pro
- Justifying Technical Complexity and Scaling Trade-Offs Under Pushback Medium Pro
- Direct and Reachable Referral Graph Counts Medium Pro
- Fault-Tolerant Recurring Cron Scheduler at 100K Scale Medium Pro
- Strict At-Most-Once Background Task Scheduler Hard Pro
- Crash-Resilient Distributed Task Scheduler Medium Pro