Nov 23, 20266 min read

Threaded Comments in Postgres: Recursive CTEs vs ltree

How to store nested replies, load a whole thread in display order with one query, cap nesting depth and handle deleted parents, with a TypeScript comments service on Encore.

Illustration for Threaded Comments in Postgres: Recursive CTEs vs ltree

Flat comment lists are easy. Once replies can have replies, you need to load a thread of 400 comments in reading order, each reply under its parent, without one query per level or a tree built in application code.

Postgres has two built-in answers, a recursive query over parent_id and a materialized path with ltree. This guide compares them, covers a common ltree ordering bug and builds a comments service in TypeScript.

How do you model replies in a table?

Every approach starts with an adjacency list, a parent_id column that references the comment being replied to, with NULL for top-level comments. It is easy to insert, keeps referential integrity with a foreign key and maps directly to how users think about replies. What it does not give you is order: the database does not know that comment 57 belongs under comment 12, three levels down, unless something walks the tree.

How does a recursive CTE load a thread?

WITH RECURSIVE starts from the top-level comments and repeatedly joins children onto the rows found so far, building a sort key as it goes:

WITH RECURSIVE thread AS ( SELECT id, parent_id, body, 0 AS depth, ARRAY[id] AS sort_path FROM comments WHERE post_id = $1 AND parent_id IS NULL UNION ALL SELECT c.id, c.parent_id, c.body, t.depth + 1, t.sort_path || c.id FROM comments c JOIN thread t ON c.parent_id = t.id ) SELECT id, parent_id, body, depth FROM thread ORDER BY sort_path;

It needs no extra column and stays correct when comments move, which is why it is a good first version. Its cost grows with depth and thread size, since every level is another join step and the whole tree is rebuilt on each read, and paging through a large thread means computing all of it first.

How does ltree make reads cheaper?

The ltree extension adds a label path type such as 000000000012.000000000057, stored on each row when the comment is written. A thread is then WHERE post_id = $1 ORDER BY path, which a B-tree index on (post_id, path) returns in display order without recursion. Depth is nlevel(path) - 1, and a whole subtree is path <@ '000000000012', which a GiST index on path serves.

ltree compares labels as text, so 1.10 sorts before 1.9, a result we confirmed on Postgres 17, and replies show up out of order as soon as IDs reach two digits. Zero-pad each label to a fixed width when you build the path and the text order matches the numeric order.

Recursive CTEltree path
Extra columnNonepath
Load a threadRecursive query, rebuilt per readORDER BY path on an index
Subtree queryRecursive query from that nodepath <@ parent_path
Moving a commentUpdate one parent_idUpdate the path of the whole subtree

Comments are written once and read many times, and they almost never move, which is why the materialized path is the common choice for discussion threads.

How do you handle depth and deleted comments?

Cap nesting at a fixed depth, often 6 to 10 levels, since deeper threads are unreadable on a phone. A reply to a comment at the cap attaches to that comment's parent instead. When a user deletes a comment that has replies, keep the row, clear the body and show a placeholder, because removing it would orphan the replies or delete other people's words with it.

Threaded comments with Encore

Encore

