Design a Collaborative Editor (Google Docs style)

A frontend system design guide for a real-time collaborative text editor. You will learn how to model a document and how many users can edit it at once without losing work. You will also see how the UI stays fast on large documents.

Frontend system design · Real-time collaboration

Design an editor where several people type in the same document at once. Every client must end with the same text, and each user keeps a smooth local typing experience.

Correctness contract: All clients that have seen the same set of operations show the same document. A keystroke that the UI accepted is never silently lost, even across offline periods. Undo only reverts the user's own changes. A user never sees edit controls for a document they cannot edit.

You know HTML, the DOM, JavaScript, and what a WebSocket is. You do not need prior knowledge of OT or CRDTs. Google Docs, Notion, and Figma are used only to frame the problem. This is a teaching design, not a claim about their internals. Numbers are rough estimates.

A collaborative editor has three hard problems stacked on top of each other. The first is editing itself. Browsers give you contentEditable, which is powerful but inconsistent, so serious editors keep their own document model and treat the DOM as a view. The second is concurrency. Two people can type at the same position in the same millisecond, and both must end up with the same text. Operational Transformation (OT) and Conflict-free Replicated Data Types (CRDTs) are the two families of answers. The third is scale on the client. A 200 page document can hold 100,000 words and thousands of comments, and the editor must still respond to a keystroke within one frame. This guide builds the design layer by layer and shows the trade-offs an interviewer expects you to name.

Contents

  1. Concepts to understand first
  2. 1. Clarifying questions and requirements
  3. 2. Scope and budgets
  4. 3. High-level architecture
  5. 4. Data model
  6. 5. Interface and API
  7. 6. Deep dive: the editing surface and contentEditable
  8. 7. Deep dive: OT versus CRDT
  9. 8. Deep dive: presence, cursors, and multi-user undo
  10. 9. Deep dive: offline edits and merge
  11. 10. Deep dive: large documents, comments, and permissions
  12. 11. Failure modes
  13. 12. Trade-offs
  14. 13. 45-minute interview walkthrough
  15. 14. Summary
  16. 15. Common mistakes
  17. Worked example: two users edit the same sentence
  18. Code lab: OT transform for text
  19. Check yourself
  20. Key terms
  21. Further reading

Concepts to understand first

Document model versus DOM

The document model is a structured tree or list that your code owns, for example paragraphs that contain text runs with marks like bold. The DOM is only a rendering of it. Every edit becomes a model operation first. The view then patches the DOM to match.

Example. Pressing Ctrl+B produces the operation "add mark bold to range 10 to 15". The view turns that into a <strong> element.

Limit. The browser still edits the DOM itself during IME composition and spellcheck. The editor must read those changes back and map them to model operations.

Operational Transformation (OT)

OT sends operations like "insert X at 5". When two operations were made at the same base version, a transform function adjusts one so it still means the same thing after the other. A central server usually picks one global order.

Example. Bob deletes 2 characters at position 2. Alice inserts at position 5 at the same time. The server transforms Alice's insert to position 3.

Limit. Transform functions are hard to get right for rich text and tree structures. Peer-to-peer OT without a server is much harder still.

CRDT

A CRDT gives every character or element a unique, stable ID and an ordering rule. Replicas can apply operations in any order and still converge. No central transform step is needed. Yjs and Automerge are popular libraries.

Example. Alice inserts "X" with ID (alice, 17) after the character (bob, 3). Every replica places it there, no matter when it arrives.

Limit. CRDTs keep metadata and tombstones for deleted items. Memory and load time grow unless the library compacts well.

Versions and acknowledgements

With a central server, each accepted operation gets a version number. A client sends its operation with the base version it was made on. The server acknowledges with the new version, and broadcasts it to others.

Example. Alice is at version 41 and sends an op with base=41. The server already has 42 from Bob, so it transforms Alice's op and stores it as 43.

Limit. Version numbers only work with one ordering authority per document. Sharding a single document across servers breaks this.

Presence (awareness)

Presence is short-lived state about who is in the document: name, colour, cursor, and selection. It is not part of the document and is never stored in history.

Example. Bob's caret appears as a blue line with his name, 3 lines below yours.

Limit. Cursor positions must be expressed in a form that survives edits, or the remote caret jumps to the wrong place.

Relative positions and anchors

An absolute offset like 120 becomes wrong as soon as someone types before it. A relative position points at a stable item ID plus a side. Cursors, selections, and comment ranges all use relative positions.

Example. A comment anchored "after item (alice, 40) until before item (alice, 52)" stays on the same words after others edit the paragraph above.

Limit. If all anchored text is deleted, the anchor collapses. The UI must decide whether to keep the comment as orphaned or resolve it.

