Live Comment Thread with Instant Local Posting and Reconciliation
System DesignModel answerLast updated
Design a live comment feature where new posts show up instantly on the author's screen, then reconcile safely with server acknowledgments, broadcast events, retries, and durable storage.
You are building the comment section for a page where many people read and discuss at once, such as a live event page or a shared document. Comments from other people should appear in near real time.
A key requirement is that the author's own comment shows up in the list the moment they hit submit, so they can keep scrolling, typing, or reacting while the network request is still in flight.
Design the full system, covering the client, the API, the real-time channel, and storage.
What to cover
- How a locally rendered, not-yet-confirmed comment is identified, and how that identity is later replaced by the server's identity.
- How the write path avoids duplicate comments when requests are retried or time out with an unknown outcome.
- How the server's response and the live broadcast event for the same comment are merged without showing it twice.
- How comments are ordered, and what happens to a pending comment's position when the server assigns the final order.
- What the user sees for pending, failed, and retrying comments, and what actions they have.
- How history is stored durably and how a client that reconnects or opens a second device catches up.
Assumptions
- A pending comment on screen does not mean the server accepted it. The UI must treat it as provisional.
- Decide and state your position on edits and deletes, ordering guarantees, and delivery guarantees (at-most-once, at-least-once, exactly-once effect).
- Give rough scale numbers and say how they influence your choices.
Treat the points below as clarifying questions you should answer or assume explicitly: can comments be edited or deleted, how are they ordered, what should happen after a timeout where the commit outcome is unknown, and must a second device see the same conversation?
Hints
Hint 1
Give every comment two identities: a client-generated ID created at submit time and a server-assigned ID and sequence. Think about which one the retry key should be.
Hint 2
Assume the same comment can arrive twice on the client, once in the HTTP response and once through the live event, in either order. What single rule makes both paths safe?
Hint 3
Separate display order from commit order. Ask what a reconnecting client needs to send, such as a last-seen cursor, to fetch exactly what it missed.
Hint 4
Model the pending comment as a small state machine (sending, confirmed, failed, retrying) and decide which transitions are legal after a timeout.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Scale: a thread may have up to ~50k concurrent viewers, ~100 new comments per second at peak on the hottest thread, and millions of threads overall. Reads and fan-out dominate writes by orders of magnitude.
- Comments are append-only at first. Edits and deletes are supported as later events (an edit or tombstone event), not in-place rewrites, so the same sync mechanism handles them.
- Ordering: a single per-thread total order assigned by the server. Delivery is at-least-once, and the client deduplicates, giving an exactly-once effect.
- A second device must see the same thread, so the server is the source of truth, not local state.
Identities
Each comment has:
clientId: a UUID generated on the client at submit time. It is also the idempotency key.idandseq: assigned by the server on commit.seqis a monotonically increasing per-thread integer.
The pending comment renders immediately with clientId, a status = sending flag, and the author's local timestamp.
Write path
- Client appends the pending comment to local state and sends
POST /threads/{t}/commentswith{clientId, body}. - The server validates (auth, length, rate limit, moderation hook) and performs an idempotent insert. A unique constraint on
(thread_id, client_id)guarantees that a retry returns the existing row instead of creating a second one. - Within the same transaction it allocates
seq(a per-thread counter row or a sequence/partition offset) and writes the comment. An outbox row or a log append publishes the "comment created" event. - The response returns
{id, seq, createdAt, clientId}.
Because of the unique key, the client can retry any number of times safely. This is the answer to the unknown-outcome timeout: the client does not need to know whether the first attempt committed, it just retries with the same clientId.
Reconciliation of response and event
The comment may reach the client by response, by live event, or both, in either order. One rule handles every case: the local store is keyed by clientId, and any incoming message with a known clientId upgrades the existing entry rather than inserting a new one.
- Response first: mark confirmed, attach
idandseq. The later event finds the entry already confirmed and is a no-op. - Event first: the event carries
clientId, so the pending entry is upgraded. The response then becomes a no-op. - Comments from other users have no local entry, so they insert, keyed by
id.
Apply updates idempotently (merge by max seq, never downgrade a confirmed entry to pending).
Ordering
Confirmed comments sort by seq. Pending comments render at the bottom, in submit order, below all confirmed ones. When a pending comment is confirmed, it moves to its seq position. Usually that is the end, but if other people's comments committed first it may land slightly above. To avoid jarring jumps, animate the move or keep the author's view stable by only reordering when the item is off-screen or very close to the bottom. Never use client clocks for ordering.
Pending and failure states
State machine per local comment: sending → confirmed, sending → retrying → confirmed, retrying → failed, failed → sending (manual retry).
- Automatic retries use exponential backoff with jitter, a small cap (for example 3 to 5 attempts over ~30 seconds), and the same
clientId. - Definitive rejections (400, 403, moderation block) go straight to
failedwith a reason, with no retry. - A failed comment stays visible with a clear marker and "Retry" and "Delete" actions. Keep the draft text so the user never loses it.
- If the user closes the tab with unsent items, persist the outbox in IndexedDB or local storage and resume on next load. The same
clientIdmakes resuming safe.
Real-time delivery
- Clients hold a WebSocket or SSE connection to a gateway tier. Gateways subscribe to a per-thread topic on a pub/sub or log system (Kafka, Redis streams, NATS).
- The write service publishes after commit (via outbox, so a crash cannot commit without publishing). Gateways fan out to connected clients of that thread.
- For very hot threads, shard fan-out across gateways and batch events (for example every 100 ms) to cut message count.
- Events are at-least-once. Clients dedupe by
idandclientId.
Durable history and catch-up
- Storage: comments table partitioned by
thread_id, clustered byseq. A wide-column store or sharded SQL both work. Primary key(thread_id, seq), unique index on(thread_id, client_id). - Initial load:
GET /threads/{t}/comments?limit=50returns the latest page plus the highestseq. Older pages are fetched withbefore_seq. - Reconnect or second device: the client sends
after_seq = lastSeenSeq. The server replays the gap from storage, then the client switches to live events. If the gap is detected (eventseqjumps), the client refetches the range instead of trusting the stream. - Edits and deletes are new events with their own
seqthat reference the target comment, so a replay produces the same final state.
Trade-offs
- Per-thread sequence gives a simple total order but makes one thread a serialization point. At ~100 writes/s this is fine. Beyond that, use a partitioned log where the partition is the thread.
- Unique key on
clientIdcosts an index but removes whole classes of duplicate bugs. - Showing pending comments at the bottom is simple and honest. Inserting them at their guessed final position is nicer but risks visible reordering.
Common mistakes
- Using the server response as the only reconciliation path and then rendering a duplicate when the live event arrives.
- Generating the idempotency key per attempt instead of per comment, which defeats the purpose.
- Treating a timeout as failure and letting the user resubmit with a new ID, producing duplicates.
- Ordering by client timestamp.
- Dropping a failed comment from the UI and losing the user's text.
- Publishing the event before the database commit, so viewers see comments that later vanish.