Encore is a backend framework with built-in infrastructure, which keeps the comments table, the ltree extension and the endpoints in one TypeScript service. The Postgres database enables ltree in its migration, the extension is part of the Encore Postgres image used locally, and request validation comes from the endpoint's types.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- comments/migrations/1_create_comments.up.sql CREATE EXTENSION IF NOT EXISTS ltree; CREATE TABLE comments ( id BIGSERIAL PRIMARY KEY, post_id BIGINT NOT NULL, parent_id BIGINT REFERENCES comments (id), author_id TEXT NOT NULL, body TEXT, path LTREE NOT NULL, deleted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX comments_post_path ON comments (post_id, path); CREATE INDEX comments_path_gist ON comments USING gist (path);
// comments/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("comments");
// comments/comments.ts import { api, APIError } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { MinLen, MaxLen } from "encore.dev/validate"; const db = new SQLDatabase("comments", { migrations: "./migrations" }); const MAX_DEPTH = 8; const label = (id: number) => String(id).padStart(12, "0"); interface AddCommentParams { postId: number; parentId?: number; body: string & MinLen<1> & MaxLen<10000>; } interface Comment { id: number; parentId: number | null; authorId: string; body: string | null; depth: number; createdAt: Date; } export const add = api( { expose: true, auth: true, method: "POST", path: "/posts/:postId/comments" }, async (p: AddCommentParams): Promise<{ id: number }> => { await using tx = await db.begin(); let parentId: number | null = null; let parentPath = ""; if (p.parentId !== undefined) { const parent = await tx.queryRow<{ id: number; parent_id: number | null; path: string; depth: number }>` SELECT id, parent_id, path::text AS path, nlevel(path) - 1 AS depth FROM comments WHERE id = ${p.parentId} AND post_id = ${p.postId}`; if (!parent) throw APIError.notFound("parent comment not found"); // At the depth cap, attach the reply next to the parent instead of under it. const atCap = parent.depth >= MAX_DEPTH - 1 && parent.parent_id !== null; parentId = atCap ? parent.parent_id : parent.id; parentPath = atCap ? parent.path.split(".").slice(0, -1).join(".") : parent.path; } const next = await tx.queryRow<{ id: number }>` SELECT nextval(pg_get_serial_sequence('comments', 'id'))::int8 AS id`; const id = next!.id; const path = parentPath ? `${parentPath}.${label(id)}` : label(id); const authorId = getAuthData()!.userID; // the signed-in user, never the request body await tx.exec` INSERT INTO comments (id, post_id, parent_id, author_id, body, path) VALUES (${id}, ${p.postId}, ${parentId}, ${authorId}, ${p.body}, ${path}::ltree)`; await tx.commit(); return { id }; }, ); export const thread = api( { expose: true, method: "GET", path: "/posts/:postId/comments" }, async ({ postId }: { postId: number }): Promise<{ comments: Comment[] }> => { const comments = await db.queryAll<Comment>` SELECT id, parent_id AS "parentId", author_id AS "authorId", CASE WHEN deleted_at IS NULL THEN body END AS body, nlevel(path) - 1 AS depth, created_at AS "createdAt" FROM comments WHERE post_id = ${postId} ORDER BY path LIMIT 1000`; return { comments }; }, ); export const remove = api( { expose: true, auth: true, method: "DELETE", path: "/comments/:id" }, async ({ id }: { id: number }): Promise<void> => { // Keep the row so replies stay attached; the thread shows a placeholder. // Only the author matches; add a moderator check here if moderators can delete. await db.exec` UPDATE comments SET deleted_at = now(), body = NULL WHERE id = ${id} AND author_id = ${getAuthData()!.userID}`; }, );

encore run starts Postgres locally with ltree available and applies the migration, so you can post a dozen nested replies and check that /posts/1/comments returns them in reading order, with each query visible in the local trace. The ID comes from the table's own sequence through nextval before the insert, so the path label always matches the row's primary key. Both write endpoints require a signed-in user: the author comes from the auth handler rather than the request body, and remove only matches the caller's own comments.

An agent that adds reactions or edit history to this service can change the schema and the thread query together, then seed a deep thread locally and confirm the order did not break.

Best fit: Apps with discussions, reviews or support threads that want nested replies served from their own Postgres database in one indexed query.

Frequently asked questions

How do you store nested comments in Postgres?

Give each comment a parent_id that points to the comment it replies to. To read a thread in display order, either walk the tree with a WITH RECURSIVE query or also store a materialized path, for example with the ltree extension, and ORDER BY that path.

Should I use a recursive CTE or ltree for comments?

A recursive CTE needs no extra column and is fine for small threads. ltree stores the full path on each row, so loading a thread is a single indexed ORDER BY path and subtree queries use the <@ operator, which pays off once threads get long or are read far more than written.

Why are my ltree comments in the wrong order?

ltree compares labels as text, so a path ending in 10 sorts before one ending in 9. Zero-pad the numeric labels to a fixed width, such as 12 digits, when you build the path.

How do I build threaded comments with Encore?

Enable ltree in a migration for an Encore Postgres database, store parent_id and a zero-padded path on each comment, and read a thread with ORDER BY path from a TypeScript endpoint. encore run starts Postgres locally with ltree available.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders