Design Collaborative Document Editing
Several people type into the same document at the same time, and everyone sees everyone else's changes within a moment, with nothing lost. This lesson designs that editor: operations instead of whole-document saves, operational transformation with a central server or CRDTs without one, a session server per open document, an append-only operation log with snapshots, live cursors, offline edits that merge cleanly, and version history.
What you will learn
- Send small operations, not whole documents; saving whole documents loses concurrent edits.
- Operational transformation rewrites concurrent operations so every copy converges.
- CRDTs give every character a unique, ordered id, so edits merge without a central server.
- Route all editors of one document to one session server, which orders operations.
- Store an append-only operation log plus periodic snapshots; history comes for free.
- Cursors and presence are ephemeral: broadcast them, never store them.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: Why saving the whole document fails
- Step 4: Operational transformation
- Step 5: CRDTs
- Step 6: OT or CRDT, side by side
- Step 7: The high-level design
- Step 8: The editing protocol
- Step 9: Storage, snapshots and history
- Step 10: Cursors and presence
- Step 11: Offline editing
- Step 12: Two keystrokes, end to end
- Step 13: Permissions, scaling and failures
- Step 14: The follow-up questions
- Recap
The question
Welcome to lesson twenty-two of the system design course. Today's question is: design collaborative document editing. The interviewer says: design a document editor where several people can type in the same document at the same time, and conflicts are resolved automatically.
You have used this. You and three colleagues open the same document. Someone fixes a typo in the first paragraph while you write the conclusion, and a third person adds a table. Everyone sees the others' cursors moving and their text appearing, a fraction of a second after they type. Nobody presses save. Nothing is lost.
It feels like magic, and it hides one of the more interesting problems in distributed systems. Two people press a key at the same moment, at positions that affect each other. Each sees their own change first. How do both copies end up identical, and both changes survive?
This question is a favourite for senior and staff interviews, because it tests whether you can reason about concurrency precisely, not just draw boxes. The boxes here are actually simple. The algorithm in the middle is where you earn the offer.
We will go step by step: requirements, estimates, why saving whole documents fails, the two families of algorithms, operational transformation and CRDTs, then the architecture, storage, cursors, offline editing, history, permissions, failures and the follow-up questions. Let us start.
Step 1: Clarify the requirements
- 01Edit togethermany editors, changes appear live
- 02Presencewho is here, live cursors and selections
- 03Offlinekeep typing, merge on reconnect
- 04Historysee and restore earlier versions
- 05Sharingview, comment, edit permissions
- 06Rich textformatting, lists, tables, images
Functional requirements. Create and open a document. Several people edit at once and see each other's changes in real time. See who else is in the document and where their cursors are. Edit offline and sync later. Browse version history and restore an older version. Share with view, comment or edit permission.
Ask about scale per document. How many people edit one document at once? Usually a handful, rarely more than fifty, though a hundred viewers on a popular document is possible. That matters because it tells us one server can handle one document. Scope rich text: say we will design for plain text first, and explain how formatting fits later.
- 01Instant local typingnever wait for the server
- 02Remote edits fastunder a few hundred ms
- 03Convergenceall copies end identical
- 04Intentioneach edit does what its author meant
- 05Durableacknowledged edits never lost
- 06Scalemillions of documents, mostly idle
Non-functional requirements. Low latency: your own typing must appear instantly, with no round trip, and others' edits within a few hundred milliseconds. Convergence: after everyone stops typing, every copy must be identical. Intention preservation: each person's edit should do what they meant. And durability: no acknowledged keystroke is ever lost.
Convergence and intention are the two words to say out loud. Convergence alone is easy: just throw away one person's edit, and everyone agrees. The hard requirement is that everyone agrees and nobody's work disappears.
Step 2: Back-of-the-envelope estimates
Let us size it. A hundred million documents. Ten million people active per day. At peak, maybe two million documents open at once, most with just one editor, some with a few.
A typing person generates about five operations a second, one per keystroke. The client batches them, sending every fifty to a hundred milliseconds. With three million active typists at peak, that is around ten to fifteen million operations a second across the system. Large in total, but each document sees only a few dozen operations per second.
That last point is the key insight from the numbers. The load is huge in aggregate, but tiny per document, and documents are independent. So we can shard by document, and a single server can easily handle all the editors of one document. The hard part is not throughput; it is correctness.
Storage: a typical document is fifty kilobytes. A hundred million documents is five terabytes of current content. The operation history is bigger, because every keystroke is recorded, so we compact it into snapshots and keep detailed history only for recent edits.
Step 3: Why saving the whole document fails
doc = "cat" Asha: types "s" at end → saves "cats" Ravi: types "A " at start → saves "A cat" server keeps the last save: "A cat" Asha's "s" is gone
The simplest design: each client edits locally, and every few seconds saves the whole document to the server. The last save wins. Let us see why that fails.
Asha and Ravi both start from the word cat. Asha adds an s at the end. Ravi adds A and a space at the start. Asha saves cats. A moment later, Ravi saves A cat. The server keeps the last save, A cat, and Asha's edit silently vanishes. With real typing speeds, this happens constantly.
Locking the document, one editor at a time, avoids the problem but kills the product. Locking each paragraph is better, but people still collide, and it feels clumsy. The answer is to stop sending documents and start sending operations: insert s at position three, insert A space at position zero. Operations can be combined. Whole documents cannot.
But operations bring their own puzzle. Asha's insert at position three was correct for cat. After Ravi's insert of two characters at the start, the end of the word is now at position five. If we apply Asha's operation as is, the s lands in the wrong place. This is the core problem, and there are two families of solutions.
Step 4: Operational transformation
doc = "cat"
A = insert("s", 3) B = insert("A ", 0)
apply B first: "A cat"
transform(A, B): B inserted 2 chars before position 3
→ A' = insert("s", 5)
apply A': "A cats" ✓ both edits keptThe first family is operational transformation, or OT. The idea: when two operations happen concurrently, transform one against the other, so it still does what its author meant after the other has been applied.
In our example, Ravi's operation inserted two characters before Asha's position. So when Asha's operation arrives after Ravi's, we shift its position by two: insert s at five, not three. Both copies become A cats. Converged, and both intentions kept.
The transform function has rules for each pair of operation types: insert against insert, insert against delete, delete against delete. For example, if two people delete the same character, the second delete becomes a no-op. Ties need a rule too: two inserts at the same position are ordered by user id, so every copy picks the same order.
OT is simplest with a central server that decides one order of operations. Each client sends operations tagged with the document version it was based on. The server transforms any operation based on an old version against the operations it has accepted since, assigns it the next version number, and broadcasts it. Clients transform incoming operations against their own unconfirmed ones.
This is the approach used by the best-known document editors for years. Its strength: a central order makes reasoning manageable, and the document representation stays a simple string. Its weakness: it needs that central server, which makes long offline editing and peer-to-peer harder, and the transform rules for rich text get intricate.
Step 5: CRDTs
each char: { id: (counter, replica), after: id_of_left_neighbour, value }
c(1,A) a(2,A) t(3,A)
Asha: s(4,A) after t(3,A)
Ravi: A(1,R) after START, ' '(2,R) after A(1,R)
merge in any order → "A cats" on every copy
delete = mark id as a tombstoneThe second family is conflict-free replicated data types, or CRDTs. Instead of transforming positions, never use positions at all. Give every character a unique, permanent id, and define a total order on those ids. Inserting a character means: put this new id between these two existing ids.
Because ids never change, Asha's s is inserted after the t, wherever that t ends up. Ravi's characters are inserted at the start. Apply the two edits in either order and you get the same result. No transformation needed: concurrent operations simply commute.
Deletes mark a character's id as deleted, a tombstone, rather than removing it, because a concurrent insert might refer to it as a neighbour. Tombstones are cleaned up later, when every replica has seen the delete.
The strength of CRDTs: no central server is needed to merge, so offline editing and peer-to-peer sync are natural, and the correctness argument is cleaner. The cost: every character carries metadata, so memory use can be several times the text size, though modern libraries compress runs of characters typed together very effectively.
Which should you choose in the interview? Either is a good answer if you explain it. I would say: for a server-centred product with mostly online users, OT with a central server is proven. If offline editing is a first-class requirement, a CRDT is the more natural fit. Many newer editors use CRDTs and still route edits through a server for ordering, persistence and permissions. Mention that hybrid; it shows you know current practice.
Step 6: OT or CRDT, side by side
| Operational transformation | CRDT | |
|---|---|---|
| Needs a central order | yes, usually a server | no, merges anywhere |
| Offline editing | possible, transforms a long backlog | natural, operations commute |
| Metadata per character | none | an id per character, compressed |
| Correctness | transform rules are tricky | simpler to prove |
| Maturity | decades in production | newer, now widely used |
Before the architecture, put the two families side by side, because the interviewer will often ask you to choose and justify it.
Read the table row by row. OT needs a central order, so it fits naturally with a server in the middle, which we need anyway for permissions and storage. CRDTs merge anywhere, so they shine when people edit offline for a long time, or sync directly between devices.
On cost, OT keeps the document as plain text, so memory is small. A CRDT keeps an id for every character, and tombstones for deleted ones, so memory can grow, although good libraries compress runs of characters typed by the same person into one entry.
On correctness, OT transform functions are famously easy to get subtly wrong, especially for rich text, and several published algorithms were later shown to have bugs. CRDTs have cleaner proofs. On maturity, OT has run the biggest editors for many years, and CRDTs have caught up quickly.
My summary for the interview: I will design with a central session server either way, because we need it for ordering broadcasts, permissions and persistence. Inside it, I will use OT for a mostly online product, and I would switch to a CRDT if the interviewer makes offline editing a core requirement. Then move on, and do not get stuck in the debate.
Step 7: The high-level design
Now the architecture. Clients connect over a WebSocket, a long-lived two-way connection, through a gateway.
When a client opens a document, the gateway asks a router: which session server owns this document? The router uses consistent hashing on the document id, or a lookup table, so that every editor of the same document lands on the same session server.
The session server holds the document's live state in memory. It receives operations, orders and transforms them if we use OT, or merges them if we use a CRDT, appends them to the operation log, acknowledges the sender and broadcasts to every other editor. One server per document means one place that decides order, with no distributed locking.
The operation log is the durable record. A compaction job periodically folds operations into snapshots. A separate document service handles metadata: titles, owners, folders and permissions. And presence, who is here and where their cursor is, lives in memory on the session server and is broadcast, never written to the database.
Notice how little shared state there is. Each document's session is independent. To scale, add session servers; the router spreads documents across them. A server handling ten thousand quiet documents and a few busy ones is normal.
Step 8: The editing protocol
on keystroke:
apply locally; pending.push(op)
every 50 ms: send batch { base_version, ops }
on ack(version): pending.shift(); my_version = version
on remote(op, version):
op' = transform(op, pending) # against my unconfirmed ops
apply op'; my_version = versionLet us look closely at what a client does when you type, because this is where instant local typing comes from. The client applies your keystroke to its own copy immediately. You never wait for the server. Then it puts the operation in a pending list and sends it.
The server receives the batch, which says: these operations were based on version one hundred and four. If the server is at version one hundred and six, it transforms the batch against operations one hundred and five and one hundred and six, applies the result, gives it version one hundred and seven, and appends it to the log.
Then it sends an acknowledgement to the author, and broadcasts the transformed operations to everyone else. Each other client transforms the incoming operations against its own pending ones, so the edit lands in the right place in its copy too. Every client converges on version one hundred and seven.
A useful rule: each client has at most one batch in flight. It waits for the acknowledgement before sending the next batch, and buffers keystrokes meanwhile. This keeps the transformation logic simple, because the server only ever has to transform against a known set of operations, and it is the approach most production OT systems use.
Step 9: Storage, snapshots and history
| Store | Key | Holds |
|---|---|---|
| op log | doc_id, version | author, time, operations |
| snapshots | doc_id, version | full document state at that version |
| named versions | doc_id, name | pointer to a snapshot |
| docs | doc_id | title, owner, permissions, latest version |
Storage is an append-only operation log per document: version, author, timestamp, and the operations. Appending is fast, and the log is a perfect audit trail. But opening a document by replaying a million keystrokes would be slow.
So a compaction job writes snapshots: the full document state at a version, say every thousand operations or every few minutes of activity. Opening a document loads the latest snapshot and replays the few operations after it. That takes milliseconds.
Version history falls out naturally. To show the document as it was yesterday, load the nearest snapshot before yesterday and replay up to that point. Group operations into sessions by author and time, so the history list says: Asha edited for twenty minutes this morning, instead of showing every keystroke.
Old detailed operations can be pruned after a while, keeping only snapshots at hourly or daily granularity. Restoring an old version does not rewrite history. It creates a new operation that changes the document to match the old state, so the restore itself is undoable.
Step 10: Cursors and presence
Live cursors make the product feel alive, and they are a different kind of data. A cursor position is only interesting right now. Nobody needs to know where Asha's cursor was yesterday. So presence is ephemeral: it lives in the session server's memory and is broadcast, never stored.
Each client sends its cursor and selection a few times a second, throttled. The session server relays it to the others. Cursors are expressed relative to the document, so when remote edits arrive, clients shift cursor positions with the same transform used for text, or, with a CRDT, anchor them to character ids, which move with the text automatically.
When a client disconnects, the session server removes its presence after a short timeout and tells the others. With a hundred viewers, avoid sending every cursor to every viewer; show editors' cursors and a count of viewers. That keeps the broadcast fan-out bounded.
Step 11: Offline editing
A user on a train keeps typing with no connection. The client keeps applying edits locally and storing them in the browser's local storage as pending operations, all based on the last version it saw.
On reconnect, it sends the pending operations with their base version. With OT, the server transforms them against everything that happened since, which might be hundreds of operations, and broadcasts the result. With a CRDT, it simply merges, since operations commute. Either way, both the offline person's work and everyone else's survive.
Be honest about the limits. After a long separation, the merged text is consistent, but the meaning can be odd: two people rewrote the same sentence differently, and you get both rewrites interleaved. No algorithm understands meaning. Good products highlight heavily merged regions, or offer to show both versions, so a human can tidy up.
Step 12: Two keystrokes, end to end
Let us follow two concurrent keystrokes through the whole system. Asha and Ravi have the same document open, at version two hundred. Both connections go to the same session server, because the router hashed the document id to it.
Asha types an s at position three. Her editor shows it instantly and sends: base version two hundred, insert s at three. At the same moment, Ravi types A and a space at position zero. His editor shows it instantly and sends: base two hundred, insert A space at zero.
Ravi's batch reaches the server first. It is based on the current version, so no transformation is needed. The server applies it, assigns version two hundred and one, appends it to the log, acknowledges Ravi and broadcasts it to Asha.
Asha's batch arrives next, based on version two hundred, but the server is now at two hundred and one. It transforms Asha's insert against Ravi's: Ravi inserted two characters before position three, so Asha's insert moves to position five. Version two hundred and two. Ravi receives it and applies insert s at five. Meanwhile Asha's client receives Ravi's operation, transforms it against her pending insert, which changes nothing because Ravi's insert was before hers, and applies it.
Now both screens show A cats, at version two hundred and two. Total time: a few tens of milliseconds for each person to see the other's edit. Neither waited for their own keystroke, nothing was lost, and the log holds both operations for history. That is the whole system in one example.
Step 13: Permissions, scaling and failures
- 01Session server diesrouter reassigns; new server loads snapshot + log
- 02Client disconnectpending ops kept locally, resent on reconnect
- 03Duplicate opsclient op ids make resends idempotent
- 04Hot documentone server is enough for dozens of editors
- 05Huge viewer countfan out through broadcast relays
Permissions are checked when a client opens a document and on every operation batch. A viewer's connection simply cannot send operations; the session server rejects them. When someone's access is removed, the document service tells the session server, which closes that connection.
If a session server crashes, its documents' clients reconnect. The router assigns each document to another server, which loads the latest snapshot and replays the log. Clients resend any unacknowledged operations. Each operation carries a client-generated id, so the server ignores one it already logged. Users see a second of reconnecting and nothing is lost.
Acknowledge an operation only after it is durably appended to the log. That is the rule that makes the durability promise true: if the client got an acknowledgement, the operation survives any server crash.
For a document watched by thousands, like a company-wide announcement, the session server still orders operations for the few editors, but broadcasting to thousands of viewers goes through relay servers that fan out the stream. The ordering point stays single; only the delivery spreads.
Step 14: The follow-up questions
Now the follow-up questions interviewers like to ask.
Max asks
“Why must all editors of one document go to the same server?”
Because OT needs one place to decide the order of operations. Splitting a document across servers would need distributed agreement on every keystroke, which is slow and complex. Documents are small and independent, so one server per document is both simpler and plenty fast.
Max asks
“How does formatting work, like bold?”
Formatting becomes operations too: apply bold to this range. With OT, ranges are transformed like positions. With CRDTs, formatting marks attach to character ids at their start and end. Tables and lists are trees, so rich editors model the document as a tree of nodes and apply the same ideas per node.
Max asks
“How do comments stay attached to the right text?”
Anchor a comment to a range, and move the range with every edit, using the same transform as cursors, or attach it to character ids with a CRDT. If the anchored text is deleted entirely, keep the comment and mark it as referring to deleted text.
Max asks
“What about undo?”
Undo must undo my last edit, not someone else's. So each client keeps its own undo stack, and undo creates a new inverse operation, transformed against everything that happened since. It is never a rollback of the shared document.
Max asks
“How would you search across documents?”
Search reads snapshots, not the live session. A background indexer picks up new snapshots and updates a search index, a few seconds behind live edits. Results are filtered by the searcher's permissions at query time.
Max asks
“How do you stop one huge document from slowing everything down?”
Load it lazily. Split very long documents into sections, each with its own snapshot, and load only the sections near the reader. Operations still go through one session server, but opening the document no longer means loading every page into memory first.
Max asks
“How would you add suggestion mode, where edits need approval?”
A suggestion is an operation stored as a proposal instead of applied text, anchored to a range like a comment. Everyone sees it rendered as a coloured insertion or strike-through. Accepting it turns it into a normal operation through the session server; rejecting it deletes the proposal. The same ordering, logging and anchoring we already built does all the work.
Max asks
“How do you know the system is healthy?”
Watch the time from a keystroke being sent to it reaching other editors, per session server, at the ninety-ninth percentile. Also watch reconnect rates, operation rejections and snapshot lag. And run a background checker that opens random documents from the log and from the snapshot, and confirms they produce identical text.
Recap
- 01Operationsnot whole documents
- 02OTtransform against concurrent ops; central order
- 03CRDTunique ordered ids; merge anywhere
- 04Session serverone per open document, via a router
- 05Op log + snapshotsdurability and history
- 06Presencebroadcast, never stored
Let us recap. Saving whole documents loses concurrent edits, so send operations. Concurrent operations conflict on positions, and there are two ways out: operational transformation, which rewrites positions through a central order, and CRDTs, which use permanent character ids so operations commute.
Route every editor of a document to one session server that orders, logs, acknowledges and broadcasts. Apply local edits instantly and reconcile in the background.
Store an append-only log with periodic snapshots, which gives fast opening and version history. Keep cursors in memory only, merge offline edits on reconnect, and acknowledge only after the log write.
The moment that wins this interview is walking through the cat example, two inserts, one transform, on the whiteboard, calmly. Practice exactly that with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson twenty-three.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.