KatInterview

Design a Tree Storage Service with Descendant Lookup

System DesignModel answer
MediumModel answerSystem DesignREST APIdatabase schematrees

Last 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:

  1. 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).
  2. 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.