Org Tree Reporting Hierarchy Count Service
System DesignModel answerLast updated
Design a system to efficiently query total subordinate counts in a corporate hierarchy while handling organizational structure changes.
Design a service for a corporate organizational hierarchy where employees report to managers in a tree structure (each employee has at most one direct manager, executives at the top have none).
Your system must support:
-
Query operation (high volume): Given an employee ID, return the total number of people in their complete reporting chain (all direct reports, their reports, and so on recursively).
-
Update operation: Handle changes when an employee moves to a different manager. All subsequent queries must reflect the updated structure.
Consider:
- How would you model and store this data?
- What algorithms would you use for queries and updates?
- How would you maintain query performance under frequent reads with occasional writes?
- How would you prevent invalid states like reporting cycles?
- What are the trade-offs in your design?
Assume a large enterprise with hundreds of thousands of employees, query rates in the tens of thousands per second, and organizational changes happening throughout each day.
Hints
Hint 1
The reporting hierarchy forms a forest (collection of trees) - what properties of trees can you exploit?
Hint 2
Consider materializing aggregate data rather than computing it on every query
Hint 3
Think about what changes when one person moves - does the entire tree need recalculation?
Hint 4
Reporting hierarchies in real companies are quite shallow, typically 10-20 levels maximum
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Org Tree Reporting Hierarchy Count Service
1. Requirements and Scale Analysis
Begin by establishing concrete numbers that guide design decisions:
Scale parameters:
- Employee count: 200k-500k (design for up to 1M)
- Hierarchy depth: 10-20 levels in practice (corporate structures are shallow)
- Query throughput: 20k-100k requests/second (dashboards, profile views, reporting tools)
- Update frequency: thousands per day for individual moves, occasional batch reorganizations affecting hundreds
- Latency target: sub-10ms p99 for queries
Correctness constraints:
- Structure must remain a valid forest (no cycles)
- Each employee has exactly one manager or none (if at top level)
- Counts must eventually converge after updates (strong consistency not required immediately for all readers)
Key operations:
getSubordinateCount(employeeId)→ integer countupdateManager(employeeId, newManagerId)→ success/erroraddEmployee(employeeId, managerId)→ success/error
2. Data Model
Store the organizational structure in a relational database as the authoritative source:
employees (
id PRIMARY KEY,
manager_id FOREIGN KEY REFERENCES employees(id) NULL,
subordinate_count INT NOT NULL DEFAULT 0,
version BIGINT,
updated_at TIMESTAMP
)
hierarchy_changes (
sequence_id BIGINT PRIMARY KEY AUTO_INCREMENT,
employee_id BIGINT,
old_manager_id BIGINT,
new_manager_id BIGINT,
timestamp TIMESTAMP
)
The subordinate_count field is precomputed and materialized. This converts an expensive recursive query into a simple lookup. The count represents all descendants (reports, their reports, etc.) but not the employee themselves.
3. Core Algorithm
Query: Return the stored subordinate_count[employeeId] - this is O(1).
Update when moving employee X from manager A to manager B:
The key insight: when X moves, only the counts along the ancestor paths change. X's subtree remains intact.
Let s = subordinate_count[X] + 1 (X plus all their descendants).
-
Cycle prevention: Walk upward from B following parent pointers. If we encounter X before reaching the root, reject the move (would create a cycle). This takes O(depth).
-
Remove from old path: Starting at A, walk up to the root, subtracting
sfrom each ancestor's count. -
Update parent pointer: Set
parent[X] = B. -
Add to new path: Starting at B, walk up to the root, adding
sto each ancestor's count.
This update costs O(depth) database writes, approximately 15-30 rows for typical hierarchies.
Pseudocode:
def get_subordinate_count(emp_id):
return db.query("SELECT subordinate_count FROM employees WHERE id = ?", emp_id)
def update_manager(emp_id, new_manager_id):
# Start transaction
with db.transaction():
# Lock involved rows
emp = db.lock_row("employees", emp_id)
old_manager_id = emp.manager_id
# Validate no cycle
current = new_manager_id
while current is not None:
if current == emp_id:
raise CycleError("Cannot move employee under their own subordinate")
current = db.query("SELECT manager_id FROM employees WHERE id = ?", current)
# Calculate subtree size
subtree_size = emp.subordinate_count + 1
# Update old manager's path (subtract)
current = old_manager_id
while current is not None:
db.execute(
"UPDATE employees SET subordinate_count = subordinate_count - ? WHERE id = ?",
subtree_size, current
)
current = db.query("SELECT manager_id FROM employees WHERE id = ?", current)
# Update parent pointer
db.execute("UPDATE employees SET manager_id = ? WHERE id = ?", new_manager_id, emp_id)
# Update new manager's path (add)
current = new_manager_id
while current is not None:
db.execute(
"UPDATE employees SET subordinate_count = subordinate_count + ? WHERE id = ?",
subtree_size, current
)
current = db.query("SELECT manager_id FROM employees WHERE id = ?", current)
# Log change
seq = db.insert("hierarchy_changes", emp_id, old_manager_id, new_manager_id)
return seq
4. Architecture for Scale
To handle high query volume with low latency:
Write Path:
HR Tools → Write Service → Primary DB → Change Stream (Kafka)
Read Path:
Change Stream → Read Replicas (in-memory) → Load Balancer → Clients
↓
Cache Layer
Write service (single writer):
- Serializes all hierarchy modifications
- Handles cycle checking and count updates transactionally
- Publishes changes to a stream
- Write volume is low enough for a single instance with failover
Read replicas:
- Load entire hierarchy into memory at startup (~20-40 MB for 1M employees)
- Store as adjacency list:
parent_map[emp_id]andcount_map[emp_id] - Subscribe to change stream and apply updates incrementally
- Serve queries from memory at microsecond latency
- Scale horizontally by adding replicas
Benefits:
- Queries are pure memory lookups (no database hit)
- Write path ensures data integrity through single-writer serialization
- Read-write separation allows independent scaling
- The entire structure fits easily in RAM
5. Handling Edge Cases and Trade-offs
Eventual consistency:
- Read replicas lag behind writes by milliseconds to seconds
- For read-your-writes semantics, return the change sequence number on writes
- Client can specify minimum version in queries; replica either serves it or redirects to primary
Bulk reorganizations:
- Moving thousands of employees individually is expensive
- For large batches: compute all new parent pointers, validate no cycles globally, then recompute all counts via post-order traversal in O(N)
- Treat as a new snapshot and publish atomically
Correctness verification:
- Run periodic reconciliation: recompute counts from scratch and compare against materialized values
- Alert on discrepancies (indicates bugs or partial failures)
- Since counts are derived data, repair by recomputation
Alternative: compute on read:
- Store only parent pointers, compute counts via recursive queries
- Simpler writes but O(N) query cost in worst case
- Could cache computed results, but cache invalidation on any subtree update is complex
- Rejected due to read-heavy workload requirements
Concurrency gotcha:
- Two concurrent moves can individually pass cycle checks but together create a cycle
- Example: simultaneously moving A under B and B under A
- Solution: single-writer queue or locking both ancestor paths
- Single writer is simpler and sufficient given write volume
6. Complexity Analysis
- Query: O(1) with materialized counts
- Update: O(depth) ≈ O(1) in practice since depth is bounded at ~20
- Bulk recompute: O(N) using post-order traversal
- Space: O(N) for storing N employees
- Memory per replica: ~30-50 bytes per employee ≈ 30-50 MB for 1M employees
Common Mistakes to Avoid
- Computing counts recursively on every query (too slow for read-heavy load)
- Forgetting cycle prevention (can corrupt the tree structure)
- Not considering concurrent updates that together form a cycle
- Assuming unlimited depth (real org charts are shallow - exploit this)
- Over-engineering for write throughput (writes are rare relative to reads)
- Not materializing aggregate data for a read-heavy access pattern