Design a Collaborative Editor – Frontend System Design

We’ll walk through the frontend system design for a collaborative document editor like Google Docs. Our goal is to design an editor surface where typing feels local, remote edits land without jumping the caret, and other people show up as live cursors — even when two people type in the same paragraph. You’ll see how the collaboration engine sits behind a View Model, why presence is a separate channel from document ops, and the OT vs CRDT trade-off interviewers expect you to pick on purpose.
The hard part is not the toolbar. Google Docs is a canvas — it has been since the 2021 rewrite — plus a hidden input for IME and screen readers. The hard part is building that canvas: a layout engine that wraps glyphs into lines, a tile rasterizer that paints only the viewport, a hit-test that turns (x, y) into a document offset, and a collaboration layer that remaps the caret when someone else types. We’ll treat the document as a local-first CRDT, paint it ourselves, sync diffs over a WebSocket, and persist a snapshot so a new tab does not replay history. If you can explain how a keystroke becomes a glyph on a tile without waiting for the server, you’ll stand out.
Problem Statement
Build the frontend for a collaborative document editor like Google Docs.
Requirements:
- Users can create and edit a rich-text document (headings, bold, lists, links)
- Multiple people can edit the same document at the same time
- Each user sees the others’ cursors and selections in real time
- The document must stay consistent even when two people type in the same paragraph
- The editor should work offline for a short time and sync when the user comes back
Describe your approach to the editor surface, how you keep concurrent edits consistent, how presence works, and any optimizations you’d consider.
Interviewers are checking three things: you keep keystrokes on the client, you have a real consistency story (not “last write wins”), and you do not stuff cursor coordinates into the document itself. Start by locking scope, then pick OT or CRDT out loud.
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Web only, or also native apps? | Web (desktop and mobile browsers). |
| 2 | Do we need comments, suggestions, or version history? | Presence and live edits only. Comments are out of scope. |
| 3 | How many people can edit at once? | Design for about 50 concurrent editors. |
| 4 | Rich text only, or also images and tables? | Rich text and inline images. Tables are out of scope. |
| 5 | Should we use OT or CRDTs? | Walk me through the trade-off and pick one. |
| 6 | Is SEO important? | No. Documents are behind auth. |
| 7 | Any accessibility requirements? | Yes. Keyboard shortcuts and a screen-reader-friendly document. |
| 8 | Offline support? | Yes, short offline edits should sync when back online. |
Ask these before you draw boxes. “Comments are out of scope” saves you from designing a second CRDT for anchored threads. “Design for 50” tells you presence fan-out is a real cost, not a toy. “Walk me through OT vs CRDT” is the interview — pick one and defend it.
Requirements
Functional Requirements
- Create, open, and edit a rich-text document
- Toolbar for bold, italic, headings, lists, and links
- Live cursors and selections for other editors
- Conflict-free concurrent edits
- Reconnect and replay missed operations after a blip
- Short offline editing with a queued sync
Non-Functional Requirements
- Typing feels local: keystrokes appear in under 16ms
- Remote ops show up within ~200ms on a good network
- The document stays consistent for every client
- Accessible: canvas paint plus a hidden text input the AT can actually caret-walk
- Secure: only invited users can read or write
Under 16ms is one frame at 60fps. That number is why you never await the server before inserting a character. The ~200ms remote budget is “feels live,” not a hard SLA — say that out loud so the interviewer knows you are not inventing a guarantee.
Napkin Math
| Metric | Estimate |
|---|---|
| Active documents | 1,000,000 |
| Concurrent editors per doc (p95) | 10 (design for 100 — Google’s published cap) |
| Ops per editor | ~3 keystrokes/sec while typing |
| Peak ops on a busy doc | 100 × 3 ≈ 300 ops/sec (batch — not 300 HTTP calls) |
| Presence heartbeats | every 2s per editor |
What this tells us: typing must stay local. Never wait for the server to echo a character. Presence is a separate, low-priority channel so it doesn’t fight with document ops.
Scalability Estimates
The napkin numbers are enough to pass. A stronger answer expands them into traffic the socket and the snapshot store have to survive.
| Metric | Estimate | Calculation | Notes |
|---|---|---|---|
| Active documents | 1,000,000 | Given as the working set | Most are idle. Only open docs hold a socket. |
| Busy docs at peak (hedged) | ~10,000 | ~1% of the working set open at once | Order-of-magnitude, not a measured figure. |
| Editors on a busy doc (p95 / design) | 10 / 50 | Interviewer cap | Fan-out cost is editors × op rate. |
| Peak document ops on one doc | ~150 ops/sec | 50 editors × 3 keys/sec | Must apply locally before ACK. |
| Presence messages on one doc | ~25/sec if naive, ~12.5/sec throttled | 50 editors × (1 / 2s); throttle cursors to ~15Hz while moving | Do not put these in the CRDT. |
| Yjs update size | ~50–200 bytes per keystroke batch | Encoded binary update, not a full doc | HTTP snapshot exists so a new tab skips history replay. |
| Snapshot size (typical) | ~100–300KB | Rich text + a few inline images as references | Images live on a CDN; the doc stores URLs + dimensions. |
150 ops/sec on one document is fine for a single JS thread if you invalidate layout and paint once per frame. It is not fine if every keystroke rebuilds the DOM or triggers a React render of the whole page. That is the architecture constraint the math is supposed to produce.
Architecture / Component Design

