patterntypescriptModerate
Live Commenting Systems Need Optimistic Insert with Reconciliation on Conflict
Viewed 0 times
live commentsoptimistic insertreconciliationtemp IDcomment orderingdeduplicationreal-time comments
Problem
In a live commenting system, a user submits a comment and it appears instantly (optimistic UI), but another user submitted a comment at the same time. After server confirmation, the comment order is wrong or duplicated.
Solution
Insert the optimistic comment with a client-generated temp ID. On server confirmation, reconcile by replacing the temp ID with the server ID. Re-sort comments by server-assigned timestamp, not insertion order.
type Comment = { id: string; text: string; authorId: string; createdAt: number; pending?: boolean };
async function postComment(text: string) {
const tempId = `temp:${crypto.randomUUID()}`;
const optimistic: Comment = {
id: tempId, text, authorId: me.id,
createdAt: Date.now(), pending: true
};
setComments(prev => sortByTime([...prev, optimistic]));
const confirmed = await api.createComment(text);
setComments(prev =>
sortByTime(prev.map(c => c.id === tempId ? { ...confirmed, pending: false } : c))
);
}
function sortByTime(comments: Comment[]): Comment[] {
return [...comments].sort((a, b) => a.createdAt - b.createdAt);
}Why
Server-assigned IDs and timestamps are the canonical order. Client clocks drift and optimistic inserts happen before the server processes the comment, so client-side ordering by insertion time diverges from server truth.
Gotchas
- De-duplicate comments when a WebSocket broadcast delivers the same comment the current user just submitted.
- Check incoming WebSocket comments: if id is already in local state (matched by temp ID via idempotency key), skip.
- Add an idempotency key to the POST request so server-side duplicates are prevented on retry.
- Pending comments should not be deletable or quotable until confirmed — disable those interactions.
Revisions (0)
No revisions yet.