Scrivio Interview library
DesignIntermediate8 min read · updated 12 November 2026

A product category tree with 200,000 nodes is read on every page and updated a few times a day. Compare adjacency list with recursive CTEs, materialized path (ltree), nested sets and a closure table for this use.

An adjacency list (parent_id) is the simplest to update, but every subtree read needs a recursive CTE with one iteration per level. A materialised path or ltree turns subtree reads into indexed prefix queries but rewrites descendants when a subtree moves; nested sets read fast but renumber much of the tree on every insert; a closure table stores every ancestor-descendant pair, so reads are plain joins and writes insert many rows. For 200,000 nodes read on every page and changed a few times a day, I would keep parent_id as the source of truth and add a closure table or ltree, or simply cache the whole tree in memory.

Why this question is asked

Category trees look like a small problem until they sit on the hot path. Every product page shows breadcrumbs, every listing filters by 'this category and everything under it', and every menu renders a branch. At 200,000 nodes, the difference between a good and a bad tree model is the difference between a 1 millisecond lookup and a recursive query on every request. Interviewers ask this design question to see whether we can compare models by their read and write costs and fit them to a workload. In this answer, we will recap the four models with the same small tree, measure the cost of a subtree read and a move in each, and then choose one for this workload with numbers.

1The Workload and a Small Example Tree

Our workload has two clear properties. Reads are constant: every page needs either the ancestors of one category (breadcrumbs) or all descendants of one category (listings). Writes are rare: a few edits a day, usually adding a leaf, occasionally moving a branch. A design that makes reads cheap at the cost of slower writes is therefore a good trade.

To compare the models, we use one small tree throughout: Electronics (1) has Phones (2) and Laptops (3), and Phones has Android (4) and iPhone (5).

2Adjacency List With Recursive CTEs

The adjacency list stores one column, parent_id, per node. Adding a node is one insert; moving a branch is one update of one row. It is impossible to get out of sync, because each fact is stored once.

The cost is on the read side. Finding all descendants of Electronics needs a recursive CTE, which runs one iteration per level of depth, each iteration an index lookup on parent_id.

SQL
CREATE TABLE category (id int PRIMARY KEY, parent_id int REFERENCES category, name text);
CREATE INDEX ON category (parent_id);
WITH RECURSIVE sub AS (
SELECT id FROM category WHERE id = 1
UNION ALL
SELECT c.id FROM category c JOIN sub s ON c.parent_id = s.id
)
SELECT id FROM sub; -- 1, 2, 3, 4, 5 (3 iterations for 3 levels)

For a branch with 5,000 nodes six levels deep, this is fast enough for a report but noticeably expensive when it runs on every page view, thousands of times a second.

3Materialised Path and ltree

A materialised path stores, on every node, the full path from the root, such as 1.2.4 for Android. PostgreSQL's ltree extension provides a type for exactly this, with operators like <@ (is a descendant of) and @> (is an ancestor of) and support for GiST indexes. With a plain text path, a B-tree index with text_pattern_ops supports prefix queries such as path LIKE '1.2.%'.

SQL
CREATE EXTENSION IF NOT EXISTS ltree;
ALTER TABLE category ADD COLUMN path ltree;
CREATE INDEX category_path_gist ON category USING gist (path);
-- Electronics '1', Phones '1.2', Laptops '1.3', Android '1.2.4', iPhone '1.2.5'
SELECT id FROM category WHERE path <@ '1.2'; -- 2, 4, 5 (Phones and below)
SELECT id FROM category WHERE path @> '1.2.4'; -- 1, 2, 4 (breadcrumbs for Android)
-- Moving Phones under Laptops rewrites every descendant's path:
UPDATE category SET path = '1.3' || subpath(path, 1) WHERE path <@ '1.2'; -- 3 rows

Subtree and ancestor reads become one indexed query with no recursion. Using ids rather than names in the path means renaming a category changes nothing. But moving a branch rewrites the path of every node in it, so moving a branch of 20,000 categories updates 20,000 rows. That is fine a few times a day, provided it runs in one transaction.

4Nested Sets

Nested sets number the tree in a depth-first walk, giving each node a left and right value, so that every descendant's numbers fall inside its ancestor's range. Electronics gets (1, 10), Phones (2, 7), Android (3, 4), iPhone (5, 6), Laptops (8, 9). A subtree read is one range query, WHERE lft BETWEEN 2 AND 7, which is very fast.

The problem is every write. Inserting a new node under Android means adding 2 to the left and right values of every node to its right in the walk, which on average is half the tree: around 100,000 row updates and locks for one new leaf. Concurrent edits block each other on those rows. Nested sets suit trees that are written almost never and rebuilt in bulk, and they are a poor fit for anything with concurrent writers.

5Closure Table

A closure table stores every ancestor-descendant pair, including each node paired with itself at depth 0. For our tree that is 11 rows: (1,1,0), (1,2,1), (1,3,1), (1,4,2), (1,5,2), (2,2,0), (2,4,1), (2,5,1), (3,3,0), (4,4,0) and (5,5,0).

