Build a Post Comment Thread with Reliable Alerts
System DesignModel answerLast updated
Design the comment feature for an existing social app: APIs, schema, pagination, durable notification fan-out, and how to scale reads and writes when one post goes viral.
You are adding a comment feature to a social app that has fewer than one million users. Login, user accounts, and posts already exist and should be reused as they are. Your job is to design the comment thread under a post and the alerts it triggers.
Cover these three areas.
1. APIs and storage
- Define how clients create, list, edit, and delete comments.
- Describe the data model: identifiers, links to post and author, reply structure, timestamps, and edit/delete state.
- Explain authorization and how pagination stays stable while new comments arrive.
- Explain how a client retry of a create request avoids producing a duplicate.
2. Notifications
- Say who gets notified (post author, parent-comment author, mentioned users) and how duplicates and user preferences are handled.
- Show how a committed comment leads to notifications without the comment write depending on every downstream channel (push, email).
- Explain how you recover if the system fails between committing the comment and publishing the event.
3. Scaling
- Explain where you would add capacity for reads and writes.
- Describe how you would handle one post that suddenly receives heavy traffic.
- List the metrics you would use to tell an application bottleneck from a database bottleneck or a notification backlog.
Request rates, traffic distribution, and latency targets are not given, so state your own assumptions and numbers. Before finalizing the schema, say which product questions you would clarify (reply depth, what deleting a parent does, ordering, who is notified).
Hints
Hint 1
Pick answers to the product questions first (for example one level of replies, tombstones for deleted parents, chronological order) because the schema and indexes follow from them.
Hint 2
Use keyset (cursor) pagination on (post_id, created_at, id) rather than OFFSET, and give create requests a client-supplied idempotency key with a unique constraint.
Hint 3
Write the comment and an outbox row in the same transaction; a separate worker publishes events and creates notification rows, so a crash between commit and publish loses nothing.
Hint 4
Do a quick capacity estimate: even a generous assumption gives a few hundred writes per second at peak, so one primary database plus caching and replicas is likely enough. Focus on hot-post behavior and the metrics that locate the bottleneck.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify and assume
I would settle these first, because they shape the schema:
- Replies: one level deep. Deeper nesting is rarely worth the query and UI cost, and a reply to a reply can simply attach to the top-level parent with an optional "replying to" user.
- Deletion: soft delete. If a parent is deleted but has replies, keep a tombstone ("comment removed") so the thread stays coherent. Childless deleted comments can be hidden.
- Ordering: chronological by default (oldest or newest first); "top" ordering can come later.
- Notified: post author, parent-comment author, and mentioned users, never the actor themselves, and each person at most once per comment.
Capacity assumptions: 1M users, ~10% daily active, so 100k DAU. Say each views 20 posts a day with comments and writes 0.5 comments a day. That is about 2M comment-list reads a day (~25/s average, ~250/s peak) and 50k writes a day (~1/s average, ~10–30/s peak). This is small for a single relational primary. The hard part is correctness and hot posts, not raw volume.
Part 1: APIs and storage
Table comments: id (bigint or ULID, time-sortable), post_id, author_id, parent_id (null for top-level), body, created_at, edited_at, deleted_at, client_request_id.
Indexes:
(post_id, parent_id, created_at, id)serves top-level listing and replies.- Unique
(author_id, client_request_id)gives idempotent creation. (parent_id, created_at, id)for reply lists.
Endpoints:
POST /posts/{id}/commentswithbody, optionalparent_id, and an idempotency key. On a unique-key conflict, return the existing comment with 200 instead of creating another.GET /posts/{id}/comments?cursor=&limit=returns top-level comments with a reply count and the first few replies.GET /comments/{id}/replies?cursor=loads more.PATCH /comments/{id}: only the author, setsedited_at.DELETE /comments/{id}: the author, the post owner, or a moderator. Soft delete, blank the body in responses.
Pagination: use a keyset cursor encoding (created_at, id) and query WHERE post_id=? AND (created_at,id) > (?,?) ORDER BY created_at,id LIMIT 50. OFFSET would skip or repeat items when comments are inserted mid-scroll and gets slower with depth. Cap limit so every query is bounded.
Authorization: reuse the existing auth middleware. Verify the post exists and is visible to the caller (blocks, private accounts), validate body length (e.g. 2,000 chars), and rate-limit per user.
Part 2: Notifications
Principle: the comment write must not depend on push or email providers. Use the transactional outbox pattern.
- In one DB transaction, insert the comment and an
outboxrow (event_type=comment_created,comment_id,status). - A relay worker polls unsent outbox rows (or tails the log), publishes them to a queue, and marks them sent. If the process dies after commit but before publishing, the row is still there and gets picked up on restart. Delivery is at-least-once, so consumers must be idempotent.
- A notification consumer resolves recipients (post author, parent author, mentions), removes the actor, dedups into a set, and checks preferences and mute/block settings.
- It inserts rows into
notifications(user_id,type,comment_id,read_at,created_at) with a unique key on(user_id, type, comment_id). Replayed events then become no-ops. This is the persisted state the in-app bell reads. - Separate delivery attempts (push/email) are tracked in a
deliveriestable or by the queue, with retries, exponential backoff, a dead-letter queue, and per-channel rate limits. A failing email provider delays emails but never touches the comment or the in-app notification.
Extras: batch or collapse ("5 people commented") for busy posts, and delete or ignore notifications when the comment is deleted.
Part 3: Scaling
Application tier: stateless servers behind a load balancer; add instances when CPU or latency rises. At this scale 2–3 instances for redundancy suffice.
Database: a single primary with one or two read replicas. Reads of comment lists go to replicas, but read-your-own-write (a user just posted) should hit the primary or merge the new comment client-side, because replicas lag.
Caching: cache the first page of comments per post (and counts) in Redis with a short TTL (5–30 s) or invalidate on write. Store comment counts as a denormalized column or cached counter instead of COUNT(*).
Hot post:
- Reads: the first-page cache absorbs most traffic; use request coalescing so one miss does not trigger a stampede.
- Writes: inserts into an indexed table are cheap, but updating a shared counter row on every comment creates lock contention. Increment the counter asynchronously or in batches, or in Redis with periodic flush.
- Notification fan-out: a viral post's author would receive thousands of notifications. Aggregate them rather than sending each one.
- Protect with rate limits and slow-mode if abuse occurs.
Metrics to find the bottleneck:
- App server: CPU, p95/p99 latency, error rate, thread/connection pool saturation. High app CPU with idle DB points to the servers.
- Database: query latency per statement, connections, lock waits, replica lag, buffer cache hit rate, slow query log. Slow queries with low app CPU point to a missing index or a hot row.
- Cache: hit ratio, evictions.
- Notifications: queue depth, oldest-message age, consumer lag, dead-letter count, per-provider error rate. Rising queue age with healthy comment latency means the backlog is downstream only.
Common mistakes
- Using OFFSET pagination.
- Publishing to a queue after commit without an outbox, losing events on a crash.
- Notifying the commenter themselves or notifying the same person twice.
- Calling
COUNT(*)per request or locking a counter row on each write. - Over-engineering (sharding, Kafka clusters) for under a million users.
- Not planning for retries: no idempotency on create or notification insert.
Later steps
If load grows: partition comments by post_id, move the queue to a managed log, and add relevance ranking with a precomputed score.