The editor is a smart container. The View Model owns the document store and the collaboration engine. The UI never talks to the WebSocket itself.
Think of four layers, not a pile of components. The document (a Y.Doc) is the source of truth for characters, marks, and inline images. The layout engine turns that document into line boxes and pages. The canvas surface paints those boxes into cached tiles and draws the caret, selection, and remote cursors on top. A hidden IME input sits at the caret so the OS can compose CJK text and so a screen reader has a real text node. The View Model maps engine events into chrome: title, role, connection status, offline queue length. React never owns the document.
If you let the toolbar call document.execCommand or poke a contenteditable, you lose the transaction log and you lose layout control. Every formatting change has to go through the same path as a keystroke so undo, remote merge, offline replay, and the canvas stay consistent.
A 45-minute answer can say “I’d bind Yjs to ProseMirror.” That is an honest timebox. Production Docs does not do that. Say the timebox, then walk the canvas. That is the senior answer.
<EditorContainer>
useViewModel()
<Toolbar />
<PresenceAvatars />
<CanvasViewport />
<ImeCaretInput />
<PageOverlays />
</EditorContainer>
Component Structure and Responsibilities
- EditorContainer loads the document, opens the socket, and hydrates the store. It is the only component that mounts the sync provider. On unmount it destroys the provider so a route change does not leak a WebSocket.
- Toolbar applies marks (bold, heading) through the View Model, never by poking the DOM. Buttons read
activeMarksfrom the current selection so Bold lights up when the caret is inside bold text. - CanvasViewport is a scrollport over one or more page canvases. It does not use
contenteditable. Pointer events hit-test into document offsets. Paint is a rAF loop over dirty tiles. - ImeCaretInput is a 1×line-height textarea (or
contenteditablespan) positioned at the caret, opacity near 0,aria-labelon the document. It receives keystrokes and IME composition. The canvas paints the composed preview. Oncompositionendone transaction commits. - PageOverlays holds things the canvas should not own: comment pins, the link popover, image resize handles. Remote carets can paint on the canvas (cheaper) or as overlay divs (easier hit-test). They never steal focus.
- PresenceAvatars is the strip of faces. It reads the awareness set, not the Y.Doc. A join or leave updates this list without touching the editor.
- OfflineBanner (small) shows “Saved locally — syncing when back online.” Interviewers like seeing you surface the queue instead of failing silently.
Network Layer and Data Management
A Sync Manager wraps the Yjs provider. The rest of the app never constructs a WebSocket or calls fetch for ops. That module owns:
- HTTP snapshot load:
GET /api/docs/:idreturns base64 Yjs state plusrole - Provider connect: apply the snapshot, then open
WS /api/docs/:id/sync - Outgoing updates:
Y.encodeStateAsUpdateafter local transactions - Incoming updates:
Y.applyUpdatethen remap local selection - Awareness: cursor + name + color on a throttle, not on every
selectionchange - Reconnect: send a state vector, not a full reload
- Auth: short-lived socket token from an httpOnly session cookie
State splits into three stores on purpose. The Y.Doc is the document. An awareness map is ephemeral presence. A small UI store (React context or Zustand) holds title, role, connection: "online" | "reconnecting" | "offline", and the offline op count. Mixing those three is how you get a re-render on every remote keystroke.
Core Editing Workflow
- The user opens
/docs/:id. EditorContainer fetches the HTTP snapshot and ACL role. - The View Model hydrates a Y.Doc from
snapshot, runs layout, and paints the first viewport tiles. The user can type before the socket is up — those ops queue. - The Sync Manager opens the WebSocket and exchanges state vectors so both sides send only missing updates.
- A local keystroke hits ImeCaretInput, applies to the Y.Doc immediately (under 16ms), invalidates layout from that paragraph, and dirties the tiles that paragraph sits on. The next rAF paints the glyph. The encoded update goes on the socket when the buffer flushes (~16ms).
- A remote update arrives.
Y.applyUpdatemerges it. Layout invalidates from the touched blocks. Your selection is remapped through the same transaction so an insert at index 4 does not shove your caret if you were at index 20. Only dirty tiles repaint. - Presence is a second message type. Cursors paint on the canvas (or in PageOverlays). They are never written into the Y.Doc.
- On
offline, the provider stops. Local typing keeps updating the Y.Doc and IndexedDB. Ononline, you send a sync step and drain the queue.
This is the sentence you want in the interview: “The server fans out updates and persists snapshots. It is not in the keystroke path.”
Building the Canvas

