Skip to main content
08

Design a collaborative document editor (like Google Docs)

HardCRDTOperational transformationReal-timePresence

Design a collaborative document editor like Google Docs or Notion: several people edit the same document at the same time, see each other's cursors, and everyone ends up with the same document.

A typical framing: "Up to 50 people can edit a document at once. Edits from others appear within a fraction of a second. Users can keep typing during short network drops, and the document must never end up different for different people."

TL;DR

The core problem is concurrent edits: two users change the same text at the same time, and both must end up with the same result (convergence) without losing either intent. There are two families of solutions:

  • Operational Transformation (OT): edits are operations (insert "x" at 5). A central server orders them and transforms each operation against the ones it didn't know about. Google Docs uses this.
  • CRDTs (Conflict-free Replicated Data Types): every character gets a unique, ordered id, so edits merge automatically in any order, with no central transformation. Libraries like Yjs and Automerge implement this, and they also work offline and peer-to-peer.

On the client, every edit is applied locally first (no waiting for the network), then sent to a sync server over a WebSocket. Remote edits are merged in. Presence (cursors, selections, who's online) is a separate, ephemeral channel. The editor itself is built on a structured editor framework (ProseMirror, Lexical, Slate), not raw contenteditable. Persist the document as snapshots plus a log of updates, and support offline editing with IndexedDB.

1. Requirements

Questions worth asking:

  • Rich text (headings, lists, tables, images) or plain text?
  • How many simultaneous editors? (5 and 500 are very different problems.)
  • Offline editing: minutes of flaky Wi-Fi, or days on a plane?
  • Comments, suggestions mode, version history?
  • Permissions: view, comment, edit?

Functional

  • Rich-text editing with real-time collaboration.
  • Live cursors and selections with names and colors, and a list of who's here.
  • Version history, comments.

Non-functional

  • Local edits feel instant: typing never waits for the network.
  • Convergence: everyone's document ends identical.
  • Intent preservation: concurrent edits don't garble each other's text.
  • Offline tolerance: keep editing and sync later.
  • Performance: large documents stay responsive.

2. Architecture

Loading diagram...
  • Editor view: renders the document and turns user input into document operations. Use ProseMirror, Lexical, TipTap or Slate. They handle selection, IME input (e.g. Hebrew or Japanese keyboards), undo and schema validation, which raw contenteditable gets wrong.
  • Local document model: the OT document or CRDT (e.g. a Y.Doc). The source of truth on the client.
  • Sync server: receives updates, orders or relays them, broadcasts them to the other clients in the same document, and persists them. Documents are sharded by id, so all editors of one document reach the same server instance.
  • Presence: cursor positions and user info. Sent often, never persisted.

3. Data model

The conflict

The document is "cat". At the same moment:

  • User A inserts "s" at index 3: "cats"
  • User B deletes index 0: "at"

If B's client naively applies A's operation (insert "s" at 3) to "at", the index is now out of bounds. Index-based operations break when the document changes underneath them.

OT: transform the operation

The server receives B's delete first, then A's insert, which was based on the old version. It transforms A's operation against B's: a character before position 3 was deleted, so insert at 3 becomes insert at 2. Everyone gets "ats".

ts
type Op =
  { type: 'insert'; pos: number; text: string } | { type: 'delete'; pos: number; len: number }

// Simplified: transform an insert against a concurrent delete that came first.
function transformInsert(
  op: Extract<Op, { type: 'insert' }>,
  applied: Extract<Op, { type: 'delete' }>,
) {
  if (applied.pos >= op.pos) return op
  return { ...op, pos: op.pos - Math.min(applied.len, op.pos - applied.pos) }
}

Every pair of operation types needs a transform function. Getting all of them right (especially for rich text) is notoriously hard, and OT relies on a central server to define one order of operations.

CRDT: ids instead of indexes

In a sequence CRDT, every character has a unique id (for example (clientId, counter)) and refers to its neighbor by id, not by index. "Insert s after the character with id A:3" means the same thing no matter what else changed. Deletes mark characters as removed (tombstones). A deterministic tie-break (e.g. by client id) orders two inserts at the same spot the same way on every client. So updates can be applied in any order, any number of times, and every replica converges, with no central transformation.

OTCRDT
Needs a central serverYes, to order operationsNo (works peer-to-peer and offline)
Metadata overheadSmallLarger (ids, tombstones), well optimized in Yjs
Long offline periodsHardNatural
Used byGoogle DocsApps built on Yjs or Automerge; Figma uses a CRDT-inspired model with a central server

For a new product, a mature CRDT library (Yjs) with an editor binding (y-prosemirror) is the pragmatic choice.

4. Interface (API)

text
WS /docs/:docId/sync
  -> client sends: its state vector (what it has), then local updates as they happen
  <- server sends: the updates the client is missing, then remote updates as they happen

WS awareness channel (same socket)
  <-> { userId, name, color, cursor: { anchor, head } }   // ephemeral, throttled

GET  /api/docs/:docId/versions        -> named snapshots for version history
POST /api/docs/:docId/comments        { anchor, text }

The state vector handshake makes sync efficient: after reconnecting, a client says "I have up to counter N from each client", and the server sends only the difference.

5. Optimizations and deep dives

Local-first editing

Apply every keystroke to the local model and editor immediately, then send the update. Never round-trip to the server before showing a character. Batch updates (e.g. every 50 ms) to avoid one network message per keystroke.

Presence and cursors

Cursors are ephemeral: throttle them (~10-20 updates per second at most), don't persist them, and drop users who stop sending heartbeats. Anchor remote cursors to relative positions (CRDT ids), not indexes, or they drift when text is inserted before them. Give each user a stable color and a name label.

Offline and reconnecting

  • Persist the document and pending updates in IndexedDB (y-indexeddb), so the document opens instantly and survives a refresh while offline.
  • On reconnect, run the state-vector sync and merge. With a CRDT, a merge after days offline is still conflict-free, though the result may need human review (two people rewrote the same paragraph). Some products show a "changes merged" notice.

Undo

Undo must undo your own changes, not your collaborator's latest edit. Editor and CRDT libraries track the origin of each change (Y.UndoManager with tracked origins) to undo only local operations.

Persistence and history

  • Store an update log plus periodic snapshots, so loading a document doesn't replay a million updates. Compact old updates (garbage-collect tombstones) where possible.
  • Version history = named snapshots. Restoring a version is a new edit on top, not a rewind.

Performance for large documents

  • Render only what's on screen for very long documents. Avoid re-rendering the whole document on every remote update: editor frameworks update only changed nodes.
  • Load the document progressively (first pages first) and lazy-load embedded content (images, tables, code blocks).

Permissions and security

The sync server checks permissions on every update, not only when the page loads: a viewer whose client is modified must not be able to push edits. Validate updates against the document schema on the server too.

Common follow-ups

  • "Why not just lock paragraphs?" Locking is simple but feels bad: people wait for each other, and stale locks need timeouts. Real-time merge is the expected experience today.
  • "Why not last-write-wins on the whole document?" Concurrent edits would silently erase each other's work. LWW works for simple fields (a title, a checkbox), not for shared text.
  • "How would you add comments anchored to text?" Anchor them to CRDT relative positions (start and end ids), so they move with the text and survive edits around them.
  • "How do you scale to many documents?" Shard documents across sync servers by document id (consistent hashing), so all collaborators on one document meet on one instance, and keep idle documents out of memory.

What interviewers look for

  • Clearly stating the concurrency problem with a concrete example, and the convergence requirement.
  • Knowing OT vs. CRDT at a conceptual level, the trade-offs, and when to use a library.
  • Local-first edits with asynchronous sync.
  • Presence as a separate, ephemeral, throttled channel, with cursors anchored to relative positions.
  • Offline support, undo of local changes only, and server-side permission checks.

Was this helpful?

Related questions