Org Chart Service: Hierarchy Storage and Safe Manager Moves
System DesignModel answerLast updated
Design a service for a large company's reporting structure that serves chain and subtree lookups quickly and keeps reporting lines acyclic under concurrent reorganizations.
Org Chart Service
A company with more than 100,000 people (and room to grow) needs a backend that stores who reports to whom. Design that service.
What it must do
- Create employees and change who an employee reports to.
- Return the people who report directly to a given manager.
- Return the full upward chain of managers for any employee.
- Return everyone beneath a given manager, at any depth.
Quality requirements
- Directory reads must be fast and highly available.
- Reorganizations are frequent, including moving whole teams or departments.
- Reporting lines must be strongly consistent. The structure must never contain a loop, such as A managing B while B manages A, even when many changes arrive at the same time.
What to cover in your answer
- A storage schema, and why it keeps subtree queries cheap.
- The HTTP API for the operations above.
- An architecture that handles concurrent changes to the structure safely.
- How you detect and prevent loops when a manager is changed, including what happens when two changes race.
State your assumptions about scale (read and write rates, tree depth) and justify your choices with trade-offs.
Hints
Hint 1
Compare four ways of storing a tree: a plain parent pointer, nested intervals, stored paths, and an ancestor/descendant pair table. For each, ask how costly subtree reads and subtree moves are.
Hint 2
Moving employee E under manager M creates a loop exactly when M is E or already sits below E. Think about which storage layout lets you test that with a single lookup.
Hint 3
Two moves can each look safe on their own and still form a loop together (A under B, B under A). Which isolation or locking strategy rules this out, and is a heavy one acceptable at your write rate?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing and assumptions
| Item | Assumption |
|---|---|
| Employees | 100K now, plan for 10M |
| Depth | Typically 8-12, at most about 20 |
| Reads | 2-5K QPS (profiles, org-chart pages, permission checks) |
| Writes | Under 10/s normally; a reorg may move several thousand people at once |
| Data size | About 1 KB per person, around 100 MB total. The bare hierarchy (id, manager id) is only a couple of MB |
Conclusions: the workload is overwhelmingly read-heavy, the whole tree fits in RAM on every server, and writes are rare but must be strictly correct.
2. Storage model
| Model | Subtree read | Ancestors | Move a subtree | Notes |
|---|---|---|---|---|
| Parent pointer | Recursive query | Recursive query | O(1) | Simple, slow for deep reads |
| Nested intervals | Range scan | Range scan | O(N) renumber | Poor fit for frequent moves |
| Stored path | Prefix scan | Parse string | Rewrite every path below | Compact, fine |
| Closure table | One indexed lookup | One indexed lookup | O(subtree x depth) rows | Flexible, easy loop check |
Choice: keep a parent pointer on the employee row as the source of truth, and maintain a closure table beside it, in a relational database with transactions (for example Postgres). At 100K people and depth 10 the closure table has about 1M rows, which is small.
employees(id PK, name, title, dept_id, manager_id NULL REFERENCES employees,
version INT, updated_at)
org_closure(ancestor_id, descendant_id, depth,
PRIMARY KEY (ancestor_id, descendant_id),
INDEX (descendant_id, depth))
org_meta(org_id PK, tree_version BIGINT)
manager_history(employee_id, manager_id, valid_from, valid_to)
Every node has a self row with depth 0. Queries:
- Direct reports:
WHERE manager_id = ?(or closure withdepth = 1). - Chain:
WHERE descendant_id = ? ORDER BY depth. - Subtree:
WHERE ancestor_id = ? AND depth > 0, paginated.
3. API
POST /employees -> 201 {id, version}
GET /employees/{id}
PATCH /employees/{id} (non-hierarchy fields only)
PUT /employees/{id}/manager {new_manager_id, expected_version} -> 200 | 409 cycle | 412 stale
GET /employees/{id}/reports ?cursor&limit
GET /employees/{id}/chain
GET /employees/{id}/subtree ?max_depth&cursor&limit
POST /reorgs {moves:[...], effective_at} -> 202 {reorg_id}
Manager changes get their own endpoint because they need loop validation and concurrency control. expected_version gives optimistic concurrency. Bulk reorgs are all-or-nothing.
4. Move operation and loop prevention
Invariant: moving E under M creates a loop if and only if M equals E or M is a descendant of E.
With the closure table this is one lookup:
SELECT 1 FROM org_closure WHERE ancestor_id = :E AND descendant_id = :M;
The self row covers the case M = E. If a row comes back, reject with 409.
The move, in one transaction:
- Delete closure rows linking E's subtree to E's old ancestors (ancestors strictly above E).
- Insert rows linking every ancestor of M (including M) to every node in E's subtree, with depth =
a.depth + d.depth + 1. - Update
employees.manager_id, bumpversion, bumporg_meta.tree_version.
Why the check alone fails. Two concurrent transactions can each validate and still combine into a loop: T1 moves A under B (B is not below A), T2 moves B under A (A is not below B), both commit. This is write skew. Options:
- Serialize all hierarchy writes with a row lock on
org_meta(SELECT ... FOR UPDATE) or an advisory lock. At under 10 writes/s with millisecond transactions, this costs nothing and is easy to prove correct. This is the right default. - SERIALIZABLE isolation. The database aborts one of the conflicting transactions and the client retries. Correct, but abort rates climb during large reorgs.
- Fine-grained locking. Lock E, M and M's ancestors in id order. More concurrency, harder to reason about; only worth it for a multi-tenant system at much larger scale.
A distributed lock (Redis, ZooKeeper) is only needed if hierarchy data spans several databases. With one database, its own lock is safer because there are no lease-expiry races.
Bulk reorgs. Apply moves one after another inside a single transaction under the same lock, validating each against the intermediate state. Order matters: a batch may be valid in one order and fail in another. Process asynchronously (return 202). Moving 5K people at depth 10 is roughly 50K closure inserts, under a second.
As a defense in depth, add a periodic job that walks parent pointers and verifies there are no loops and that the closure table matches the parent pointers.
5. Architecture
Clients -> Gateway -> Directory service (stateless)
reads -> in-memory tree per instance (or Redis)
writes -> single logical writer (lock) -> Postgres primary
-> outbox/CDC -> Kafka "org-changes" -> caches, search index
Read replicas serve profile lookups; search is fed from CDC.
- Writes go to the primary under the lock. A transactional outbox publishes
{tree_version, employee, old_manager, new_manager}after commit. - Reads: each instance keeps parent and child arrays in memory (a few MB at 100K, still modest at 10M). Chain is a pointer walk of about 10 steps; subtree is a DFS over child lists. Instances apply change events in
tree_versionorder, and fall back to a reload if they detect a gap. - Consistency: a client that just made a change can pass the returned
tree_versionand the read path waits until it has caught up (read-your-writes). Everyone else tolerates sub-second staleness. - Availability: replicas and in-memory copies keep serving reads if the primary fails over; only writes pause.
6. Trade-offs and extras
- Closure table costs extra storage and write amplification in exchange for simple reads and a trivial loop check. Moving a large department is the worst case; that is why it is batched and async.
- If depth were tiny and subtrees small, a parent pointer plus recursive queries would suffice. If almost nothing moved, nested intervals would be fine.
- Temporal queries ("who was the manager last March?") use
manager_history. - Permission checks that depend on the hierarchy should use the in-memory tree and carry the
tree_versionthey were evaluated against.
7. Common mistakes
- Checking for loops without serializing writes, which misses write skew.
- Putting manager changes into a generic update and skipping validation.
- Choosing nested intervals despite frequent moves.
- Reaching for a distributed lock when a single database lock is enough.
- Unbounded subtree responses with no pagination or depth limit.
- Applying bulk moves in an arbitrary order or not atomically.
- Forgetting the self row (depth 0), which breaks the self-move check.