Design a Collaborative Editor (Google Docs)
Concurrent editing without conflicts — operational transformation versus CRDTs, cursor presence, and how documents are actually persisted.
#1. Requirements
Functional
- Multiple users edit the same document simultaneously.
- Changes appear to others within a few hundred milliseconds.
- See collaborators' cursors and selections.
- Full version history; ability to restore.
- Offline editing that merges on reconnect.
Non-functional
- Convergence — all clients end with an identical document, always.
- Intent preservation — the merged result should reflect what each user meant.
- Low latency for local edits (typing must feel instant — zero perceptible delay).
- Documents up to ~100 pages with up to ~50 concurrent editors.
Clarifying questions: Plain text or rich text with formatting? (Rich text is substantially harder.) Do we need true offline support (pushes toward CRDTs)? Peer-to-peer or server-mediated? Max concurrent editors?
#2. Estimation
100M documents, 10M DAU, 5% of sessions collaborative.
Concurrent editing sessions: ~500,000
Operations: an active typist produces ~5 ops/s
500K sessions × 2 avg active editors × 5 = 5M ops/s peak
→ but each op is tiny (~50 B) and fanout is small
(only to others in the same document)
Per-document broadcast: 5 ops/s × 3 collaborators
= 15 messages/s — trivial per document
Storage:
document snapshots: 100M × 100 KB = 10 TB
operation log: retained for history, compacted periodicallyWhat this decided: this is not a throughput problem — it's a correctness and latency problem, sharded naturally by document. Each document is an independent, small-scale system, which is a very pleasant property worth pointing out.
#3. Why the naive approaches fail
Locking. One editor at a time. Correct, and it defeats the entire purpose.
Last-write-wins on the whole document. Two people editing different paragraphs, one person's work vanishes. Obviously unacceptable.
Send character positions. This is the subtle failure and worth walking through, because it motivates everything else:
Document: "HELLO"
Alice: insert "X" at position 1 → "HXELLO"
Bob: insert "Y" at position 3 → "HELYLO" (concurrently)
Naive application at Alice's client:
"HXELLO" + insert Y at 3 → "HXYELLO" ✗
Naive application at Bob's client:
"HELYLO" + insert X at 1 → "HXELYLO" ✓
DIVERGENCE. Same operations, different results.Positions are only meaningful relative to a specific document state. Once concurrent edits exist, a raw position index is ambiguous. This example is worth drawing in the interview — it makes the problem concrete in fifteen seconds.
#4. Operational Transformation
Usually shortened to OT, and it's the approach behind most established products.
The idea: an edit like "insert X at position 3" was written against the document as its author saw it. By the time it reaches you, you may have applied edits they hadn't seen, so position 3 no longer means the same place. OT adjusts — transforms — the incoming edit to account for the changes it didn't know about, so it lands where its author meant.
Alice's op: insert("X", pos 1)
Bob's op: insert("Y", pos 3)
At Alice's client, Bob's op arrives. Transform it against
Alice's already-applied op:
Alice inserted at position 1, which is BEFORE position 3
→ shift Bob's position by +1
→ insert("Y", pos 4)
Result: "HXELLO" + Y at 4 → "HXELYLO" ✓ matches BobThe transformation function T(op_a, op_b) produces adjusted operations such that applying them in either order yields the same document.
What makes OT hard:
- The transformation functions must satisfy convergence properties, and getting them right for all operation-pair combinations is famously difficult. Published algorithms have had correctness bugs found years after deployment.
- Complexity explodes with operation types. Insert/delete on plain text is manageable. Add formatting, tables, images, and lists, and the pairwise transformation matrix becomes very large.
- It generally requires a central server to impose a canonical order on operations. Each client transforms against that order.
Why products still use it: it's efficient (operations are small, no per-character metadata), it produces intuitive results for text, and it's battle-tested at scale.
#5. CRDTs
The alternative: make the edits impossible to conflict in the first place, so nothing ever needs transforming. "Commute" is the mathematical word — apply them in either order and you get the same document.
The trick for text is to stop using positions at all. Give every character its own permanent identifier, ordered so that you can always mint a new one between any two existing ones. An insert then says "put X between these two specific characters", which stays true no matter what else happened.
Instead of "insert X at position 1", say:
"insert X with id (4.5, siteA) between id 4 and id 5"
Fractional positions mean you can ALWAYS create an
identifier between two existing ones, without renumbering.
Ties broken by site ID.
Both clients sort by identifier → identical document,
regardless of arrival order.Deletion marks a character as a tombstone rather than removing it, so a concurrent insert next to it still has a valid anchor.
Advantages: no central server required (peer-to-peer capable), correct by construction (much easier to prove and test), and offline editing merges naturally — which is a genuine product capability, not just an implementation detail.
Costs, all real:
- Per-character metadata. Each character carries an identifier, which can be several times the size of the character itself. Modern implementations (Yjs, Automerge) mitigate this heavily with run-length encoding: when one author types a run of characters in a row, their identifiers are consecutive, so the whole run is stored as one entry ("author A, ids 100–147") instead of 48 separate ones.
- Tombstones accumulate. A document edited for years carries every deleted character. Garbage collection requires knowing all replicas have seen the deletion — which needs coordination, the very thing CRDTs avoid.
- Convergence ≠ intent. Two users editing the same word converge to a consistent result that may be nonsense. If Alice and Bob both fix the typo "teh" at the same moment — each deleting it and typing "the" — every client agrees on the result, but the result is "thethe". CRDTs guarantee agreement, not sensibility.
#6. Choosing — the answer to give
There's also a pragmatic third option worth mentioning: since a server is present anyway, it can simply assign a total order to incoming operations and rebroadcast. Clients apply operations in server order. The only transformation left is local: a client shows its own edits immediately, before the server has ordered them, so when the server's ordered stream arrives it must adjust those not-yet-confirmed edits to sit correctly after the ones the server placed first. This is simpler than full OT and adequate for many products.
Recent research has narrowed the gap between the two. Eg-walker (Gentle & Kleppmann, EuroSys 2025) stores only the plain operation history, as OT does, and builds CRDT state temporarily only while merging concurrent branches — so everyday memory use is close to OT's, while offline merges keep CRDT-style correctness. Fugue (Weidner & Kleppmann, 2023) fixes a classic CRDT anomaly where two people typing at the same spot get their words interleaved character by character.
#7. Architecture
┌────────┐ WebSocket ┌────────────────────┐
│client A│◄───────────►│ │
└────────┘ │ Document session │ one owner per
┌────────┐ │ server │ document
│client B│◄───────────►│ (in-memory doc │ (routed by
└────────┘ │ state + op log) │ doc_id hash)
┌────────┐ │ │
│client C│◄───────────►│ │
└────────┘ └─────────┬──────────┘
│ periodic
┌─────────▼──────────┐
│ Persistence │
│ - op log (append) │
│ - snapshots │
└────────────────────┘One server owns each document. This is the key architectural decision: routing all edits for a document to a single process gives you a natural serialization point — one place where all edits are put into a single sequence, one after another — so ordering is trivial and no distributed coordination is needed. Route by hash(doc_id) — the same partitioned ownership pattern that avoids global leader election.
Local-first application: the client applies its own edit immediately to local state (so typing feels instant), sends it to the server, and reconciles when the authoritative order comes back. Never wait for a server round trip before showing the user their own keystroke.
#8. Persistence
OPERATION LOG (append-only)
every op, in server order, with author and timestamp
→ enables history, undo, replay, and audit
SNAPSHOTS (periodic)
full document state every N operations
→ opening a document loads the last snapshot plus
the ops since, instead of replaying from creationThis is event sourcing applied to a document: the log of changes is the real record, and the current document is just what you get by replaying it. Snapshots are needed for the reason event sourcing always needs them — without them, opening a years-old document would mean replaying millions of operations from the start.
Compaction: old operations can be collapsed into snapshots and archived once no client needs them for history. Keep enough for the version-history feature the product promises.
#9. Presence and cursors
Separate from the document data, and much simpler:
- Cursor positions and selections are ephemeral, high-churn, and worthless when stale. Broadcast over the same WebSocket, never persist, and drop freely under load.
- Cursor positions must be expressed relative to the same identifiers as the document model — a raw index breaks as soon as someone types above you.
- Debounce updates (~20/s max) and coalesce; nobody needs every mouse movement.
This is a good example of data whose correct durability is zero, and saying so shows you classify data by requirement rather than treating it all the same.
#10. Failure modes & follow-ups
| Failure | Behaviour |
|---|---|
| Client disconnects mid-edit | Buffer operations locally; on reconnect, send the buffer with the last-known server sequence and receive missed ops. This is why op logs matter. |
| Document server dies | Another node takes ownership and rebuilds from the last snapshot plus the op log. Brief interruption; no data loss because ops were persisted before acknowledgment. |
| Two servers own the same document | Split brain — divergent histories. Prevent with fencing tokens: each new owner gets a higher ownership number, every write to storage carries it, and storage rejects any write with a lower number than one it has already seen — so the stale owner's writes are refused. |
| Very large document | Split into sections with independent op streams; load lazily. Editing page 90 shouldn't require the whole document in memory. |
| Slow client | Bound its outbound queue; if it falls too far behind, force a full resync from a snapshot rather than buffering unbounded ops. |
Follow-ups:
- "Rich text formatting?" — formatting is an operation over a range, and ranges shift under concurrent edits. Substantially harder than plain text for both OT and CRDTs. Being honest that this is where most of the real complexity lives is better than glossing over it.
- "Undo in a collaborative context?" — undo must remove your operation, not the last global one. Requires selective undo, which means generating an inverse operation and transforming it against everything since. Genuinely subtle.
- "Access control?" — enforce at the session server on connect and on each operation; a permission revoked mid-session must terminate the connection.
- "Why not just lock paragraphs?" — some products do exactly this, and it's a legitimate simplification. It trades true concurrency for a dramatically simpler implementation. Naming it as a valid product-level tradeoff rather than dismissing it reads well.
#Check yourself
Why do raw character positions fail in collaborative editing?Show answer
What does operational transformation do?Show answer
What makes OT hard?Show answer
How do text CRDTs avoid conflicts?Show answer
What do CRDTs cost?Show answer
OT or CRDT — what decides it?Show answer
What is the key architectural decision?Show answer
How are documents persisted?Show answer
#What to carry forward
- The hard problem is an algorithm: positions break under concurrency.
- OT transforms operations with a central order; CRDTs give characters stable IDs and converge by construction.
- Choose by the offline and peer-to-peer requirement.
- One owner per document, local-first edits, op log plus snapshots.
- Presence is ephemeral — broadcast it, never persist it.