1. Clarifying questions and requirements

Functional requirements

Non-functional requirements

2. Scope and budgets

Document size

Operation rate

Frame budget

A keystroke has 16 ms from beforeinput to paint. Spend under 2 ms applying the op to the model, under 4 ms patching the DOM, and leave the rest for browser layout and paint. Sending to the network happens after paint, never before it. Remote ops are applied in batches inside one requestAnimationFrame callback so 20 remote ops cause one layout, not twenty.

Startup budget

3. High-level architecture

Collaborative editor architecture: input layer produces intents, the document model and sync core create operations, the sync core persists to IndexedDB and sends ops over WebSocket to the collab server, remote ops flow back into the model and view, and presence updates feed cursors.
Figure 1. Client layers of a collaborative editor. Local edits flow down to the network. Remote edits flow back up into the same model.

Layers

Intuition

Treat the editor like a tiny database. The model is the table. Ops are the write-ahead log. The view is a query result that you refresh after every write.

4. Data model

Use a block list with inline runs. Each block has a stable ID. Comments and presence point at relative positions, not offsets.

type BlockId = string                      // stable, e.g. "b_7f3a"
type Mark = { type: 'bold' | 'italic' | 'link' | 'code'; attrs?: Record<string, string> }

type Block =
  | { id: BlockId; type: 'paragraph' | 'heading'; level?: 1 | 2 | 3; runs: TextRun[] }
  | { id: BlockId; type: 'listItem'; listId: string; depth: number; runs: TextRun[] }
  | { id: BlockId; type: 'image'; src: string; alt: string }

type TextRun = { text: string; marks: Mark[] }

// Relative position: survives concurrent edits
type RelPos = { itemId: string; assoc: -1 | 1 }

type DocState = {
  docId: string
  version: number                          // last server-acked version (OT)
  blocks: Record<BlockId, Block>
  order: BlockId[]                         // or a CRDT sequence in CRDT mode
  pending: Op[]                            // sent, not yet acked
  buffer: Op[]                             // local, not yet sent
}

type Presence = {
  clientId: string; userId: string; name: string; color: string
  anchor: RelPos | null; head: RelPos | null
  lastSeen: number
}

type CommentThread = {
  id: string; start: RelPos; end: RelPos
  quotedText: string                       // for orphan display
  messages: { authorId: string; body: string; at: string }[]
  resolved: boolean
}

type Permission = 'owner' | 'editor' | 'commenter' | 'viewer'

The two queues, pending and buffer, are the core of the OT client. At most one batch is in flight. New local edits go into buffer until the in-flight batch is acknowledged. This is the classic "one outstanding op" rule from Jupiter and Google Wave. It keeps transforms simple because the client only ever rebases against one server stream.

5. Interface and API

HTTP endpoints

WebSocket protocol

// client to server
{ "t": "join",     "doc": "d1", "version": 1200, "token": "..." }
{ "t": "op",       "doc": "d1", "base": 1200, "clientSeq": 57, "ops": [ ... ] }
{ "t": "presence", "doc": "d1", "anchor": {...}, "head": {...} }
{ "t": "ping" }

// server to client
{ "t": "joined",   "version": 1203, "missed": [ ...ops 1201..1203... ], "role": "editor" }
{ "t": "ack",      "clientSeq": 57, "version": 1204 }
{ "t": "remote",   "version": 1205, "author": "u9", "ops": [ ... ] }
{ "t": "presence", "clientId": "c42", "state": {...} | null }
{ "t": "error",    "code": "STALE_BASE" | "FORBIDDEN" | "TOO_LARGE", "resync": true }

Key protocol rules are as follows.

In CRDT mode, the protocol is simpler. Yjs uses a state vector, which is a map from client ID to the highest clock seen. On connect, each side sends its state vector. The other side replies with only the missing updates. There is no transform and no global version, although the server may still number updates for storage.

Editor component props

<CollabEditor
  docId="d1"
  user={{ id: 'u1', name: 'Alice', color: '#3366ff' }}
  role="editor"
  transport={wsTransport}
  persistence={indexedDbPersistence}
  onSaveStateChange={(s) => setBadge(s)}   // 'saved' | 'saving' | 'offline' | 'error'
/>

6. Deep dive: the editing surface and contentEditable

Why not just use contentEditable

Setting contenteditable="true" on a div gives you a caret, selection, IME, spellcheck, and accessibility for free. It also gives you problems.

The model-first approach