This is the part most candidates skip. They say “rich text editor” and jump to OT. Google Docs paints the document. You need a layout engine and a rasterizer, not a contenteditable with a toolbar.
Why not contenteditable? The browser owns line breaking, caret, selection, paste, and IME. Those four disagree across Chrome, Safari, and Android. You cannot put 50 remote carets into a native selection. You cannot remap a native caret when a CRDT item lands at index 4. execCommand is deprecated and writes different HTML per engine. Spellcheck, autocorrect, and composition events fight a React tree. Docs left that model for a reason.
A canvas answer has five pieces. Write them on the board in this order.
1. Document → blocks, not HTML
The CRDT (or OT log) stores a sequence of block nodes. A paragraph is a list of styled runs, not an HTML string.
type TextRun = {
text: string;
marks: { bold?: boolean; italic?: boolean; link?: string; fontSize?: number };
};
type Block = {
id: string;
type: "paragraph" | "heading" | "listItem";
runs: TextRun[];
};
type LayoutRun = {
text: string;
x: number;
width: number;
font: string;
baseline: number;
};
type LineBox = {
blockId: string;
start: number; // document offset
end: number;
y: number;
height: number;
runs: LayoutRun[];
};
Never layout from innerHTML. Measure from runs. A remote bold at offset 12 is a mark change on a run, not a DOM mutation you hope the browser will keep.
2. Layout engine: wrap, then paginate
Layout is a pure function of (blocks, page width, fonts). It walks each block, measures each run, and emits line boxes.
Measure once, cache forever (until the font changes). ctx.measureText on every keystroke will miss 16ms. Key the cache by font + glyph (or by word if you wrap on spaces). Latin can use a simple width table. CJK and ligatures need the full measured width of the cluster, not char.length.
Greedy wrap: add words until the next word does not fit pageWidth - padding, then break. Soft hyphens and long URLs are the follow-up — mention overflow-wrap behavior and a last-resort character break so a 200-character token does not blow the page.
Pagination: fill a page with line boxes until y + line.height > pageHeight - margin, then start a new page. Docs is paginated. A “pageless” mode is the same engine with one infinitely tall page.
Invalidation is the performance trick. A keystroke in paragraph 40 does not relayout paragraphs 1–39. Their y-positions are unchanged. Relayout from paragraph 40 downward only if the paragraph’s height changed (it wrapped to one more line). If height is stable, only that paragraph’s lines are dirty. That is why you store blockHeights[] and a prefix sum for y.
function offsetToPoint(lines: LineBox[], offset: number): { x: number; y: number; height: number } {
// binary search lines by start/end, then walk runs with cached widths
}
function pointToOffset(lines: LineBox[], p: { x: number; y: number }): number {
// binary search lines by y, then walk runs until x is inside
}
Those two functions are the caret, the click, the drag-select, and every remote cursor. If you cannot convert offset ↔ pixel, you do not have an editor. You have a picture of an editor.
3. Tiles, not one giant canvas
A 50-page doc at 2× devicePixelRatio is tens of millions of pixels. You do not paint it every frame.
Split each page into tiles (256–512 CSS px tall). Each tile is an OffscreenCanvas (or an offscreen <canvas>) cached until its line boxes change.
The visible scrollport plus one tile of prefetch is the working set. On scroll, blit cached tiles with drawImage. On a keystroke, mark the tiles that paragraph intersects, relayout, redraw those tiles, blit.
const TILE = 256;
function paintFrame(ctx: CanvasRenderingContext2D, viewport: Rect, dirty: Set<string>) {
for (const tile of tilesIntersecting(viewport)) {
if (dirty.has(tile.id)) rasterizeTile(tile); // glyphs + inline images
ctx.drawImage(tile.canvas, tile.x, tile.y - viewport.top);
}
paintSelection(ctx, selectionRects(selFrom, selTo));
paintCaret(ctx, offsetToPoint(lines, caret));
paintPresence(ctx, remoteCarets.map((c) => offsetToPoint(lines, c.from)));
}
Glyphs: fillText is fine at interview scale. At Docs scale you atlas common glyphs onto a texture and drawImage slices so you are not shaping “the” 400 times a page. Mention the atlas; do not implement it on the whiteboard.
Inline images: the tile draws a reserved rect from the block’s display width/height (no CLS), then an ImageBitmap when it has decoded. Decode off the main thread (createImageBitmap). The CRDT stores a CDN URL, never bytes.
Device pixel ratio: backing store is cssSize * dpr. Reset on resize and on browser zoom or the text goes blurry on retina. This is the same rule as the drawing-tool canvas.
4. Caret, selection, and the hidden input
The canvas cannot receive IME. A <canvas> is a bitmap. The OS compositor, the keyboard, and VoiceOver need a focused text control.
Park a textarea (or a 1-line contenteditable) at the caret. Match font-size and line-height so iOS zoom and the IME window sit on the glyph. Opacity 0 is fine; caret-color: transparent so you do not see two carets. On each caret move, set input.style.transform to the caret pixel — do not remount it.
| Event | What you do |
|---|---|
beforeinput / input |
Read data / inputType. Insert, deleteContentBackward, insertParagraph become ops. Prevent the textarea from growing. |
compositionstart |
Open a composing preview string. Do not emit ops yet. |
compositionupdate |
Paint the preview on the canvas at the caret. Still one local-only buffer. |
compositionend |
Commit the preview as a single insert op. Clear the textarea value. |
keydown (arrows, Cmd+B) |
Move the model caret / apply a mark. Prevent default so the hidden input does not scroll the page. |
| pointerdown on canvas | pointToOffset → set caret → move the input → input.focus(). |
Selection is a list of rectangles, one per line in the range, filled at ~20% of the caret color. Drag-select is pointer capture + pointToOffset on move, painted on rAF, not on every event. Triple-click selects the block; double-click uses a word-break table (space / punctuation), not a regex word-boundary on Unicode.
Copy and paste go through the hidden input and clipboardData. On copy, write text/plain from the selected offsets and a private application/x-docs-ops (or HTML you generate from runs) so paste into Slack is plain and paste into another doc keeps marks. On paste, sanitize to your schema — never innerHTML the clipboard.
5. Hit-testing and remote carets
Click, drag, and “scroll caret into view” all use pointToOffset / offsetToPoint. Remote presence is the same: awareness sends { from, to } as document offsets, never as pixels. Each client maps those offsets through its own layout. That is why a zoomed-in tab and a mobile tab still put Ada’s caret on the same letter.
If Ada’s font has not loaded yet, fallback metrics will place her caret wrong for a frame. Either delay first paint until the document fonts are ready (document.fonts.ready), or accept a one-frame jump. Say that out loud.
Scroll-into-view: when the local caret leaves the viewport (arrow down, or a remote edit that grows a paragraph above you), set scrollTop from the caret’s y. Do not use element.scrollIntoView — there is no element.
What you still use the DOM for
<canvas> pixels are invisible to assistive tech. Keep a hidden, offscreen replica of the plain text (or the focused textarea with the current paragraph synced into it) with role="textbox" and aria-multiline="true". Sync the replica on commit, not on every composing preview. Announce “Ada joined” in an aria-live="polite" region. The toolbar stays real <button>s.
That split — canvas for paint, DOM for IME and AT — is the sentence that separates a Docs answer from a Medium-editor answer.
Keeping Concurrent Edits Consistent
Two people typing in the same paragraph is the interview. You have two honest options:
| OT (Operational Transformation) | CRDT (e.g. Yjs, Automerge) | |
|---|---|---|
| Idea | Every edit is an op. The server transforms incoming ops against ops it has already accepted. | Every character (or block) is a unique item. Merging is deterministic on every client. |
| Server role | Required. It is the source of truth and assigns a version to every op. | Optional. A server still helps with persistence and fan-out, but clients can merge peer-to-peer. |
| Offline | Harder. You must transform a queue of local ops against everything that happened while you were gone. | Natural. Local edits are just more CRDT items. |
| Cost | Well-known (Google Docs). Transform functions are easy to get wrong. | More metadata per character. Libraries are mature now. |
Pick OT with a central server as the baseline. That is what Google Docs actually runs. Say CRDT / Yjs as the alternative when they ask about offline-first or peer-to-peer — not as if it is what Docs ships.
“I’d use OT against a revision-numbered log. The client types into a local replica. Each batch carries the base revision it was written against. The server transforms late batches and broadcasts. The canvas consumes the document after each apply.”
You still will not write a full transform matrix on the whiteboard. You will walk one example so they know you understand why naive indexes break.

