Skip to content

How to design nested comments (frontend)

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Asked at
  • ServiceNow
Practice this question

The problem

Comment threads beneath an article: replies nested to any depth, more of a long thread loaded on request, and posting, editing and deleting your own comments. The answer turns on two decisions. The client holds a single copy of each comment in a map keyed by id, and for each parent the ids of its children in order plus a paging cursor, so a branch five levels down can grow without touching the rest of the tree. And a reply someone posts appears in the thread at once, marked as posting, while the server catches up.

Clarifying questions

AskWhy it mattersA typical answer

Does the server send the thread already nested, or as pages of comments where each one names its parent?

It decides how the client stores the thread. A nested tree is easy to draw once but hard to add to later; a flat page with parent ids needs a small amount of client work and then pages anywhere.

Flat pages. GET /posts/{id}/comments returns a page of top-level comments with a cursor, each carrying its reply count, and GET /comments/{id}/replies pages the replies under one comment. The client builds the tree.

How deep can replies go, and is this read on phones?

Unlimited depth on a narrow screen runs out of room for indentation long before the thread runs out of replies, so the drawing needs a depth limit and somewhere for the rest to go.

Any depth, on phones and desktops. Beyond a chosen depth the client stops indenting and offers a link to the rest of the branch on a page of its own.

How large do threads get, and how fast must the page react?

The size tells you whether the whole thread can ever be drawn at once; the response budget tells you whether a reply can wait for the server before it shows.

Threads of 10,000 comments, 20 top-level comments in each page, and a click or keystroke answered within 200 milliseconds.

Do replies from other people need to appear while someone is reading?

Live arrivals change the data layer (a subscription) and the reading experience (content moving under the reader). It's a different design if it's in scope from the start.

Not in the first pass. Keep a place in the design for a notice that new replies are waiting, in case the question comes up later.

What happens to the replies under a comment that is deleted?

If a deleted comment vanishes, its replies lose their place in the tree. Keeping a placeholder changes the Comment entity and the delete flow.

They stay readable. The deleted comment remains as a placeholder with its body removed.

Who can edit or delete, and is moderation part of this?

Edit and delete for your own comments is a client flow; moderation, reporting and ranking are a different product surface.

People edit and delete their own comments. Moderation, reporting, ranking, mentions and rich text are out of scope.

The requirements menu

RequirementScopeWhy

Read the comments under a post, each reply shown under the comment it answers

Core

The thread is the product. Showing a reply under what it answers is what makes it nested rather than a flat list.

Reply to any comment, at any depth

Core

Replying at depth is what forces the per-parent child lists and the depth handling on a phone.

Load more top-level comments, and more replies under one comment, when asked

Core

Large threads are far bigger than one page can draw, so paging has to work at the top level and inside any branch.

Edit or delete your own comment

Core

Both change a comment that may already have replies under it, which is where the placeholder for a deleted comment comes from.

Collapse a branch to hide its replies, and open it again

Optional

Take it if time allows: it reuses the same show-and-hide control as loading replies, and it helps readers skip a sub-thread they're done with. Leave it if the core paging isn't finished.

Open a link to one comment deep in the thread

Optional

Take it if the interviewer asks about sharing a comment: the page must load the comment's ancestors first and scroll to it. It's a separate load path, so it can wait.

Show replies from other people as they arrive

Optional

Take it when asked. It adds a subscription and a notice so arrivals don't move the text under the reader. Leave it out of the first pass.

Show how many replies a comment has before they are loaded

Optional

Take it: the API already returns a reply count, and the button that loads replies needs a number to say how many are behind it.

Vote on comments

Out of scope

Votes bring their own optimistic update and their own ordering question. Say they'd follow the same posting pattern and move on.

A complete local copy of each thread, stored in the browser for offline reading

Out of scope

Storing whole threads on the device is a lot of machinery for a page that is usually read online. Mention it as a possible extension and leave it.

Moderation and reporting tools

Out of scope

A different product surface with its own permissions and screens.

Ranking which comments show first

Out of scope

Order comes from the server; the client draws whatever order the page arrives in.

Mentions and notifications

Out of scope

Both reach outside the thread into other people's inboxes; neither changes how the thread is drawn.

Rich text and images in comments

Out of scope

Rendering untrusted markup is its own question. Assume plain text bodies.

Non-functional requirements

RequirementWhat it forces

A posted reply shows within 200 milliseconds, before the server has answered

The reply is added to the local store at once with an id the client made, drawn as posting, and the request goes out after. The server's answer later confirms it or marks it failed. The 200 milliseconds is the Core Web Vitals threshold for a good Interaction to Next Paint, measured at the 75th percentile, so it covers painting the reply, not the round trip.

A thread of 10,000 comments is never drawn all at once

Top-level comments arrive 20 a page by cursor and replies load per parent on request. The top-level list draws the comments near the screen and nothing further, and one comment redraws when its own entry in the store changes rather than when any part of the thread changes.

Deleting a comment leaves the replies under it readable

A delete keeps the comment's node in the store with a deleted flag and an emptied body, so its child list stays attached and its replies keep their indentation and their parent.

