Comment threads add conversational context, but the data model and interface need rules for depth, visibility, and moderation. Without those rules, one deeply nested reply can make a discussion impossible to read or moderate.
Choose a thread model deliberately
A simple adjacency model stores a nullable
parentIdEnforce that a reply’s parent belongs to the same article or discussion. Prevent self-parenting and cycles, and define a maximum depth if the UI cannot present arbitrary nesting. Use a transaction for creating a comment and updating derived counters. Keep deletion semantics explicit: hard delete, tombstone, or hidden content each affects reply context differently.
Treat comments as untrusted
Validate lengths and rate limits, escape or safely render text, and provide report and moderation flows. Authorization checks should cover both the comment and its parent resource. A deleted account or removed parent should not expose private content through a reply endpoint.
For the interface, indent only a few levels and then flatten visual depth while retaining reply context. Use clear labels and keyboard-accessible actions. Test concurrent replies, deleted parents, pagination, moderation, and permission changes. The thread should preserve useful context without making every comment a permanent public record.
Keep reply ownership inside the write
A reply can reference an existing comment and still be invalid for the requested article. Before inserting, compare the parent comment's article ID with the authorized article being written to. If comment deletion and writes can race, use a foreign key and choose a transaction or constraint design that preserves the invariants when those operations overlap. PostgreSQL foreign keys
For reads, paginate root comments by a stable ordering such as a creation timestamp plus a unique ID. Load bounded replies when the user opens a thread, maintaining the same article predicate. Test a thread with a hidden parent and visible replies so the product decides whether readers see a tombstone or a hidden branch. Check the root and reply queries with EXPLAIN on representative rows before adding an index that only fits a tiny fixture. PostgreSQL EXPLAIN
Worked example
Bind blog_id through your database client after authorizing access to the article. Fetch replies separately; before insertion verify the parent belongs to this same article.
sqlSELECT id, content, "parentId" FROM "Comment" WHERE "blogId" = :blog_id AND "parentId" IS NULL AND "deletedAt" IS NULL ORDER BY "createdAt", id LIMIT 20;




Community
Discussion
Loading comments…