KatInterview

Counting Nodes in a Distributed Tree Network

System DesignModel answer
MediumModel answerSystem Designdistributed-systemsconcurrencytrees-graphs

Last updated

Design a distributed algorithm and protocol to count all nodes in an N-ary tree using asynchronous message passing, local state, and deduplication.

Consider a system where nodes in an $N$-ary tree run on separate machines across a network. Each node knows its parent node (unless it is the root) and its immediate child nodes.

Implement the message handling logic inside a distributed Node class that processes incoming network calls of the form receive_message(from_node, message). When triggered on an arbitrary node, your algorithm must execute an asynchronous protocol using message passing to determine the total number of nodes in the full tree and deliver that final count to the initiator.

Your design must fulfill these specific constraints:

  1. Message Types: You are allowed to define and use only two message types: REQUEST_COUNT and REPLY_COUNT.
  2. Correctness & Safety: Every node in the network must contribute exactly $1$ to the total count. Avoid deadlocks, infinite loops, and double counting.
  3. Arbitrary Initiator: Any node in the tree (whether root, internal node, or leaf) must be able to initiate a node count.
  4. Concurrent Requests: The system must safely isolate multiple concurrent counting sessions (either started by different nodes or multiple runs from the same node).

Provide a thorough technical breakdown addressing:

  • (a) Data Structures & Schema: Define the payload schema for both message types.
  • (b) Local Node State: Describe the per-session local variables stored on each node and how shared state is synchronized under concurrent events.
  • (c) Request & Reply Lifecycle: Explain step-by-step how a request traverses the tree and how sub-counts aggregate back.
  • (d) Deduplication & Edge Cases: Explain how duplicate packets, topology loops/cross-edges (if misconfigured), and network retries are handled safely.
  • (e) Termination: How does the initiating node confirm that the count is complete and exact?
  • (f) Complexity & Assumptions: Detail the total message count, network round-trip time, memory overhead, and underlying network delivery assumptions.

Hints

Hint 1

Treat the tree as an undirected graph where neighbors consist of a node's parent and children. The initiator acts as the root of the spanning tree for that session.

Hint 2

Maintain per-session state protected by a node-level lock. Crucially, release the lock before dispatching network messages to prevent cross-node deadlocks.

Hint 3

Assign a unique session identifier composed of the initiator ID and a monotonic local sequence counter to differentiate concurrent runs.