Showing and hiding replies works by keyboard and is announced to screen readers

The control that loads or hides replies is a real button carrying aria-expanded, toggled by Enter and Space, and pointing at the list it controls, which is the disclosure pattern.

Estimates

QuantityWorkingResultWhat it sizes

Pages to fetch a whole large thread

10,000 comments / 20 top-level comments per page = 500 pages, if the thread were all top-level comments fetched through this API; a whole-thread fetch that includes replies would move that data into fewer, larger responses

About 500 requests, and the whole thread in memory, before the page is complete

Why no design here fetches and draws the whole thread. The first page is what a person reads first; the rest loads as they scroll.

Share of a large thread the first page shows

20 top-level comments / 10,000 comments = 0.2%

0.2% of the thread on the first load

The page's state is a small window onto the thread, so the store must cope with most of the tree being absent and arriving in any order.

Clicks to read a comment with 20 replies

6 replies shown before the rest are tucked away; 20 - 6 = 14 behind the button; at 5 a click that is three clicks (5, 5 and 4)

Three clicks, each a request for one parent's next page

The button's label is a subtraction, reply count minus children loaded, and it has to stay right as both numbers change.

Core entities

EntityWhat it holds

Comment

One comment as the server returns it, stored once however many lists point at it.

Client store

The thread as the client knows it: a map of comments and, per parent, an ordered child list with a cursor.

Pending comment

A reply the person has posted that the server has not yet accepted.

Thread view state

What the page is showing right now, apart from the data itself.

The API

EndpointNotes

GET /posts/{id}/comments?cursor&limit=20 → { comments, next_cursor }, each with its reply count

A page of top-level comments. Each comment names its parent (null here) and carries a reply count, so the thread can show how many replies wait behind each button before loading any.

GET /comments/{id}/replies?cursor&limit=5 → { comments, next_cursor }

A page of direct replies under one comment, with its own cursor. Any branch pages on its own, which is what lets a comment deep in the tree load more without refetching above it.

POST /comments { post_id, parent_id, client_id, body } → comment

client_id is made on the client and sent again on each retry, so the server can recognize a repeat and return the comment it already saved instead of making another. The returned comment carries the server id that replaces the client id in the store.

PATCH /comments/{id} { body } → comment

Edits the body. The client keeps the old body until the response arrives; on refusal it restores the old text and says so.

DELETE /comments/{id} → { id, deleted }

Marks the comment deleted. The client keeps the node, clears its body and shows a placeholder, so replies under it stay where they are.

The high-level design

nested threadServerTop-level listCommentcomponent

Step 1 of 4

The whole thread, nested, drawn by recursion

Start with the shortest path to a working page: the server returns the whole thread as nested objects, and a single recursive component renders a comment and calls itself for each child. It shows the data flow end to end, and it already has the two faults the rest of the design answers: the thread is drawn in full on open however big it is, and a page of replies loaded later for one branch has to be merged by rebuilding the path from the root to its parent.

flat pagesclient idPOSTpendingon clickdeepercursorServerData layerReply formPending repliesComments by idChildren byparent, cursorTop-level list,near screenNew replies noticeCommentcomponentChild commentsShow more repliesContinue threadlink
The whole design

What breaks first

The deep dives

How the thread is shaped and drawn. A comment five replies deep gets a new reply while its branch is half loaded, and the reader has just asked for more replies above it. How does your client hold the thread, and how does that reply get drawn in the right place?

A concept that helps here: Client caching and normalized storesA concept that helps here: Where state livesA concept that helps here: Pagination and infinite scroll

Posting a reply, and the server saying no. Someone writes a long reply on a train, presses post, the request times out, and a second try is refused. What do they see in the thread at each step, and what happens to their text?

A concept that helps here: Optimistic updates and rollbackA concept that helps here: Sync queues and client idempotencyA concept that helps here: Partial failure in the UI

A thread far longer than the page. An article goes viral and gathers ten thousand comments in an afternoon, many with long chains of replies. What does the page load and draw when someone opens it, and what happens as they read on?

A concept that helps here: List virtualizationA concept that helps here: Pagination and infinite scrollA concept that helps here: Accessible widgets

Concepts this guide uses

Sources

  1. techinterview.org: Build a comments thread, nested replies, pagination, optimistic updates
  2. Frontend Digest: Design a comments thread
  3. Hacker News API: items, parents and kids
  4. Redux docs: Normalizing state shape
  5. CSS-Tricks: Styling comment threads
  6. YouTube Data API: CommentThreads list
  7. Disqus blog: Introducing collapsed replies
  8. WAI-ARIA Authoring Practices Guide: Disclosure (show and hide) pattern
  9. web.dev: Web Vitals
  10. TanStack Query docs: Optimistic updates
  11. Stripe blog: Designing predictable APIs with idempotency keys
  12. TanStack Virtual docs: Introduction
  13. LogRocket blog: How to speed up long lists with TanStack Virtual
  14. React docs: memo
  15. JavaScriptBit: Frontend system design, nested comments
Sign in to report a mistake