Design a Tree Storage Service with Descendant Lookup
System DesignModel answerLast updated
Design a REST API and backing storage model to persist a node hierarchy and efficiently retrieve all descendants of any node.
Design a Tree Storage Service with Descendant Lookup
You are tasked with designing a backend service that manages a hierarchy of nodes — think page trees, folder structures, org charts, or category taxonomies.
Functional Requirements
The service must support two core operations:
- Add a node — insert a new node under a specified parent. Inserting with no parent creates a new root (the system may contain multiple roots, forming a forest).
- Fetch all descendants — given a node, return every node in its subtree, recursively, at any depth.
What to Cover
Your design should address:
- API contract: Define REST endpoints for both operations. Include example request and response bodies, relevant status codes, and any headers worth calling out.
- Storage model: Compare at least two tree-storage strategies (for example: adjacency list, materialized path, nested sets, closure table). Pick one (or a combination) and justify it in terms of query performance, write cost, and operational complexity.
- Large subtrees: A subtree can contain up to one million nodes. How do you paginate the descendant response? Why does cursor-based pagination matter here?
- Cycle prevention: Under what conditions could a cycle be introduced, and how does your design prevent it?
- At least one edge case from each of: the write path (creating a node) and the read path (fetching descendants).
Scope
You do not need to design a full distributed system. Focus on the API surface, the schema, and the reasoning behind your choices. Mentioning move and delete operations is a bonus; you do not need to fully design them.
Hints
Hint 1
Start by asking clarifying questions about read/write ratio and expected subtree size — this directly drives your schema choice. A read-heavy workload favors a structure that makes descendant queries cheap, even if writes become slightly more expensive.
Hint 2
Think about what makes OFFSET-based pagination dangerous for tree data specifically. Concurrent inserts mid-traversal and the cost of skipping rows at large offsets are both problems. What alternative gives you a stable, O(limit) page?
Hint 3
Cycle creation is impossible on a pure add-only API — a brand new node has no descendants, so it cannot be an ancestor of its own parent. Cycles only become possible when you support moving a node. Mention this distinction even if move is out of scope.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Questions First
Before drawing any boxes, ask:
- Operations in scope: Add and fetch descendants are required. Are move and delete needed? Even if not, flag that move is where cycles become possible.
- Read/write ratio: Tree reads typically dominate writes by something like 100:1. This matters because several schema options trade write cost for read speed.
- Subtree shape: How deep can trees get, and how wide? A max depth of 20 is common; 1,000 is possible. A single subtree might hold a million nodes.
- Response format: Flat list with depth and parent ID, or nested JSON? Nested JSON cannot be paginated cleanly, so flat is the right default.
- Multi-tenancy: Are trees scoped to a workspace or tenant? If so, every query needs a
tenant_idfilter.
API Design
Keep it resource-oriented. Nodes are the resource.
Create a node
POST /v1/nodes
Idempotency-Key: <client-generated UUID>
{
"parentId": "n_42",
"name": "Q3 Planning"
}
201 Created
Location: /v1/nodes/n_108
{
"id": "n_108",
"parentId": "n_42",
"name": "Q3 Planning",
"depth": 3,
"createdAt": "2024-05-01T10:00:00Z"
}
parentId: nullcreates a root node.- Return
404if the parent does not exist (avoid distinguishing "does not exist" from "not visible" to prevent existence leaking across tenants). - The
Idempotency-Keyheader makes retries safe — a network failure after the insert but before the201reaches the client should not create a duplicate.
Fetch descendants
GET /v1/nodes/n_42/descendants?maxDepth=5&limit=100&cursor=<opaque>
{
"items": [
{ "id": "n_77", "parentId": "n_42", "depth": 1, "name": "..." },
{ "id": "n_108", "parentId": "n_77", "depth": 2, "name": "..." }
],
"nextCursor": "<opaque>",
"hasMore": true
}
Two supporting endpoints worth mentioning: GET /v1/nodes/{id}/children for direct-children-only (the common lazy-load pattern in tree UIs), and GET /v1/nodes/{id} for a single node. A PATCH for moving a node is out of scope but worth naming.
Storage Model Comparison
| Model | Insert cost | Descendants query | Move subtree |
|---|---|---|---|
| Adjacency list | O(1) | Recursive CTE — many index probes at depth | O(1) |
| Materialized path | O(1) | Prefix range scan — fast | Rewrite every path in subtree |
| Nested sets | O(n) — renumbers tree | Range scan | O(n) |
| Closure table | O(depth) rows | Single index scan | O(subtree × depth) |
Nested sets are a trap for any workload with concurrent writes. Every insert renumbers a large fraction of the table. Reject it early and explain why.
Recommended approach: adjacency list as the source of truth, plus a closure table for descendant queries.
CREATE TABLE nodes (
tenant_id BIGINT,
id BIGINT,
parent_id BIGINT, -- NULL for roots
name TEXT,
depth INT,
created_at TIMESTAMPTZ,
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, parent_id) REFERENCES nodes(tenant_id, id)
);
CREATE TABLE node_closure (
tenant_id BIGINT,
ancestor_id BIGINT,
descendant_id BIGINT,
depth INT,
PRIMARY KEY (tenant_id, ancestor_id, depth, descendant_id)
);
CREATE INDEX ON node_closure (tenant_id, descendant_id);
Inserting a new node under parent P (single transaction):
INSERT INTO nodes VALUES (:tenant, :new_id, :parent_id, :name, ...);
INSERT INTO node_closure (tenant_id, ancestor_id, descendant_id, depth)
SELECT tenant_id, ancestor_id, :new_id, depth + 1
FROM node_closure
WHERE tenant_id = :t AND descendant_id = :parent_id
UNION ALL
SELECT :t, :new_id, :new_id, 0; -- self-row
The self-row at depth 0 keeps every query uniform. Insert cost is O(depth of parent), which is acceptable given typical tree depths.
A materialized path (Postgres ltree with GiST index) is equally defensible. It gives fast prefix-scan reads and free DFS ordering. The downside is that moving a node rewrites every path in its subtree. If move is out of scope, materialized path is a strong single-structure alternative. State the trade-off and choose deliberately — that is what gets credit.
Pagination for Large Subtrees
Never use OFFSET. At large offsets it re-scans skipped rows, and concurrent inserts shift the window so rows are duplicated or missed across pages.
Use keyset pagination. The cursor encodes (depth, descendant_id), which maps directly to the primary key of node_closure:
SELECT n.*
FROM node_closure c
JOIN nodes n ON n.tenant_id = c.tenant_id AND n.id = c.descendant_id
WHERE c.tenant_id = :t
AND c.ancestor_id = :root_id
AND c.depth > 0
AND (c.depth, c.descendant_id) > (:cur_depth, :cur_id) -- keyset resume
AND c.depth <= :max_depth
ORDER BY c.depth, c.descendant_id
LIMIT :page_size;
Each page is O(page_size) — it reads a contiguous slice of the index. Breadth-first ordering means a parent always appears before its children, which makes client-side tree reconstruction straightforward.
Cap limit at something like 1,000. For full exports of very large subtrees, issue an async job: POST /v1/nodes/{id}/exports returns 202 Accepted with a job ID. The result lands in blob storage and the client polls or receives a webhook.
Cycle Prevention
On a pure add-only API, cycles are structurally impossible. A freshly created node has no descendants, so it cannot already be an ancestor of its intended parent. The foreign key on parent_id ensures the parent exists, and the insert transaction is what makes the node visible — there is no window for a race.
Cycles only become possible with a move operation (PATCH /v1/nodes/{id} with a new parentId). Before committing a move, check that the proposed new parent is not already a descendant of the node being moved. With the closure table this is one query:
SELECT 1 FROM node_closure
WHERE tenant_id = :t AND ancestor_id = :node_id AND descendant_id = :new_parent_id;
If a row is returned, reject the move with 422 Unprocessable Entity.
Common Mistakes to Avoid
- Returning nested JSON for descendants — it cannot be paginated and creates unbounded response sizes.
- Choosing nested sets without flagging the write cost; interviewers notice.
- Using OFFSET pagination and not explaining why it breaks under concurrent writes.
- Forgetting the
tenant_idscoping — a security boundary, not just a performance concern. - Treating cycle prevention as a general graph problem without noting that add-only trees are cycle-free by construction.