Modern editors keep contentEditable for the caret and input, but never trust the DOM as the source of truth. The flow is as follows.

  1. Listen to beforeinput. Its inputType tells you the intent, like insertText, deleteContentBackward, or insertParagraph.
  2. Call preventDefault() for intents you handle. Apply the change to the model.
  3. Re-render the affected blocks. Restore the selection from the model with the Selection API.
  4. For IME composition, do not prevent default. Let the browser show the composition. On compositionend, read the text and convert it into one model op.
  5. Use a MutationObserver as a safety net. If something else changed the DOM, read it back or re-render the block from the model.
Mistake

Re-rendering a block in the middle of an IME composition. The composition breaks and the user sees doubled or lost characters. Defer remote changes to the composing block until compositionend, then apply them.

Paste and security

Never insert pasted HTML into the DOM. Parse it with DOMParser into a detached document, walk it, and map allowed elements to model nodes. Drop scripts, event handlers, styles, and unknown tags. Links must use http, https, or mailto schemes. Remote ops from other users get the same treatment. Validate them against the schema before applying, because a malicious client can send anything over the socket.

Accessibility of the surface

7. Deep dive: OT versus CRDT

OT sync sequence: Bob and Alice both edit from version 41, the server accepts Bob's delete as version 42, transforms Alice's insert to a new position as version 43, acknowledges each client, and broadcasts remote ops.
Figure 2. Server-ordered OT. The server assigns versions and transforms late ops. Clients rebase their pending ops on top of remote ones.

How the OT client works

The client keeps three states: the server-acked document, the in-flight batch, and the local buffer.

  1. A local edit applies to the view at once and goes into buffer.
  2. If nothing is in flight, the buffer moves to pending and is sent with base = version.
  3. When a remote op arrives, the client transforms it against pending and buffer, then applies the transformed op to the view. It also transforms pending and buffer against the remote op so they stay valid.
  4. When the ack arrives, version moves forward, pending is cleared, and the buffer is sent next.

The server does the same transform against every op accepted since the client's base. With one server order, the transform only needs a property called TP1. Applying A then B' gives the same result as B then A'. Peer-to-peer OT needs a stronger property, TP2, which most practical transform functions do not satisfy. That is why OT products almost always use a central server.

How a sequence CRDT works

Each inserted character gets an ID made of a client ID and a counter. It also records the ID of its left neighbour at insert time, and in some designs the right neighbour too. When two clients insert at the same place, a fixed tie-break rule, such as comparing client IDs, decides the order. Deletes do not remove items. They mark them as tombstones so later inserts that reference them still find their place.

Choosing between them

Interview

Do not say CRDTs are strictly better. Say what each costs. OT costs complex transform code and needs a central order. CRDTs cost metadata memory, tombstones, and a harder story for rich text intent, such as two users applying bold and a link to overlapping ranges.

Rich text intent

Convergence is not the same as preserving intent. If Alice bolds "quick brown" while Bob types "very " inside it, should the new word be bold? Most users expect yes. Marks need rules about whether they expand at their edges. Libraries like Peritext research this carefully. In an interview, mention that you define mark expansion rules per mark type: bold expands, links do not.

8. Deep dive: presence, cursors, and multi-user undo

Presence

Each client publishes its selection as a pair of relative positions plus user info. Send it on selection change, throttled to about 100 ms. The server or the awareness protocol relays it to others. Each entry has a lastSeen time. If a client sends nothing for 30 seconds, others remove its cursor. On tab close, send a null state so the cursor disappears at once.

Drawing remote cursors

  1. Convert each remote RelPos to an absolute model position.
  2. Map the model position to a DOM range.
  3. Call range.getClientRects() to get pixel boxes. Draw the caret and selection highlights in an overlay layer with absolute positioning.
  4. Recompute on every document change, resize, and scroll. Batch the work in one requestAnimationFrame.

Never insert cursor elements inside the editable DOM. They would break selection, IME, and the model mapping. Use an overlay, or the CSS Custom Highlight API, which can paint ranges without changing the DOM.

Tip

Above about 20 visible collaborators, show avatars and a count instead of every cursor. Hundreds of carets help no one and cost layout time.

Multi-user undo

A global undo would revert Bob's latest change when Alice presses Ctrl+Z. That is wrong. Each user undoes only their own changes. The steps are as follows.

9. Deep dive: offline edits and merge

Durable local state

Save every local change to IndexedDB before you consider it safe. Write the pending ops in a small transaction after each batch. Every few hundred ops, write a fresh snapshot and drop the old ops. On reload, read the snapshot, replay the pending ops, render, then connect.

Reconnect and merge

With a CRDT, reconnect is simple. Exchange state vectors and send the missing updates both ways. The merge is automatic and order independent.

