Designing a Thread-Safe Organization Hierarchy Service
System DesignModel answerLast updated
Design a thread-safe, concurrent organization tree supporting high-volume reads and atomic modifications without deadlocks or partial updates.
Design an in-memory organization hierarchy service that supports concurrent access for both reads and writes across users and groups.
Core Structure & Operations
- The hierarchy is structured as a tree composed of Users (leaves) and Groups (internal nodes).
- Read Workloads: High-throughput queries such as finding the Lowest Common Ancestor (LCA) of multiple users, fetching member lists of subtrees, and navigating paths to the root.
- Write Workloads: Modifications including adding/removing users or groups, re-parenting subtrees (
move), and executing multi-step batch updates.
Requirements & Challenges
- Concurrency Strategy: Propose an architectural model balancing low-latency reads and safe, atomic writes (e.g., Reader-Writer locks, fine-grained node locks, or immutable Copy-on-Write snapshots).
- Consistency Guarantees: Ensure queries never observe transient invalid states (such as dangling references, detached nodes, or temporary cycles during re-parenting). Explain how to support snapshot isolation and read-your-own-writes semantics.
- Edge Cases & Deadlock Prevention: Detail cycle detection protocols during node moves, handling deletion of non-empty groups, and preventing deadlocks under concurrent write attempts.
- Performance & Memory: Analyze memory contention, garbage collection/epoch management for long-running readers, and trade-offs under high write contention.
Hints
Hint 1
Identify the read-to-write ratio first; in typical enterprise org structures, reads outnumber writes by several orders of magnitude.
Hint 2
Consider how immutable persistent data structures (like structural sharing) eliminate lock contention for readers.
Hint 3
To prevent cycles during a subtree move, trace the path from the target parent upwards to ensure the target is not a descendant of the node being moved.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scale & System Assumptions
Before picking a concurrency paradigm, we establish the operating envelope:
| Parameter | Operational Target |
|---|---|
| Data Size | 100,000 Users, 10,000 Groups, Depth $\le 20$ |
| Read Volume | ~10,000 QPS (LCA lookups, member listings, permission checks) |
| Write Volume | ~10-50 QPS steady-state, with periodic bursts during batch re-organizations |
| Deployment Model | In-memory operational store with persistence via Append-Only Log / Write-Ahead Log (WAL) |
Key Consistency Mandates
- Zero Partial Updates: A query traversing the tree must never observe an intermediate state where a user or group is detached or temporarily duplicated.
- Cycle Prevention: Moving a node $N$ under node $P$ must atomically fail if $P$ is a descendant of $N$.
- Non-Blocking Reads: High read traffic must never be delayed by write operations or long-running structural validation.
2. API & Interface Design
class OrgServiceAPI:
def add_user(self, user_id: str, group_id: str) -> int: ...
def remove_user(self, user_id: str) -> int: ...
def add_group(self, group_id: str, parent_id: str) -> int: ...
def remove_group(self, group_id: str, mode: str) -> int: ... # mode: REJECT_IF_HAS_CHILDREN | REPARENT_CHILDREN_UP
def move_node(self, node_id: str, new_parent_id: str) -> int: ...
def apply_batch(self, operations: list[Operation]) -> int: ...
# Read Interface
def get_snapshot(self) -> Snapshot: ...
def read_at_version(self, min_version: int, timeout_ms: int) -> Snapshot: ...
Every write operation returns a monotonically increasing 64-bit Version Sequence Number. Clients requiring read-your-own-writes pass their last observed version number to read_at_version.
3. Concurrency Architecture Strategy Comparison
Selecting the right locking or isolation mechanism is central to meeting throughput goals:
+-------------------------------------------------------------------------------+
| Strategy 1: Global Reader-Writer Lock (RWLock) |
| - Simple to implement. |
| - Concurrently blocks readers during batch writes or causes write starvation.|
+-------------------------------------------------------------------------------+
| Strategy 2: Fine-Grained Node-Level Lock (Hand-over-Hand / Two-Phase Locking) |
| - Enables concurrent updates to disjoint subtrees. |
| - High complexity; cycle checks and LCA walks require acquiring multiple |
| locks up the root, creating severe deadlock risks and high lock overhead. |
+-------------------------------------------------------------------------------+
| Strategy 3: Single-Writer Copy-on-Write (MVCC-lite via Structural Sharing) |
| - Reads require zero locks and run at native pointer-chasing speed. |
| - Writes execute sequentially via a single mutex on a draft version. |
| - Perfectly matches read-heavy workload profiles. |
+-------------------------------------------------------------------------------+
Recommendation: Copy-on-Write with Structural Sharing (MVCC-lite)
Since the workload is overwhelmingly read-heavy (10,000 QPS read vs 10 QPS write), Copy-on-Write (CoW) combined with Persistent Data Structures is optimal:
- Readers obtain a pointer to an immutable snapshot of the hierarchy tree.
- A single write lock serializes all mutating operations. The writer constructs a new immutable snapshot with structural path-copying, updates the Write-Ahead Log (WAL), and updates the global snapshot pointer using an atomic CAS / store.
4. Implementation Details & Data Structure Design
Using persistent maps (e.g., Hash Array Mapped Trie / HAMT), modifying a path of length $D$ duplicates only $O(\log N)$ or $O(D)$ internal trie nodes while sharing remaining immutable subtrees.
import threading
from typing import Optional, Dict, Set
from pyrsistent import pmap, pset, PMap, PSet
class HierarchyState:
"""Immutable state container representing a point-in-time snapshot."""
__slots__ = ('parent_map', 'children_map', 'node_types', 'version')
def __init__(
self,
parent_map: PMap[str, str],
children_map: PMap[str, PSet[str]],
node_types: PMap[str, str],
version: int
):
self.parent_map = parent_map # child_id -> parent_id
self.children_map = children_map # parent_id -> PSet(child_id)
self.node_types = node_types # node_id -> 'USER' | 'GROUP'
self.version = version
def find_lca(self, node_a: str, node_b: str) -> Optional[str]:
"""Calculates Lowest Common Ancestor on the immutable snapshot without locks."""
path_a = []
curr = node_a
while curr:
path_a.append(curr)
curr = self.parent_map.get(curr)
ancestors_a = set(path_a)
curr = node_b
while curr:
if curr in ancestors_a and self.node_types.get(curr) == "GROUP":
return curr
curr = self.parent_map.get(curr)
return None
class ConcurrentOrgHierarchy:
def __init__(self, root_group_id: str):
initial_state = HierarchyState(
parent_map=pmap(),
children_map=pmap({root_group_id: pset()}),
node_types=pmap({root_group_id: "GROUP"}),
version=0
)
self._current_state = initial_state
self._write_mutex = threading.Lock()
self._version_cond = threading.Condition(self._write_mutex)
def get_snapshot(self) -> HierarchyState:
"""Atomic pointer load providing a linearizable snapshot."""
return self._current_state
def move_node(self, node_id: str, new_parent_id: str) -> int:
"""Atomically moves a user or group to a new parent group with cycle detection."""
with self._write_mutex:
curr = self._current_state
# Validation 1: Check node existence and parent validity
if node_id not in curr.node_types or curr.node_types.get(new_parent_id) != "GROUP":
raise ValueError("Invalid target node or destination group.")
# Validation 2: Cycle Detection (Walk up from target parent)
ancestor = new_parent_id
while ancestor is not None:
if ancestor == node_id:
raise ValueError(f"Invalid move: '{new_parent_id}' is a descendant of '{node_id}'.")
ancestor = curr.parent_map.get(ancestor)
old_parent = curr.parent_map.get(node_id)
if old_parent == new_parent_id:
return curr.version # No-op
# Build new state structurally
new_children = curr.children_map
# Detach from old parent
if old_parent:
updated_old_set = new_children[old_parent].remove(node_id)
new_children = new_children.set(old_parent, updated_old_set)
# Attach to new parent
updated_new_set = new_children[new_parent_id].add(node_id)
new_children = new_children.set(new_parent_id, updated_new_set)
new_parent_map = curr.parent_map.set(node_id, new_parent_id)
# Create new immutable state
new_state = HierarchyState(
parent_map=new_parent_map,
children_map=new_children,
node_types=curr.node_types,
version=curr.version + 1
)
# Linearization point: atomic reference exchange
self._current_state = new_state
self._version_cond.notify_all()
return new_state.version
def await_version(self, target_version: int, timeout_sec: float = 2.0) -> HierarchyState:
"""Enables Read-Your-Own-Writes semantics."""
with self._write_mutex:
end_time = threading.Lock() # simulation placeholder
while self._current_state.version < target_version:
if not self._version_cond.wait(timeout=timeout_sec):
raise TimeoutError(f"Version {target_version} not reached in time.")
return self._current_state
5. Failure Recovery & Memory Reclamation
Garbage Collection & Long-Running Reads
Because queries execute over immutable snapshot references, a long-running report query holds a snapshot reference.
- Managed Memory (JVM / Python): The runtime Garbage Collector reclaims unreferenced historical trie branches automatically when the reader completes.
- Unmanaged Memory (C++ / Rust): Use Epoch-Based Reclamation (EBR) or
std::shared_ptrhazard pointers. ARC (Atomic Reference Counting) can suffer from atomic operation cache line bouncing under high core counts; EBR avoids cache line thrashing by grouping reclamation into epoch phases. - Bounding Memory Spikes: Enforce maximum reader durations. If a reader retains a snapshot older than $N$ versions or 60 seconds, issue a warning or force an exception to protect memory budgets under high write bursts.
Durability & Recovery Strategy
Write operations execute under the following WAL sequence:
- Acquire single write mutex.
- Form draft snapshot and perform path validation & cycle checks.
- Append operation payload and version number to disk WAL (via
fsyncor raft consensus log). - Atomic pointer release to update
_current_state.
Upon crash recovery, replay the WAL sequentially against an empty root to rebuild the persistent trie state up to the last flushed version.
6. Trade-offs and Verification
Trade-off Matrix
| Metric | Single Writer + CoW (Proposed) | Global RWLock | Fine-Grained Locking |
|---|---|---|---|
| Read Latency | Extremely Low ($O(1)$ lock-free pointer dereference) | Low (Subject to lock acquisitions) | Moderate (Path locking overhead) |
| Write Throughput | Moderate (~10k-50k writes/sec single thread) | Low | High (Disjoint subtrees write concurrently) |
| Deadlock Risk | Zero (Serialized single writer) | Medium | High (Needs strict address sorting) |
| Memory Footprint | Low-Medium (Structural sharing overhead) | Minimal | Low |
Concurrency Correctness Validation
- ThreadSanitizer (TSan) & Race Detectors: Compile native runtime code with TSan active to verify zero data races on shared memory pointers.
- Deterministic Simulation Testing (FoundationDB style): Inject artificial yield/sleep statements during cycle check validations and tree mutations while executing randomized write loads.
- Linearizability Verification (Jepsen-style tests): Spawn parallel workers generating randomized ops (moves, inserts, deletes) paired with verification workers that execute tree traversals against snapshots, ensuring invariant checks (e.g., node count, cycle independence, single-parent constraint) hold true across every snapshot version.