Start with ABCDE. Alice deletes D (DEL @3). Bob deletes B (DEL @1). Both authored against the same revision.
- If the server applies Alice first:
ABCDE → ABCE → ACE. Bob’s index still points atB. Fine. - If the server applies Bob first:
ABCDE → ACDE. Alice’s originalDEL @3now points atE. Transform it toDEL @2so it still killsD. Result:ACE.
Without that transform, the two arrival orders diverge (ACE vs ACD). That is the whole point of OT. Insert-vs-insert, insert-vs-delete, and a bold range that has to grow when someone types inside it are the same idea. You do not enumerate the matrix. You show you know it exists and that the server is the sequencer.
A CRDT (Yjs) is the honest timebox if they want you to skip writing transforms: every character is an item, merge is deterministic, the canvas still remaps the caret. Docs did not pick that. Figma is server-authoritative and CRDT-inspired, not a proof that Docs is a CRDT.
Caret mapping is the same collision in pixels. Alice’s caret is at offset 4 in “Hello”. Bob inserts “X” at offset 1. Text becomes “HXello”. Alice’s caret must land at 5. Then offsetToPoint moves the glyph. If you only merge bytes and leave the caret, the demo dies the first time two people type in one sentence.
type Op = {
docId: string;
clientId: string;
update: Uint8Array; // encoded Yjs update
sentAt: number;
};
type Presence = {
clientId: string;
userId: string;
name: string;
color: string;
cursor: { from: number; to: number } | null;
};
Never put presence inside the document. Cursors move constantly and should be ephemeral. If you store them as document items, every caret twitch becomes history you have to compact, and a refresh replays ghosts.
The sync protocol (this is the other half of the interview)
Canvas without a protocol is a drawing tool. Protocol without a canvas is a backend essay. You need both.