With OT, the client may hold hundreds of ops on a base version that is now far behind. The server transforms them against everything that happened in between. That works, but the cost grows with both sides of the gap. Many OT systems cap offline editing, or compress the offline ops into one composed op before sending.

When merge is surprising

Both methods converge, but the result can still surprise people. If Alice rewrote a paragraph offline while Bob deleted it online, the CRDT keeps Alice's new text, maybe without its surroundings. Good products surface this. After a long offline period, show a short notice like "Your offline changes were merged. Review changes" with a link to version history.

Mistake

Storing offline edits only in memory or in localStorage. Memory dies with the tab. localStorage is synchronous, blocks the main thread, and is limited to about 5 MB.

10. Deep dive: large documents, comments, and permissions

Rendering large documents

Comments anchored to ranges

Store each comment with a start and end relative position and a copy of the quoted text. To render, resolve both anchors to model positions, then draw highlights with the overlay or the Custom Highlight API. Place the comment cards in a side column aligned to the highlight's top. If cards overlap, push later ones down. When the selected comment changes, slide the column so its card sits next to its text.

If both anchors resolve to the same point, the text was deleted. Show the comment as "Original text deleted" with the quoted text, so the conversation is not lost.

Permissions in the UI

11. Failure modes

12. Trade-offs

OT versus CRDT

DOM rendering versus canvas rendering

Small batches versus large batches

Full virtualization versus content-visibility

13. 45-minute interview walkthrough

  1. Minutes 0 to 5. Ask about rich text, concurrency level, offline, history, and comments. List requirements.
  2. Minutes 5 to 9. Work out document size, op rate, and the 16 ms keystroke budget.
  3. Minutes 9 to 15. Draw the layers: input, model, sync core, undo, awareness, persistence, transport, view.
  4. Minutes 15 to 20. Show the data model and the WebSocket protocol with versions and clientSeq.
  5. Minutes 20 to 28. Deep dive on OT versus CRDT. Walk through one concurrent edit example.
  6. Minutes 28 to 33. contentEditable pitfalls, beforeinput, IME, and paste sanitizing.
  7. Minutes 33 to 38. Presence and multi-user undo. Offline with IndexedDB.
  8. Minutes 38 to 42. Large documents, comments with relative anchors, and permissions.
  9. Minutes 42 to 45. Failure modes, the checksum safety net, and trade-offs.

14. Summary

15. Common mistakes

Worked example: two users edit the same sentence

The document holds "The cat sat." at version 41. Positions count from 0, so "c" is at 4.

  1. Alice clicks after "The " and types "black ". Her client inserts "black " at position 4 into the view at once. The op goes into buffer.
  2. Nothing is in flight, so the client moves it to pending and sends { base: 41, clientSeq: 9, ops: [insert(4, "black ")] }.
  3. At the same moment Bob selects "cat" and types "dog". His client sends { base: 41, ops: [delete(4, 3), insert(4, "dog")] }.
  4. Bob's message arrives first. The server stores it as version 42. Its document is now "The dog sat."
  5. Alice's message arrives with base 41. The server transforms it against version 42. Both inserts are at position 4. The tie-break rule orders by client ID, and "alice" sorts before "bob", so Alice's insert stays at 4. The server stores it as version 43. Its document is "The black dog sat."
  6. The server acks Bob with version 42 and sends him remote op 43, insert(4, "black "). Bob's client has nothing pending, so it applies it. Bob sees "The black dog sat."
  7. The server sends Alice remote op 42. Alice's pending op is still unacked. Her client transforms op 42 against her pending insert. Bob's delete at 4 now targets position 10, after "black ". Alice's view becomes "The black dog sat."
  8. The ack for version 43 arrives. Alice clears pending. Both clients now show the same text at version 43.
  9. Bob's caret was a relative position after the item "g". It stays after "dog" on Alice's screen even though offsets changed.
  10. Alice presses Ctrl+Z. Her undo manager only knows her insert. It deletes "black " and leaves Bob's "dog" alone. The result is "The dog sat." on both screens at version 44.

Code lab: OT transform for text

This snippet implements insert and delete ops on a string and a transform function with a tie-break. It then checks the TP1 property on random concurrent pairs. Save it as ot.mjs and run node ot.mjs. It should print "all converged".

function apply(doc, op) {
  if (op.type === 'ins') return doc.slice(0, op.pos) + op.text + doc.slice(op.pos)
  return doc.slice(0, op.pos) + doc.slice(op.pos + op.len)
}

