Aggregate Node Counts Across an Unreliable Distributed Tree
System DesignModel answerLast updated
Design a fault-tolerant protocol where each node in a distributed tree contributes its subtree size upward until the root knows the total node count.
Background
You are building a monitoring tool for a cluster of servers arranged in a tree topology. Each server knows only its own identity, its direct parent, and its immediate children — there is no global directory or shared memory. You need the root server to compute the total number of servers in the cluster.
The network is unreliable: any message can be dropped, delayed, or delivered more than once. A server may crash and restart at any time. Your design must still produce a correct answer eventually, without requiring every server to be up simultaneously.
Your Task
Design a distributed aggregation protocol in which each server maintains local state and responds to two kinds of incoming messages. The root server initiates the process and eventually learns the total count.
Address all four of the following questions in your answer.
-
Message schema. What message types flow between a parent server and its children? List every field and the direction each message travels.
-
Idempotency. The same request can arrive at a server more than once because the sender retransmits until it gets a reply. How does a server ensure it does not perform the aggregation work twice for the same logical request?
-
Per-node state machine. What data does a server keep while it is waiting for its children to reply? Walk through the states a server transitions through, from receiving a request to sending its result upward.
-
Concurrent requests. What should a server do if a second request arrives while it is still waiting for its children to respond to an earlier one? Consider both the case where the two requests share the same ID and the case where they have different IDs.
Constraints
- A server has no knowledge of the tree beyond its own parent and children.
- All message sends are fire-and-forget; there is no blocking RPC.
- A server may receive the same request message several times due to retries, and it must behave correctly in all cases.
Example
Tree: A (root) → {B, C}, B → {D}
A sends REQUEST(id=42) to B and C.
B sends REQUEST(id=42) to D.
D (leaf) replies RESULT(id=42, count=1) to B.
B adds itself: count = 1 + 1 = 2. B replies RESULT(id=42, count=2) to A.
C (leaf) replies RESULT(id=42, count=1) to A.
A adds itself: count = 1 + 2 + 1 = 4. Done.
Deliverables
- Define the fields in each message type.
- Describe the data structure each server maintains per active request.
- Sketch the logic for
on_receive_request(req_id)andon_receive_result(req_id, child_id, count). - A working Python implementation is a strong bonus.
Hints
Hint 1
Think of this as a two-phase message flow: a wave of requests fans out from the root down to the leaves, then a wave of replies carries subtree sizes back up. Each node's job is simply to aggregate its children's replies and add 1 for itself.
Hint 2
A unique request ID is your main tool for idempotency. When a duplicate request arrives, the server should check whether it already started — or already finished — handling that ID, and act accordingly without restarting any work.
Hint 3
Track per-child results in a map keyed by child ID rather than a running integer sum. That way, a duplicated reply from the same child can be detected and ignored, because you can see it is already recorded.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core Idea: Convergecast
This is a classic convergecast pattern. A request wave travels from the root down to every leaf, and a result wave travels back up. Each node contributes exactly 1 to the count (itself) plus the sum of its children's subtree sizes. The challenge is making this work correctly under message loss and duplication.
Three mechanisms handle unreliability:
- Request IDs scope all state. Each aggregation run has a unique ID. Every piece of state a node holds is stored under that ID, so two runs never interfere.
- Senders retransmit; receivers are idempotent. A parent keeps retransmitting
REQUESTto any child that has not replied yet. A child that already finished answers again from a cache. A child still in progress silently ignores the duplicate — its existing work will produce the reply eventually. - Per-child result map instead of a running sum. Results are recorded in a
dict[child_id -> count]. A duplicateRESULTfrom the same child overwrites the same key, so it cannot inflate the total.
Message Schema
| Message | Fields | Direction |
|---|---|---|
REQUEST | req_id: str, sender_id: str | parent → child |
RESULT | req_id: str, sender_id: str, count: int | child → parent |
No separate acknowledgment message is needed. RESULT implicitly acknowledges REQUEST. The parent stops retransmitting to a child once that child's RESULT arrives.
Local State Per Node
Each node maintains a static identity (node_id, parent, children) and a dictionary aggs mapping req_id to an Aggregation record:
Aggregation:
reply_to: str | None # who sent the request (None at root)
pending: set[str] # children we are still waiting on
counts: dict[str, int] # child_id -> reported subtree size
done: bool # True once result has been sent up
result: int # cached final count
State transitions:
(no entry) --REQUEST arrives--> PENDING --all children replied--> DONE --TTL--> evicted
Entries in the DONE state are kept for long enough to answer any late duplicate requests. A safe TTL is several times your worst-case network round-trip.
Handler Logic
on_receive_request(req_id, sender)
- If
senderis not this node's parent, ignore it (stale message after a topology change). - Look up
req_idinaggs.- If DONE: resend the cached
RESULTimmediately. - If PENDING: do nothing. The in-progress aggregation will produce the reply.
- If absent: create a PENDING entry, set
pending = set(children), sendREQUESTto every child, then callcheck_complete(handles the leaf case wherependingis already empty).
- If DONE: resend the cached
on_receive_result(req_id, sender, count)
- Ignore if
req_idis unknown, the aggregation is already DONE, orsenderis not inpending. This covers duplicates, reorders, and replies from strangers. - Record
counts[sender] = countand removesenderfrompending. - Call
check_complete.
check_complete
When pending is empty: result = 1 + sum(counts.values()). Mark DONE. Either send RESULT to parent or, at the root, publish the final answer.
Handling Concurrent Requests (Requirement 4)
Same req_id arrives while PENDING. This is a retransmission. Do nothing. The node's own retransmission timer is already driving its children toward completion, and the eventual RESULT will satisfy the parent.
Different req_id arrives while PENDING. Create a separate Aggregation entry under the new ID. The two runs proceed concurrently and share no state. This is the common case when the root starts a new monitoring cycle before the previous one finishes.
An optional optimisation is to coalesce the new request onto the in-flight aggregation, resolving both IDs with a single fan-out. This is only safe if the caller accepts that the answer reflects a subtree snapshot taken slightly before the new request was issued.
Correctness Argument
Safety. Each child's value enters counts at most once (map keyed by child ID, only accepted while the child is in pending). The result is therefore 1 + Σ(subtree sizes). By induction from the leaves, every DONE node reports exactly the size of its subtree.
Liveness. Assuming every message that is retransmitted indefinitely is eventually delivered: each pending child eventually receives a REQUEST, each finished child eventually has its RESULT delivered. Completion propagates up one level at a time until it reaches the root.
Complexity. With no loss: 2(N−1) messages, one REQUEST and one RESULT per edge. Time: O(depth) round trips because sibling subtrees are processed in parallel. Space per node: O(|children|) per active request.
Python Implementation
from dataclasses import dataclass, field
from typing import Callable, Optional
@dataclass
class Aggregation:
reply_to: Optional[str]
pending: set
counts: dict = field(default_factory=dict)
done: bool = False
result: int = 0
class DistributedNode:
"""
send(dest, msg) is fire-and-forget.
on_root_done(req_id, total) is called when the root has its answer.
"""
def __init__(
self,
node_id: str,
parent: Optional[str],
children: list[str],
send: Callable[[str, dict], None],
on_root_done: Optional[Callable[[str, int], None]] = None,
):
self.node_id = node_id
self.parent = parent
self.children = list(children)
self.send = send
self.on_root_done = on_root_done
self.aggs: dict[str, Aggregation] = {}
# --- Root entry point ---
def start_count(self, req_id: str) -> None:
"""Called on the root node to kick off a new aggregation."""
self.on_receive_request(req_id, sender=None)
# --- Message handlers ---
def on_receive_request(self, req_id: str, sender: Optional[str]) -> None:
# Reject messages from unexpected senders
if sender != self.parent:
return
agg = self.aggs.get(req_id)
if agg is not None:
if agg.done:
self._send_result(req_id, agg) # answer the retransmission
# If still pending, our in-flight work will produce the reply
return
# New request: set up state and fan out
agg = Aggregation(reply_to=sender, pending=set(self.children))
self.aggs[req_id] = agg
for child in self.children:
self.send(child, {"type": "REQUEST", "req_id": req_id, "sender_id": self.node_id})
self._check_complete(req_id, agg)
def on_receive_result(self, req_id: str, sender: str, count: int) -> None:
agg = self.aggs.get(req_id)
# Ignore unknown IDs, already-finished aggregations, or unexpected senders
if agg is None or agg.done or sender not in agg.pending:
return
agg.counts[sender] = count
agg.pending.discard(sender)
self._check_complete(req_id, agg)
# --- Internal helpers ---
def _check_complete(self, req_id: str, agg: Aggregation) -> None:
if agg.pending:
return # still waiting on children
agg.result = 1 + sum(agg.counts.values())
agg.done = True
if self.parent is None and self.on_root_done:
self.on_root_done(req_id, agg.result)
else:
self._send_result(req_id, agg)
def _send_result(self, req_id: str, agg: Aggregation) -> None:
if agg.reply_to is not None:
self.send(agg.reply_to, {
"type": "RESULT",
"req_id": req_id,
"sender_id": self.node_id,
"count": agg.result,
})
Common Mistakes
- Using a running integer sum instead of a per-child map. A duplicated
RESULTfrom the same child would be counted twice, silently inflating the total. - Restarting the fan-out on a duplicate
REQUEST. This sends redundant messages to children, can create multiple in-flight aggregations for the same ID, and breaks the idempotency guarantee. - Forgetting the leaf base case. A leaf has no children, so
pendingis empty from the start.check_completemust be called immediately after setup, or leaves will never respond. - Evicting DONE entries too early. If a cached result is gone before the parent's retransmission timer fires, the next duplicate
REQUESTtriggers a full re-aggregation, which may produce a stale count if the subtree has changed.