Design the front end of a collaborative document editor like Google Docs.
Several people open the same document in their browsers and edit it at the same time. Everyone sees the others' changes within a fraction of a second, along with their cursors and selections. The document supports rich text (headings, bold/italic, lists, links, images, tables) and comments anchored to ranges of text.
The interviewer adds:
Focus on the client: the editor model, how concurrent edits are merged, the sync protocol, presence, offline behaviour, and how you keep typing fast in a huge document. Treat the storage backend as something you can shape the API of, not something you must build.
A collaborative editor is two hard problems glued together: a rich-text editor (a structured document, a selection model, input handling) and a replicated data structure (many replicas editing concurrently and converging). Interviewers want to see that you know which decisions belong to which half, and that you can pick a concurrency strategy and defend it.
| Concern | Target |
|---|---|
| Local keystroke latency | input to paint < 16 ms p95 (one frame) regardless of network |
| Remote propagation | p50 < 150 ms, p95 < 500 ms between two clients in the same region |
| Document size | 100+ pages (~300k characters, a few thousand blocks); open in < 2 s on a mid-range laptop |
| Concurrency | 50 editors, 500 viewers on one doc |
| Convergence | all replicas reach the identical document once they have seen the same set of operations |
| Durability | an acknowledged edit survives a server crash; an unacknowledged one survives a tab crash (IndexedDB) |
| Accessibility | editable region usable with screen readers (NVDA, JAWS, VoiceOver), keyboard-only, IME input |
Assume: central server available, offline for up to a day, desktop + tablet browsers, no E2EE, React app shell.
Everything else depends on this, so state the decision up front.
Operational Transformation (OT). Each edit is an operation such as insert(pos=42, "x"). When two operations
are concurrent, a transform function rewrites one against the other so positions stay correct. Production OT
(Google Docs, early Etherpad, ShareDB) relies on a central server that defines a total order: the client sends
one batch at a time, the server transforms it against anything committed since the client's base version, assigns a
version number and broadcasts. The client keeps an in-flight batch and a pending buffer and transforms incoming
remote ops against both.
CRDTs (Conflict-free Replicated Data Types). Each character (or run of characters) gets a unique, immutable ID
(clientId, clock) and is placed relative to its neighbours' IDs, not by index. Merging is commutative,
associative and idempotent, so updates can arrive in any order, be duplicated, or flow peer-to-peer and replicas
still converge.
y-prosemirror, y-codemirror, Lexical, Tiptap), an awareness
protocol for presence, and providers for WebSocket, WebRTC and IndexedDB.Decision. For a new build in 2025 with day-long offline, I would choose a CRDT (Yjs) bound to a model-based editor (ProseMirror via Tiptap, or Lexical), with a central server acting as relay, persistence and permission gate. I would say clearly that OT with a central server is equally valid when offline is short and the team already owns a proven OT engine; Google Docs works this way.
| Component | Responsibility |
|---|---|
| App shell | routing, auth, document list, toolbar, sharing dialog (React) |
| Editor view | renders the document model to a contenteditable DOM, maps DOM selection to model positions, handles beforeinput, IME composition, paste |
| Document model | schema-validated tree (ProseMirror Node/Lexical nodes), the editor's source of truth for rendering |
| CRDT binding | two-way sync between the editor model and the shared Y.XmlFragment; converts local transactions to CRDT ops and remote CRDT events to editor transactions |
| Sync provider | WebSocket connection, sync handshake, batching, reconnect with backoff, auth refresh |
| Persistence provider | stores CRDT updates in IndexedDB; loads the local copy before the network responds |
| Awareness/presence | ephemeral state per client: user, colour, cursor anchor/head as CRDT relative positions |
| Comments store | comment threads (server REST/GraphQL) + anchors stored as relative positions or as marks in the CRDT |
| Undo manager | scoped to local origin so it only reverts my changes |
| History panel | lists snapshots, renders diffs, triggers restore |
beforeinput (insertText). The editor view prevents default where needed and creates a model
transaction; the view updates the DOM synchronously. The user sees the character in the same frame.Y.Doc with origin local.update (a few dozen bytes). The persistence provider appends it to IndexedDB; the sync provider
batches updates for ~20–50 ms and sends them.Y.Doc; the binding translates the resulting events into an editor
transaction tagged remote (excluded from the local undo stack) and the view patches the DOM.// The Y.Doc is the replicated source of truth.
type SharedDoc = {
content: Y.XmlFragment; // the rich-text tree: paragraphs, headings, lists, tables
meta: Y.Map<unknown>; // title, page setup, default styles
commentAnchors: Y.Map<AnchorRef>; // commentId -> relative range (see below)
};
type AnchorRef = {
start: Uint8Array; // encoded Y.RelativePosition
end: Uint8Array;
};
Relative positions are the key idea for anything that must "stick" to text (cursors, comments): instead of an index that shifts with every edit, store the ID of the character the position is attached to. Converting back to an absolute index happens at render time.
// ProseMirror-like schema, simplified
type BlockNode =
| { type: 'paragraph'; attrs: { align?: 'left' | 'center' | 'right' }; content: InlineNode[] }
| { type: 'heading'; attrs: { level: 1 | 2 | 3 }; content: InlineNode[] }
| { type: 'bulletList' | 'orderedList'; content: ListItem[] }
| { type: 'table'; content: TableRow[] }
| { type: 'image'; attrs: { src: string; alt: string; width?: number } };
type InlineNode = { type: 'text'; text: string; marks: Mark[] };
type Mark =
| { type: 'bold' | 'italic' | 'underline' | 'code' }
| { type: 'link'; attrs: { href: string } }
| { type: 'comment'; attrs: { id: string } };
type AwarenessState = {
user: { id: string; name: string; color: string; avatarUrl?: string };
cursor: { anchor: Uint8Array; head: Uint8Array } | null; // relative positions
lastActiveAt: number;
};
type CommentThread = {
id: string;
docId: string;
resolved: boolean;
comments: { id: string; authorId: string; body: string; createdAt: string }[];
};
type Snapshot = {
id: string;
docId: string;
createdAt: string;
label?: string; // "Final draft"
stateVector: Uint8Array; // Yjs state vector at that point
authors: string[];
};
Where each lives: the Y.Doc in memory plus IndexedDB; awareness only in memory (never persisted); comments and
snapshot metadata in a server cache (TanStack Query or similar); UI state (open panels, toolbar state) in React
state. The editor model is derived from the Y.Doc and must never be edited directly by app code.
GET /api/docs/:docId -> { id, title, role: "editor", createdAt, ownerId }
GET /api/docs/:docId/snapshots?cursor=... -> { items: Snapshot[], nextCursor }
POST /api/docs/:docId/snapshots { label } -> Snapshot
POST /api/docs/:docId/restore { snapshotId } -> 202
GET /api/docs/:docId/comments -> { threads: CommentThread[] }
POST /api/docs/:docId/comments { anchor, body } -> CommentThread
POST /api/docs/:docId/collab-token -> { token, expiresAt, wsUrl }
The collab token is short-lived and scoped to one document and role, so the WebSocket gateway can authorise without a database round trip.
type ClientMessage =
| { t: 'sync-step-1'; stateVector: Uint8Array } // "here is what I have"
| { t: 'sync-step-2'; update: Uint8Array } // "here is what you are missing"
| { t: 'update'; update: Uint8Array; clientSeq: number }
| { t: 'awareness'; update: Uint8Array }
| { t: 'ping' };
type ServerMessage =
| { t: 'sync-step-1'; stateVector: Uint8Array }
| { t: 'sync-step-2'; update: Uint8Array }
| { t: 'update'; update: Uint8Array; origin: string }
| { t: 'ack'; clientSeq: number } // persisted durably
| { t: 'awareness'; update: Uint8Array }
| { t: 'error'; code: 'FORBIDDEN' | 'DOC_TOO_LARGE' | 'TOKEN_EXPIRED'; message: string };
On connect, both sides exchange state vectors and send each other only the missing updates. This is the whole
reconnect story for a CRDT: no special "replay" logic, because applying an update twice is a no-op. The ack lets
the client mark local updates as durable, which drives the "All changes saved" indicator.
A viewer's connection is receive-only: the gateway drops update messages from viewers and commenters (commenters
may update commentAnchors only, which the gateway checks by decoding the update and inspecting which shared types it
touches).
interface CollaborativeEditorProps {
docId: string;
role: 'viewer' | 'commenter' | 'editor' | 'owner';
user: { id: string; name: string; color: string };
onSaveStateChange?: (s: 'saved' | 'saving' | 'offline' | 'error') => void;
onSelectionChange?: (sel: { from: number; to: number; marks: string[] }) => void;
extensions?: EditorExtension[]; // tables, mentions, embeds, slash commands
}
Raw contenteditable plus document.execCommand produces inconsistent HTML across browsers and offers no reliable
model to sync. Modern editors (ProseMirror, Lexical, Slate) keep a schema-validated model, treat the DOM as a
render target, and use beforeinput events (Input Events Level 2) to translate intent (insertText,
deleteContentBackward, insertFromPaste) into model transactions. They still rely on contenteditable because it
gives native caret, selection, spellcheck, IME and accessibility for free. The hard part is reconciling when the
browser mutates the DOM anyway (IME composition on Android, autocorrect, spellcheck replacements): editors use a
MutationObserver to read the change back into the model. A lead candidate mentions that remote updates must
not be applied mid-composition in a way that destroys the composing text node; buffer remote transactions until
compositionend or map around the composition range.
Google Docs went further and renders to its own layout engine (moving towards canvas) to get exact pagination; that is a huge investment justified only for page-faithful layout. For most products, a DOM-based model editor is right.
format on Y.Text, or
ProseMirror marks mapped to XML attributes) the result is the union. Peritext-style spans define whether text typed
at a mark's boundary inherits it (bold should expand at the end; links should not).content-visibility: auto with contain-intrinsic-size on block
containers, which skips layout and paint while keeping the DOM present.mergeUpdates); throttle awareness
updates to ~10/s.y-indexeddb) before or concurrently with sending. On reload, the local
state renders immediately and the sync handshake fills the gap.navigator.storage.persist()) for heavy users so the browser does not evict the data.beforeunload only if
there are updates neither acked nor persisted locally.BroadcastChannel so tabs of the same doc share updates locally and one tab can hold the
socket (or each tab connects; the CRDT tolerates duplicates).A global undo would revert collaborators' work. Use a per-client undo manager that tracks only transactions with
origin local (Yjs UndoManager with trackedOrigins). Undoing an insert that a collaborator has since edited
around still works because the CRDT reverts by item ID, not position. Group keystrokes into undo steps by time
(~500 ms) and by word boundaries.
href protocols (http, https, mailto) to block javascript: URLs.h1–h3, ul/ol, table) inside a contenteditable
region with role="textbox" and aria-multiline="true" and an accessible name.aria-live region, rate-limited so it does not
chatter.aria-hidden; provide a "collaborators" panel that lists who is where in text form.docId on the gateway, document size limits, and a
degradation plan when the gateway is down (local editing continues; banner explains).Why not just lock paragraphs so only one person edits each? Locking is simpler but hurts UX: people collide in the same paragraph constantly (titles, tables). It also fails offline. Locking is fine for coarse objects such as a slide or a form field, not for text.
How do you add suggestion mode (track changes)? Store suggestions as marks (insertion, deletion with author
and id) instead of applying the change; accept = remove the mark (or delete the text), reject = the inverse. Both
are ordinary edits, so they sync like everything else.
What happens if two users paste 10,000 words at the same spot? CRDT ordering is deterministic by client ID, so the two blocks appear one after the other, never interleaved character by character (YATA and RGA keep runs from the same client together).
How would end-to-end encryption change the design? The server can no longer transform or validate content. CRDTs fit: the server stores and relays encrypted updates; clients merge after decrypting. You lose server-side search, previews and validation.
How big does a Yjs document get? Roughly proportional to content plus small per-run metadata; with GC on, deletions cost a few bytes per deleted range. Disabling GC for history grows it with every deleted character, which is why history is often kept server-side.
Can React render the document? It can (Lexical renders via its own reconciler, not React), but a React re-render per keystroke over thousands of nodes is too slow. Let the editor library own the DOM and expose node views for custom React components (embeds, mentions).
Spotted a mistake or a rights concern? Report an issue