// Transform a against b, where both were made on the same base
function transform(a, b) {
  if (a.type === 'ins' && b.type === 'ins') {
    const bFirst = b.pos < a.pos || (b.pos === a.pos && b.site < a.site)
    return bFirst ? { ...a, pos: a.pos + b.text.length } : a
  }
  if (a.type === 'ins' && b.type === 'del') {
    if (a.pos <= b.pos) return a
    if (a.pos >= b.pos + b.len) return { ...a, pos: a.pos - b.len }
    return { ...a, pos: b.pos, text: '' }               // inside a deleted range: drop it
  }
  if (a.type === 'del' && b.type === 'ins') {
    if (b.pos <= a.pos) return { ...a, pos: a.pos + b.text.length }
    if (b.pos >= a.pos + a.len) return a
    return { ...a, len: a.len + b.text.length }         // simple choice: delete grows over the insert
  }
  const aEnd = a.pos + a.len, bEnd = b.pos + b.len     // del vs del
  if (aEnd <= b.pos) return a
  if (a.pos >= bEnd) return { ...a, pos: a.pos - b.len }
  const start = Math.min(a.pos, b.pos)
  const overlap = Math.min(aEnd, bEnd) - Math.max(a.pos, b.pos)
  return { ...a, pos: start, len: a.len - overlap }
}

function randomOp(doc, site) {
  const pos = Math.floor(Math.random() * (doc.length + 1))
  if (Math.random() < 0.5 || doc.length === pos) return { type: 'ins', pos, text: site.repeat(2), site }
  return { type: 'del', pos, len: 1 + Math.floor(Math.random() * (doc.length - pos)), site }
}

let failures = 0
for (let i = 0; i < 10000; i++) {
  const base = 'collaborative'
  const a = randomOp(base, 'A')
  const b = randomOp(base, 'B')
  const left = apply(apply(base, a), transform(b, a))
  const right = apply(apply(base, b), transform(a, b))
  if (left !== right) { failures++; if (failures < 4) console.log('diverged', a, b, left, right) }
}
console.log(failures === 0 ? 'all converged' : `${failures} failures`)

Change the tie-break so both sides think they go first. Run it again and watch the convergence check fail. That shows why a deterministic tie-break is required.

Check yourself

  1. Why do serious editors handle beforeinput instead of reading the DOM after each change?
    Answer

    beforeinput tells you the intent before the browser changes the DOM. You can apply it to your own model and render a consistent result. Reading the DOM afterwards means parsing whatever HTML that browser produced, which differs across browsers.

  2. Why do OT products almost always use a central server?
    Answer

    With one server order, transforms only need TP1. Peer-to-peer OT needs TP2, which is very hard to satisfy with practical transform functions. The server also gives a natural place for versions, auth, and storage.

  3. What is a tombstone in a sequence CRDT and why is it kept?
    Answer

    A tombstone is a deleted item that stays in the structure, marked as deleted. Other replicas may still send inserts that reference it as a neighbour. Without it they could not find the right position.

  4. Alice presses undo right after Bob typed a word. What should happen and why?
    Answer

    Only Alice's last change is reverted. Bob's word stays. Undo stacks track local-origin changes only, and the inverse op is transformed through later ops so it still targets Alice's text.

  5. Why should remote cursors be drawn in an overlay rather than inserted into the editable DOM?
    Answer

    Extra elements inside the editable root break the mapping between DOM and model, confuse the browser selection, and can break IME composition. An overlay or the Custom Highlight API paints without touching the editable content.

  6. What makes a resend after a dropped connection safe?
    Answer

    Each batch carries a client ID and a clientSeq. The server remembers the last sequence applied per client and ignores duplicates. So the client can resend after any failure without double-applying.

  7. A viewer's role is upgraded to editor while the document is open. What must the client do?
    Answer

    The server sends a role change event. The client makes the surface editable, enables toolbars, and starts sending ops. The server's own permission check already uses the new role.

Key terms

contentEditable
An HTML attribute that makes an element editable by the user.
beforeinput
An input event that fires before the browser changes editable content and exposes an inputType.
IME composition
Multi-key input of a character, used for Chinese, Japanese, Korean, and others.
Operational Transformation
A method that adjusts concurrent operations so they apply cleanly after each other.
CRDT
A data type whose replicas converge when they apply the same updates in any order.
Tombstone
A deleted item kept in a CRDT so later references still resolve.
State vector
A map from client ID to the latest clock seen, used to compute missing updates.
Relative position
A position that points at a stable item ID instead of a numeric offset.
Presence
Ephemeral state about connected users, such as cursor and colour.
TP1
The transform property that two concurrent ops give the same result in either order.
Snapshot
A full serialized document state at a given version.
Custom Highlight API
A CSS API that styles arbitrary ranges without adding DOM elements.

Further reading

Primary references