SQL
CREATE TABLE category_closure (
ancestor int NOT NULL REFERENCES category,
descendant int NOT NULL REFERENCES category,
depth int NOT NULL,
PRIMARY KEY (ancestor, descendant)
);
CREATE INDEX ON category_closure (descendant, depth);
SELECT descendant FROM category_closure WHERE ancestor = 2; -- 2, 4, 5
SELECT ancestor FROM category_closure WHERE descendant = 4 ORDER BY depth DESC; -- 1, 2, 4
-- Adding a leaf 6 under Android (4): one row per ancestor of 4, plus itself
INSERT INTO category_closure (ancestor, descendant, depth)
SELECT ancestor, 6, depth + 1 FROM category_closure WHERE descendant = 4
UNION ALL SELECT 6, 6, 0; -- 4 rows
Four tree models for 200,000 nodes
ModelSubtree readAdd a leafMove a branchExtra storage
Adjacency listRecursive CTE, one step per level1 row1 rowNone
Materialised path / ltreeOne indexed prefix or <@ query1 rowRewrite every node in branchOne path per node
Nested setsOne range queryRenumber about half the treeRenumber large rangesTwo ints per node
Closure tableOne indexed joinOne row per ancestorDelete and insert many pairsAbout 1.4M rows

Reads are plain indexed joins on any engine, with no extension. Storage grows with depth: each node has one row per ancestor, so 200,000 nodes at an average depth of 6 is about 1.4 million rows, small for PostgreSQL. A move deletes the pairs that link the branch to its old ancestors and inserts pairs to the new ones, which for a 20,000-node branch can mean hundreds of thousands of rows; again acceptable a few times a day.

6Choosing for This Workload

With hot reads and a few writes a day, the decision is between ltree and a closure table, with nested sets ruled out by its write behaviour and the plain adjacency list too slow on the hot path. If we are on PostgreSQL and comfortable with an extension, ltree is the smallest change: one column, one index. If we want something portable or need depth-limited queries (children within two levels), the closure table is very flexible.

In both cases I would keep parent_id as the source of truth. The path or the closure rows are derived data, maintained in the same transaction as the parent_id change, either by a trigger or by the one service method allowed to change the tree, and a nightly job can rebuild them from parent_id and compare, so drift is caught.

There is also a simpler option that is often the best one. 200,000 categories at roughly 200 bytes each is about 40 MB, which fits easily in each application instance's memory. The service can load the tree at startup into a map from id to node with child lists, answer every breadcrumb and subtree question in microseconds, and reload when a change event arrives, a few times a day. The database then only needs the adjacency list.

7Follow-up questions

How would you keep the closure table in sync?

I would allow tree changes only through one service method, which updates parent_id and the closure rows in the same transaction, and lock the moved node's row so two moves of the same branch cannot interleave. A database trigger can do the same job and protects against writes that bypass the service. Either way, a periodic rebuild from parent_id into a scratch table and a comparison catches any drift.

What about the in-memory cache when there are 30 application instances?

Each instance holds its own copy and listens for a 'tree changed' event, through Kafka, Redis pub/sub or a PostgreSQL LISTEN/NOTIFY channel, and reloads. For a few changes a day, a short window where instances disagree is usually acceptable for a menu. If not, we can version the tree and include the version in cache keys.

When is the plain adjacency list enough?

When the tree is small or shallow and reads are not on the hot path, such as an admin screen, or when we cache the tree anyway. It is also the right model for trees with heavy concurrent writes, such as comment threads, where any derived structure would cost more to maintain than it saves.

8Conclusion

In this answer, we compared four tree models for a 200,000-node category tree that is read on every page and edited a few times a day. The adjacency list is simplest to write but needs recursion to read, ltree and materialised paths give indexed subtree reads at the cost of rewriting paths on moves, nested sets read fast but renumber the tree on every insert, and a closure table makes reads plain joins at the cost of more rows. For this workload, a closure table or ltree on top of parent_id as the source of truth fits well, and an in-memory cache of the whole tree is often simpler still.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd compare them by read and write cost for this workload, which is very read-heavy with a few writes a day. The adjacency list with parent_id is simplest and can't drift, but every subtree read is a recursive CTE with one iteration per level, which I don't want on every page.

Then, if they want more

Materialised path, or ltree in PostgreSQL, stores the path on each node, so descendants and ancestors are one indexed query with a GiST index, but moving a branch rewrites the path of every descendant. Nested sets give very fast range reads, but inserting a leaf renumbers about half the tree, so they're a poor fit for any concurrent writes.

A closure table stores every ancestor-descendant pair, around 1.4 million rows here; reads are simple indexed joins on any engine, and writes insert one row per ancestor, with moves touching many rows.

Given a few changes a day, I'd keep parent_id as the source of truth and add either ltree or a closure table maintained in the same transaction, with a periodic rebuild to catch drift. Honestly, at 200,000 nodes I'd also consider caching the whole tree in memory, about 40 MB, and reloading it on change events.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A product category tree with 200,000 nodes is read on every page and updated a few times...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/7caecce033/