Each client keeps four things, not a firehose of keystrokes:
| Buffer | What it holds | When it moves |
|---|---|---|
| Local | Ops applied to the replica, not yet sent | Flush after ~200ms idle, or when the in-flight ACK lands |
| Sent | The one batch on the wire | On ACK: append to the log. On fail: retry the same requestId |
| Rev | Last revision the server has confirmed to you | Every ACK and every peer batch |
| Log | Committed batches since you joined | Used to rebuild the doc; not replayed from rev 0 |
One request in flight. If you send every keystroke as its own UPDATE, the server sees them out of order the moment a packet lags. OT assumes causality. Buffer while a batch is pending; flush the buffer only after ACK. Fast networks send small batches often. Slow networks send larger batches less often. Same code.
Coalesce continuous typing into one insert. A held backspace is one delete. A paste, a heading change, or a delete-then-type starts a new intent group — that group is also what Undo will invert.
Google’s published cap is 100 concurrent editors. Design for that, demo at 10. Presence at 100 is the cost that makes you throttle awareness to 10–15 Hz, not the document ops.
Undo goes through other people
“Local inverse stack” is the junior sentence. The senior sentence is: Undo appends a new batch. You never rewrite history.

Alice inserts “cat” at 6 → Hello cat. Bob inserts “very ” at 6 → Hello very cat. Alice hits Undo. Her inverse in the old context was DEL 3 @6. Transformed through Bob it becomes DEL 3 @11. The document becomes Hello very , not Hello. Redo transforms the original insert the same way.
If you restore Alice’s old snapshot, you wipe Bob. If you undo the latest revision on the server, you undo Bob. Both fail the interview.
Keep enough before-state to invert a delete (the text you removed, its marks). If a later edit deleted the target, the inverse becomes a documented no-op — do not silently chew a peer’s paragraph.
State and Data Flow
A predictable data flow is what keeps a 100-editor room from melting the tab. The rule is: document mutations stay in the replica, presence stays in awareness, and React only sees coarse UI state.
- User action (type, paste, toolbar mark) becomes a document transaction on the Y.Doc.
- Layout invalidates from the dirty block. Selection maps through the transaction.
- The Sync Manager encodes a binary update and sends it on the socket (or queues it if offline).
- Remote updates apply to the same Y.Doc. Layout invalidates. Selection maps. Dirty tiles repaint on rAF.
- React re-renders when title, role, or connection status changes — not when a character arrives.
Performance, Prefetching, and Caching
- Do not React-render per remote op. The editor view updates through layout + dirty tiles. The chrome (avatars, “saving…”) subscribes to throttled store slices.
- IndexedDB persist: an
IndexeddbPersistence(or your own wrapper) writes the Y.Doc so a refresh does not flash an empty page while HTTP snapshot loads. Last-write to IDB plus the server snapshot reconcile on hydrate via state vectors. - Snapshot, not history replay: a new tab loads
snapshot+snapshotVersion. The socket then sends only updates after that version. Replaying a week of keystrokes is how first paint dies. - Prefetch: on the docs list, hovering a row can
GET /api/docs/:idand warm IndexedDB. Do not open a socket until the user actually enters the doc. - Code split: the layout engine + Yjs is a large bundle. Load it on the doc route, not on the marketing page. Documents are behind auth, so SEO is not a reason to SSR the editor.
- Inline images: the document stores a CDN URL and display size. The image bytes never live in the CRDT. Lazy-load with width/height reserved so remote inserts do not shift the page (CLS).
Connection state belongs in the UI store: online, reconnecting, offline. Surface it. Users will type through a flap if they think they are still live; they will pause if they see “Offline — 12 edits queued.”
Data Model
Keep the on-the-wire types small. The Y.Doc is an opaque binary blob plus a few metadata fields the list view needs without loading the editor.
type DocRole = "owner" | "editor" | "viewer";
type DocPreview = {
id: string;
title: string;
updatedAt: string;
role: DocRole;
};
type DocSnapshot = DocPreview & {
snapshot: string; // base64 Yjs state
snapshotVersion: number;
};
type Op = {
docId: string;
clientId: string;
update: Uint8Array;
sentAt: number;
};
type Presence = {
clientId: string;
userId: string;
name: string;
color: string;
cursor: { from: number; to: number } | null;
};
type SyncClientMessage =
| { type: "update"; update: string }
| { type: "presence"; cursor: { from: number; to: number } | null }
| { type: "syncStep"; stateVector: string };
type SyncServerMessage =
| { type: "update"; update: string; from: string }
| { type: "presence"; users: Presence[] }
| { type: "syncStep"; update: string }
| { type: "error"; code: "FORBIDDEN" | "SNAPSHOT_STALE" };
type OfflineQueueItem = {
id: string;
docId: string;
update: string;
createdAt: number;
};
DocPreview is what the list fetches. DocSnapshot is the open-doc payload. OfflineQueueItem is IndexedDB, not a server table — once the socket ACKs a sync step, you drop those rows.
API Design
HTTP loads the document and the access list. A WebSocket carries ops and presence.
// GET /api/docs/:id
export type GetDocResponse = {
id: string;
title: string;
snapshot: string; // base64 Yjs state
snapshotVersion: number;
role: "owner" | "editor" | "viewer";
};
// WS /api/docs/:id/sync — one connection, typed frames
// JOIN { documentId } → JOINED { revision, snapshot }
// then SYNC { revision, operations }[] until SYNC_COMPLETE
// UPDATE { requestId, baseRevision, historyGroupId, operations[] }
// ACK { requestIdAcknowledged, revision }
// PEER_UPDATE { revision, userId, operations[] }
// presence is a separate frame, same socket
// PUT /api/docs/:id/title
export type RenameDocRequest = { title: string };
The HTTP snapshot is there so a new tab doesn’t replay the entire history. After that, the socket only sends diffs.
Join is a gap-free handshake, not “fetch then hope.” Attach to the ordered stream first, read snapshot at revision R, buffer anything that commits during the read, send the snapshot, then the contiguous tail after R, then SYNC_COMPLETE. The client does not enable typing until that tail is applied. If you open the socket after the snapshot, you can miss a revision and diverge with no error.
Send the op, not the document. A full-doc payload grows with length and hides intent. A delta is { type, index, chars } plus baseRevision. Under ~500ms to other screens is the WYSIWIS bar.
WebSockets are the transport. Long polling misses updates in the reconnect gap. SSE is one-way — you would still POST updates, two channels for one protocol. A live socket is ordered; a new socket is not. Revision numbers plus ACK are how you survive a drop. Socket.IO does not give you exactly-once.
Version history is the same log, grouped. Users do not want every keystroke. Cluster batches within a few minutes into “Version 2 — Ada, Bob.” Reconstruct from the nearest snapshot plus the tail. Named versions are bookmarks, not a second store.
Each UPDATE carries requestId (monotonic per client) and baseRevision. Retry after a drop reuses both so the server can dedupe. A new requestId on retry double-applies the batch.
On reconnect: send HELLO with your last ACK revision and the ids of durable unacked batches. Do not flush the local buffer yet. Apply the missing tail, transform local/sent through it, persist, then send at most one batch. If the server’s hot log no longer covers your base, it returns SNAPSHOT_REQUIRED. You download a fresh snapshot, rebase the durable queue, or open a conflict/export UI. Never silently drop offline work.
Endpoints
| Action | Method & Endpoint | Description |
|---|---|---|
| List documents | GET /api/docs?cursor=…&limit=20 | Paginated DocPreview[] for the signed-in user. |
| Create document | POST /api/docs | Body { title }. Returns { id }. Empty Y.Doc snapshot. |
| Open document | GET /api/docs/:id | Returns GetDocResponse. 403 if not invited. |
| Rename | PUT /api/docs/:id/title | Body { title }. Title is metadata, not a CRDT item, so last-write-wins is acceptable. |
| Sync | WS /api/docs/:id/sync | Binary updates + awareness. Auth via short-lived socket token. Viewers can receive, not send update. |
| Persist snapshot | POST /api/docs/:id/snapshot | Server-side, on a timer or disconnect. Clients do not POST full snapshots on every key. |
Title is last-write-wins on purpose. Putting the title in the CRDT works, but then the docs list needs a Yjs client just to show names. Call the trade-off: list metadata is HTTP, body is CRDT.
Example: Consuming the Sync Socket
function connectDocSync(docId: string, ydoc: Y.Doc, token: string) {
const ws = new WebSocket(`/api/docs/${docId}/sync?token=${token}`);
ydoc.on("update", (update: Uint8Array) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: "update", update: toBase64(update) }));
}
});
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "update") {
Y.applyUpdate(ydoc, fromBase64(msg.update));
}
};
return () => ws.close();
}
In production you use a Yjs provider that already speaks this protocol and handles state vectors. Write the sketch anyway — interviewers want to see you know applyUpdate is merge, not overwrite.
Optimizations
- Local first: apply the keystroke to the local Y.Doc before the network round trip
- Awareness throttle: send cursor updates at ~15Hz, not on every
selectionchange - Reconnect: on
online, send a sync step (Yjs state vector) instead of reloading the page - IndexedDB: persist the Y.Doc so a refresh doesn’t flash empty
- Code split: the editor bundle (layout engine + Yjs) only loads on the doc route
Those five are the pass-line answer. The follow-up is “show me the throttle.” Cursor events fire faster than paint. If you send every one, a 50-editor room drowns the op channel.
function useAwarenessThrottle(ydoc: Y.Doc, getCursor: () => { from: number; to: number } | null) {
const lastSent = useRef(0);
useEffect(() => {
const onSelection = () => {
const now = performance.now();
if (now - lastSent.current < 1000 / 15) return;
lastSent.current = now;
const awareness = getAwareness(ydoc);
awareness.setLocalStateField("cursor", getCursor());
};
document.addEventListener("selectionchange", onSelection);
return () => document.removeEventListener("selectionchange", onSelection);
}, [ydoc, getCursor]);
}
15Hz is enough for a caret to look live. On pointerup or blur, send one last update so the remote caret does not freeze mid-move. Pair this with a reconnect that sends Y.encodeStateVector(ydoc) so you never reload the page after a flap.
Handling User Edge Cases
| Case | Strategy |
|---|---|
| Two people type at the same offset | CRDT merge is deterministic. Remap the local selection through the remote transaction so the caret does not jump onto the other person’s character. |
| User goes offline for a few minutes | Keep applying to the local Y.Doc + IndexedDB. On online, exchange state vectors and drain the queue. Do not POST the whole document. |
| Tab refresh mid-type | IndexedDB hydrate first (instant surface), then HTTP snapshot, then socket sync. Show “Restoring…” only if IDB is empty. |
| Viewer tries to type | Role comes from GET /api/docs/:id. Do not mount ImeCaretInput for viewers. Socket rejects update from viewers anyway. |
| Paste of messy Word HTML | Sanitize through a paste schema (allow marks + links + images, strip scripts and style). Never innerHTML the clipboard. |
| IME composition (CJK, accents) | Hold ops until compositionend. One transaction per composed character. |
| Laptop sleep / socket flap | visibilitychange + online trigger a sync step. If SNAPSHOT_STALE, refetch HTTP snapshot and rebind. |
| 50 cursors on a phone | Paint at most N carets (for example the last 8 that moved). Avatars still list everyone. |
Pro-Level Optimizations
| Area | Suggestion |
|---|---|
| Selection mapping | Store the local caret as a Yjs relative position, not a raw index, so a remote insert before it cannot land you on the wrong glyph. |
| IME and autocorrect | Treat composing ranges as a single op. Mobile Safari will otherwise emit a delete + insert storm. |
| Snapshot compaction | Server writes a snapshot on idle or every N updates so new tabs never replay days of history. |
| Undo | Per-client inverse stack. Do not undo remote ops. Clear the stack on a huge paste if memory matters. |
| Presence paint | Transform caret coordinates in requestAnimationFrame. Do not setState on every awareness event. |
| Bundle | Lazy-load the editor on the doc route. Keep the docs list as a light HTTP table. |
Accessibility and Security
Accessibility
- Paint on canvas; put
role="textbox"+aria-multiline="true"on the hidden IME input (and keep a plain-text replica for AT) - Announce collaborator joins with an
aria-live="polite"region - Toolbar buttons are real
<button>s with shortcuts (Cmd+B) and visible focus - Don’t steal focus when a remote cursor moves
A canvas of glyphs looks like Docs in a screenshot and is silent to a screen reader. The focused control has to be a real text node the AT can caret-walk — that is the hidden input, not the bitmap. Sync the current paragraph (or a full plain-text replica) into that node on commit. Remote carets are decorative — do not put them in the tab order and do not move document.activeElement when Bob clicks elsewhere.
Shortcuts need a visible cheat sheet (Cmd+/). Bold is Cmd+B, but headings and lists should be reachable without memorizing. When a collaborator joins, the live region says “Ada joined” once, not on every heartbeat.
Security
- The socket checks the user’s role. Viewers receive updates and cannot send them
- Sanitize pasted HTML before it becomes document content (XSS)
- httpOnly session cookie plus a short-lived socket token
- CSP that blocks unexpected script sources
The HTTP ACL is not enough. A viewer who forges a WS update frame must get FORBIDDEN and a close. Paste sanitization is the XSS you will actually see: Word and Google Docs themselves put style and on* attributes on clipboard HTML. Strip to a schema (paragraphs, marks, links with https: only, images from your CDN host). Inline images are URLs you issued, not arbitrary javascript: hrefs.
The socket token should be short-lived and doc-scoped so a leaked WS URL cannot write every document in the account. Do not put the session cookie on a wildcard WebSocket path.
Conclusion: How to Design a Collaborative Editor
Google Docs is a canvas with a sync engine, not a contenteditable that POSTs HTML. Keep typing on the client, paint through a layout engine and dirty tiles, send revision-based batches over a WebSocket (one in flight), store presence separately, and pick OT because that is what Docs runs. If you can explain how a keystroke becomes a glyph — and how Alice’s DEL @3 becomes DEL @2 when Bob landed first — you’ll stand out.
The design that survives a 100-editor room is boring on purpose. An OT log (or a Y.Doc if they push CRDT) owns characters. Layout turns those characters into line boxes. Tiles paint the viewport. A hidden input owns IME and the screen reader. Join is snapshot-plus-tail. Undo is a new batch transformed through peers. IndexedDB covers refresh and short offline, and SNAPSHOT_REQUIRED is a rebase, not a silent drop. React owns chrome and stays out of the keystroke path.
Interviewers are not grading your familiarity with Yjs APIs. They are grading whether you refused last-write-wins, refused to put cursors in the document, refused to wait for the server before painting a character, refused to let the browser own layout, and refused to undo Bob. Say those out loud, then fill in the tiles and the ACK. That is a senior answer.
