Counting Nodes in a Distributed Tree Network
System DesignModel answerLast 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:
- Message Types: You are allowed to define and use only two message types:
REQUEST_COUNTandREPLY_COUNT. - Correctness & Safety: Every node in the network must contribute exactly $1$ to the total count. Avoid deadlocks, infinite loops, and double counting.
- Arbitrary Initiator: Any node in the tree (whether root, internal node, or leaf) must be able to initiate a node count.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Technical Overview
To compute the total node count of a distributed $N$-ary tree without a central coordinator, we implement an Echo Protocol (a flooding sweep followed by a convergecast aggregation).
Because any node can trigger the count, the network topology is treated as an undirected connected graph where each node's adjacent set consists of its parent and children. The node that triggers the count acts as the root of a session-specific spanning tree.
- Flooding Phase (
REQUEST_COUNT): The initiator broadcasts a request to all immediate neighbors. Nodes receiving this request for the first time record the sender as theirupstreamparent for this session and forward the request to all their other neighbors. - Convergecast Phase (
REPLY_COUNT): Leaf nodes (nodes with no further neighbors to query) send a count of1back to their upstream parent. Intermediate nodes aggregate sub-counts from all downstream neighbors, add1for themselves, and send the accumulated count upstream.
1. (a) Message Schema
The protocol strictly uses two message types: REQUEST_COUNT and REPLY_COUNT.
Message {
type: REQUEST_COUNT | REPLY_COUNT
session_id: (initiator_id: String, sequence_number: Int)
sender_id: String
count: Int // Used only in REPLY_COUNT (size of sender's subtree)
}
session_id: A globally unique tuple combining the initiator's unique node ID and a local incrementing sequence counter. This isolates concurrent counting runs.count: Contains the subtree node tally whentype == REPLY_COUNT. ForREQUEST_COUNT, it defaults to0.
2. (b) Per-Node State and Concurrency Control
Each node stores a thread-safe map of active counting sessions: sessions: Map[SessionID, SessionState].
class SessionState:
upstream_id: str | None # Neighbor who first forwarded the request
pending_neighbors: set[str] # Set of neighbor IDs we await replies from
accumulated_count: int = 1 # Starts at 1 to include self
is_done: bool = False # True once reply has been sent upstream
cached_result: int | None = None # Saved result for idempotent retries
future: Future | None = None # Populated only on the initiating node
Synchronization Rules:
- A per-node mutex (
_lock) serializes access tosessionsand state updates. - Deadlock Avoidance Rule: Network sends (
receive_messagecalls to remote nodes) must never be performed while holding the node's internal lock. State transition calculations occur inside the lock, yielding a list of outbound messages that are sent after releasing the lock.
3. (c) Protocol Propagation and Aggregation Lifecycle
[Initiator: Node A]
/ \
(REQ)/ \(REQ)
v v
[Node B] [Node C]
/ \ |
(REQ)/ \(REQ) |(REQ)
v v v
[Node D] [Node E] [Node F] (Leaf)
1. Session Initiation
When count_nodes() is invoked on Node $A$:
- $A$ creates a new
session_id = (A.id, ++A.seq). - Under lock, $A$ initializes
SessionState:upstream_id = Nonepending_neighbors = { all neighbors (parent + children) }future = Future()
- $A$ releases the lock and sends
REQUEST_COUNT(session_id, sender_id=A)to all nodes inpending_neighbors.
2. Receiving REQUEST_COUNT
When Node $X$ receives REQUEST_COUNT from Node $Y$:
- Under lock, check if
session_idalready exists insessions. - First Time Seeing Session:
- Record
upstream_id = Y. - Set
pending_neighbors = { all neighbors } - { Y }. - If
pending_neighborsis empty ($X$ is a leaf relative to $Y$):- Mark
is_done = Trueand setcached_result = 1. - Queue a
REPLY_COUNT(session_id, sender_id=X, count=1)to send to $Y$.
- Mark
- If
pending_neighborsis non-empty:- Queue
REQUEST_COUNTmessages to all nodes inpending_neighbors.
- Queue
- Record
- Release lock and transmit queued messages.
3. Receiving REPLY_COUNT
When Node $X$ receives REPLY_COUNT(count=c) from Node $Z$:
- Under lock, retrieve the state for
session_id. - If $Z \notin \text{pending_neighbors}$, drop the message (it is a duplicate or stale reply).
- Remove $Z$ from
pending_neighbors. - Add $c$ to
accumulated_count. - If
pending_neighborsis now empty:- Mark
is_done = Trueand setcached_result = accumulated_count. - If
upstream_idis present (not initiator), queueREPLY_COUNT(session_id, sender_id=X, count=accumulated_count)toupstream_id. - If
upstream_idisNone(initiator), resolvefuturewithaccumulated_count.
- Mark
- Release lock and send queued message (if any).
4. (d) Deduplication, Edge Cases, and Race Conditions
- Duplicate
REQUEST_COUNTfrom Non-Upstream Nodes: If a cycle or duplicate path exists and Node $X$ receives aREQUEST_COUNTfrom Node $W$ when $X$ already has an active session (where $W \neq \text{upstream_id}$):- $X$ must acknowledge $W$ so that $W$'s
pending_neighborsset can drain. - $X$ immediately queues
REPLY_COUNT(session_id, sender_id=X, count=0)to $W$. Returning0ensures $X$'s subtree is not counted twice.
- $X$ must acknowledge $W$ so that $W$'s
- Network Retries from Upstream Node:
If $Y$ retries a
REQUEST_COUNTto $X$ (e.g., due to packet loss of an ACK or transport timeout):- If $X$ has already completed the session (
is_done == True), $X$ resends itscached_resultin aREPLY_COUNTback to $Y$. - If $X$ is still processing, $X$ safely ignores the duplicate request.
- If $X$ has already completed the session (
- Out-of-Order Packets:
Because state transitions depend on set membership in
pending_neighborsrather than sequence position, out-of-order message delivery does not cause incorrect tallies.
5. (e) Termination Detection
Termination is guaranteed deterministically by structural induction:
- Every leaf node immediately replies with
count = 1. - An intermediate node replies to its upstream parent if and only if all of its downstream neighbors have replied. Its reply value is guaranteed to equal $1 + \sum \text{downstream subtrees}$.
- The initiating node has
upstream_id = None. When itspending_neighborsset becomes empty, every reachable node in the connected tree has processed the request, contributed $1$, and returned its sub-total. - The initiator then completes its internal
Future, returning the global node count to the caller.
6. (f) Complexity & System Assumptions
Complexity Analysis
- Message Complexity: Exactly $2(N - 1)$ messages under normal execution without transport retries. Every tree edge carries exactly one
REQUEST_COUNTand oneREPLY_COUNT. - Time Complexity: $O(D)$ parallel network latency rounds, where $D$ is the tree diameter (if initiated from a leaf) or tree height (if initiated from the root).
- Space Complexity: $O(\text{degree})$ space per node per active session. Completed session states can be evicted after a time-to-live (TTL) threshold.
Network & Architecture Assumptions
- Delivery Guarantees: Reliable, at-least-once transport layer. FIFO ordering is not required.
- Topology: The tree network structure remains static for the duration of a counting session.
- Node Reliability: Nodes do not crash mid-session (fail-stop model without dynamic node crashes).
Reference Python Implementation
import threading
from concurrent.futures import Future
from enum import Enum
from typing import Dict, List, Set, Tuple, Optional
class MsgType(Enum):
REQUEST_COUNT = 1
REPLY_COUNT = 2
class Message:
def __init__(self, msg_type: MsgType, session_id: Tuple[str, int], sender_id: str, count: int = 0):
self.type = msg_type
self.session_id = session_id
self.sender_id = sender_id
self.count = count
class SessionState:
def __init__(self, upstream_id: Optional[str], pending: Set[str]):
self.upstream_id: Optional[str] = upstream_id
self.pending_neighbors: Set[str] = pending
self.accumulated_count: int = 1
self.is_done: bool = False
self.cached_result: Optional[int] = None
self.future: Optional[Future] = None
class Node:
def __init__(self, node_id: str):
self.id = node_id
self.parent: Optional['Node'] = None
self.children: List['Node'] = []
self._lock = threading.Lock()
self._sessions: Dict[Tuple[str, int], SessionState] = {}
self._seq = 0
# Local lookup table for simulating network dispatch
self.network_registry: Dict[str, 'Node'] = {}
def get_neighbors(self) -> List[str]:
neighbors = [child.id for child in self.children]
if self.parent:
neighbors.append(self.parent.id)
return neighbors
def initiate_count((self) -> int:
"""Entry point to initiate a node count from this node."""
outgoing_messages = []
future = Future()
with self._lock:
self._seq += 1
session_id = (self.id, self._seq)
neighbors = set(self.get_neighbors())
if not neighbors:
# Single-node tree edge case
return 1
state = SessionState(upstream_id=None, pending=set(neighbors))
state.future = future
self._sessions[session_id] = state
for nbr_id in neighbors:
outgoing_messages.append((nbr_id, Message(MsgType.REQUEST_COUNT, session_id, self.id)))
# Send messages outside the lock
self._dispatch_messages(outgoing_messages)
return future.result()
def receive_message(self, from_node_id: str, message: Message):
outgoing_messages = []
with self._lock:
session_id = message.session_id
if message.type == MsgType.REQUEST_COUNT:
if session_id not in self._sessions:
# New session request
neighbors = set(self.get_neighbors())
pending = neighbors - {from_node_id}
state = SessionState(upstream_id=from_node_id, pending=pending)
self._sessions[session_id] = state
if not pending:
# Leaf node relative to request
state.is_done = True
state.cached_result = 1
outgoing_messages.append(
(from_node_id, Message(MsgType.REPLY_COUNT, session_id, self.id, count=1))
)
else:
for nbr_id in pending:
outgoing_messages.append(
(nbr_id, Message(MsgType.REQUEST_COUNT, session_id, self.id))
)
else:
# Duplicate request
state = self._sessions[session_id]
if from_node_id != state.upstream_id:
# Request from alternate path; reply with 0 to drain sender's pending set
outgoing_messages.append(
(from_node_id, Message(MsgType.REPLY_COUNT, session_id, self.id, count=0))
)
elif state.is_done and state.cached_result is not None:
# Retried request from upstream node
outgoing_messages.append(
(from_node_id, Message(MsgType.REPLY_COUNT, session_id, self.id, count=state.cached_result))
)
elif message.type == MsgType.REPLY_COUNT:
if session_id in self._sessions:
state = self._sessions[session_id]
if from_node_id in state.pending_neighbors:
state.pending_neighbors.remove(from_node_id)
state.accumulated_count += message.count
if not state.pending_neighbors:
state.is_done = True
state.cached_result = state.accumulated_count
if state.upstream_id is not None:
outgoing_messages.append(
(state.upstream_id, Message(MsgType.REPLY_COUNT, session_id, self.id, count=state.accumulated_count))
)
elif state.future is not None:
state.future.set_result(state.accumulated_count)
# Send messages outside the lock
self._dispatch_messages(outgoing_messages)
def _dispatch_messages(self, messages: List[Tuple[str, Message]]):
for target_id, msg in messages:
target_node = self.network_registry.get(target_id)
if target_node:
# Async dispatch simulation using a new thread
threading.Thread(target=target_node.receive_message, args=(self.id, msg)).start()