Build Google Docs
Concurrent editing without conflicts. The one build where the hard problem is an algorithm rather than an architecture.
#The product
Several people type in the same document simultaneously. Everyone converges on identical text. Cursors are visible. History is preserved. Offline edits merge on reconnect.
Full treatment in the Collaborative Editor case study; this build shows the construction order.
#Phase 1 — Understand why it's hard
Positions are meaningless once concurrency exists. Walk this in an interview — it makes the problem concrete in fifteen seconds:
Document: "HELLO"
Alice: insert "X" at position 1 → "HXELLO"
Bob: insert "Y" at position 3 → "HELYLO" (concurrently)
Applying Bob's op at Alice: "HXELLO" + Y@3 → "HXYELLO" ✗
Applying Alice's op at Bob: "HELYLO" + X@1 → "HXELYLO" ✓
DIVERGENCE. Same operations, different final documents.A position index only means something relative to a specific document state — "position 3" in Bob's copy is a different spot from "position 3" in Alice's copy once she's inserted a character. The obvious fixes don't work. Locking the document so one person edits at a time removes the conflict, but also removes the simultaneous editing, which is the whole product. Last-write-wins (keep whichever version arrived last) silently throws away someone's work.
#Phase 2 — Pick a convergence strategy
Convergence is the requirement that every editor ends up with an identical document, whatever order the edits arrived in. Two families achieve it.
Operational Transformation (OT) — adjust each incoming edit to account for the edits it didn't know about, so it lands where its author meant.
Bob's insert@3 arrives at Alice, who already applied insert@1
→ Alice's insert was BEFORE position 3 → shift Bob's by +1
→ insert@4 → "HXELYLO" ✓ matches BobEfficient (small ops, no per-character metadata) and battle-tested — but genuinely hard to implement correctly. You need a transformation rule for every pair of operation types (insert vs insert, insert vs delete, delete vs format, ...), so adding one new operation type means writing rules against all the others. Published algorithms have had correctness bugs found years later. OT generally needs a central server to decide one official order of operations that every client then follows.
CRDTs — give every character a globally unique ID that can be sorted, and where you can always invent a new ID between any two existing ones (densely orderable). Because each insert says "put this between these two IDs" rather than "at position 3", operations commute: applying them in any order produces the same document, so there's nothing to fix up afterwards.
Not "insert X at position 1" but
"insert X with id (4.5, siteA) between id 4 and id 5"
Fractional positions mean you can ALWAYS create an ID
between two existing ones. Sort by ID → identical document,
regardless of arrival order.Correct by construction, works peer-to-peer and offline. The costs: every character carries its ID as extra metadata, and deletes leave behind tombstones — markers saying "this character was deleted", which other edits may still be pointing at. Tombstones accumulate forever, because you can't safely remove one until every replica has seen the delete, and confirming that needs coordination.
#Phase 3 — One owner per document
clients ──WebSocket──► document session server
(in-memory doc state + op log)
│ periodic
┌─────────▼─────────┐
│ op log (append) │
│ snapshots │
└───────────────────┘Route every edit for a document to a single process, by hash(doc_id). That gives a natural serialization point: one process sees every edit for that document and simply processes them in the order they arrive, so ordering becomes trivial and no distributed coordination is needed. This is the partitioned ownership pattern — instead of electing one leader for the whole system, each document has its own owner, so the work spreads across many servers.
Apply locally first. The client applies its own keystroke immediately. When the server sends back the official order of edits, the client adjusts its copy to match, if other people's edits landed in between. Never wait for a round trip to render the user's own typing.
#Phase 4 — Persistence
OP LOG every operation, in server order, append-only
→ history, undo, replay, audit
SNAPSHOTS full state every N ops
→ opening loads snapshot + ops since,
not a replay from creationThis is event sourcing applied to a document: the list of changes is the truth, and the document is what you get by replaying them. Snapshots exist for the reason event sourcing always needs them — without one, opening a three-year-old document would mean replaying every keystroke ever typed into it.
Ops must be persisted before acknowledgment — that's what makes recovery possible when a session server dies and another takes ownership.
#Phase 5 — Presence, and split brain
Cursors are ephemeral. Broadcast them over the same socket, never persist them, drop them freely under load, and limit each user to ~20 cursor updates a second (debouncing). A cursor position is useless the instant it's out of date, so the right amount of durability for it is zero — a good example of deciding how to store data by what it actually needs.
Split brain is the real risk. If two servers both believe they own a document, you get divergent histories that can't be merged. Prevent with fencing tokens on the persistence layer. Each time a server is granted ownership, it gets a number (an epoch) higher than any before. Storage remembers the highest epoch it has seen and rejects writes carrying a lower one. So if server A (epoch 7) freezes, server B takes over with epoch 8, and then A wakes up and tries to write, its epoch-7 writes are refused.
#The decision log
| Decision | Rejected | Because |
|---|---|---|
| Single owner per document | Any server handles any edit | Serialization point makes ordering trivial |
| Server-assigned total order | Full peer-to-peer CRDT | A server exists anyway; far simpler |
| Local-first application | Wait for server ack | Typing must feel instant |
| Op log + snapshots | State-only persistence | History, undo, and recovery all need the log |
| Persist before ack | Ack then persist | Otherwise a crash loses acknowledged edits |
| Cursors never persisted | Store presence | Worthless when stale; pure ephemeral broadcast |
| Fencing tokens on writes | Trust ownership | Split brain produces unmergeable divergence |
#What you'd cut for v1
Rich text, offline editing, version history UI, comments, suggestions. Ship plain-text collaborative editing with cursors. Rich text is where most of the real difficulty lives — formatting applies to ranges, and ranges shift under concurrent edits, which is substantially harder than character insertion for both OT and CRDTs. Being honest about that beats glossing over it.
#Explaining the design
"The core problem is that position indexes are meaningless under concurrency — two concurrent inserts applied in different orders produce different documents. I'd show that with a five-character example first.
Both OT and CRDTs solve it. Since there's a server here anyway, I'd use it as a serialization point: route all edits for a document to one owner by hash, assign a total order, and have clients apply locally first so typing feels instant. If offline-first were a requirement I'd switch to a CRDT and accept the per-character metadata.
Persistence is an append-only op log with periodic snapshots, ops durable before acknowledgment. Cursors are pure ephemeral broadcast, never persisted.
The failure mode I'd guard hardest is split brain — two owners means divergent histories that can't be merged — so ownership carries a fencing token the storage layer enforces."
#Next
Build Stripe — the build where correctness beats every other property.
#Check yourself
Why is collaborative editing an algorithm problem?Show answer
OT in one line, and its main cost?Show answer
CRDTs in one line, and their main cost?Show answer
Why route each document to one owner?Show answer
What persistence does a collaborative editor need?Show answer
How do you prevent split brain between document owners?Show answer
Why cut rich text from v1?Show answer
#What to carry forward
- Show the five-character divergence example first.
- With a server present, use it as the ordering point; choose a CRDT for offline or peer-to-peer.
- One owner per document, local-first typing.
- Op log plus snapshots, persisted before acknowledgement.
- Cursors are ephemeral; fencing tokens stop split brain.