Design a Collaborative Editor
How to design a real-time shared document editor: merging concurrent edits with OT or CRDTs, one server per document, and the follow-ups interviewers ask.
On this page
A collaborative editor lets several people edit the same document at the same time. Each person sees their own typing immediately, sees the other people's changes and cursors within a fraction of a second, and all copies of the document end up identical. Nobody presses Save, and no edit may be lost.
The hard part is that two edits made at the same moment on the same text must merge into the same result on every screen, whatever order they arrive in, while every user still types with no delay. The steps below follow A Framework for Any Design. Try each "Your turn" box before you read the section after it.
Clarify the problem
Design a collaborative document editor.
Is the text plain or rich, and do we need comments and version history?
Reason about plain text. Version history is required, and comments are out of scope.
How many people edit one document at once, and how many users are there in total?
Usually one to three editors per document, and up to 100 during a meeting. There are about 20 million daily users, and 2 million of them have a document open at peak.
Then the core problem is convergence: every copy must end with the same text, and no acknowledged keystroke may be lost.
- Functional: users type with no delay, see other people's changes and cursors live, keep editing through a short offline period, and browse the version history.
- Non-functional: all copies converge to the same text, a remote edit appears within 200 ms inside one region, an edit that was acknowledged is never lost, one document supports up to 100 editors, and a document opens in under a second.
- Out of scope: comments, search and rich-text layout.
Estimate the scale
The client groups about 100 ms of typing into one operation, for example "insert the at position 4". Assume each person with a document open sends one operation every 2 seconds on average, which allows for pauses.
How many operations per second reach the servers at peak?
- 2 million people have a document open at peak
- Each sends one operation every 2 seconds on average
Show the working
- 2,000,000 ÷ 2 s = 1,000,000 operations a second
Estimate 1 million/s (anything from 300 thousand/s to 3 million/s is a good answer)
Operations on one document must be put in one order.
Assume 2 editors per open document, which gives 1 million open documents at peak. Each operation is acknowledged to its author and sent to the other editor, which is 2 million messages a second. The 2 million WebSocket connections need 40 gateways at an assumed 50,000 each, and we assume 40 document servers that own 25,000 documents each.
For storage, a user with a document open for about an hour a day sends roughly 2,000 operations, so 20 million users produce 40 billion operations a day. At about 100 bytes each (position, text, author, revision, time) that is 4 TB of log a day, or 120 TB for 30 days.
Write the editing messages. What must an operation carry so that the server can merge it?
Compare with a model answer
The client loads the document over HTTP at a given revision and then opens a WebSocket. Each operation carries the revision it was based on and a sequence number from that client, and the server acknowledges it with the revision it finally received.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
GET /docs/{id}
200 { "rev": 1042, "content": "...", "title": "Q3 plan" }
403 Forbidden no access 404 Not Found
WSS /docs/{id}/live?since=1042
client -> server
{ "type": "op", "base_rev": 1042, "client": "c7", "seq": 17,
"ops": [ { "insert": "the ", "at": 4 } ] }
{ "type": "cursor", "rev": 1043, "at": 88 }
server -> client
{ "type": "ack", "seq": 17, "rev": 1043 }
{ "type": "op", "rev": 1044, "author": "ben", "ops": [...] }
{ "type": "cursors", "users": [ { "user": "ben", "rev": 1044, "at": 12 } ] }
{ "type": "reload" } since is older than the kept log; fetch a snapshotThe API decision worth arguing is that each client keeps at most one operation in flight. Until seq 17 is acknowledged, the client buffers any new typing and sends it later as a single operation. The server then only has to adjust an incoming operation against the operations committed after its base_rev, which keeps the merge logic simple.
The pair (client, seq) makes resends safe, because the server ignores any seq it has already applied for that client.
Decide what you store so that a document opens quickly, history can be replayed, and a client can catch up after a reconnect.
Compare with a model answer
Store an append-only operation log keyed by document and revision, periodic snapshots of the full text, and one metadata record per document. Cursor positions are not stored.
Model the data
documents -- metadata, relational
doc_id BIGINT PRIMARY KEY
owner_id BIGINT
title VARCHAR(200)
snapshot_rev BIGINT -- newest snapshot
updated_at TIMESTAMP
doc_ops -- about 100 B a row
doc_id BIGINT
rev BIGINT -- 1, 2, 3 ... per document, no gaps
author_id BIGINT
client_id VARCHAR(16)
client_seq INT
op BYTES -- the transformed operation
created_at TIMESTAMP
PRIMARY KEY (doc_id, rev)
snapshots -- blob store, key "docs/{doc_id}/{rev}", about 50 KBEvery access stays inside one document: appending the next revision, reading the operations after revision 1000, and fetching the newest snapshot. The data is therefore partitioned by doc_id, and no query crosses partitions.
doc_ops needs a store with one leader per shard and a unique primary key, such as a sharded relational database. Inserting revision 1043 then fails if revision 1043 already exists, and this is what prevents two servers from writing the same revision. At 1 million inserts a second and an assumed 20,000 per shard, the log needs 50 shards, each with a synchronous replica so that an acknowledged operation survives the loss of the leader. Snapshots are never changed after they are written, so they go to blob storage.
Sketch the components. Decide where the WebSocket connections end and which server puts the operations of document 42 in order.
Compare with a model answer
Gateways hold the WebSocket connections and forward each message to the one document server that owns the document, chosen by consistent hashing. That server orders, transforms, logs and broadcasts the operations, and a separate compactor writes snapshots.
High-level design
The cheapest place to put a document's operations in order is the memory of one process. Each open document therefore has one owner, a document server that holds its text, its recent operations and its connected editors, and every editor of the document is routed to that owner.
1Document 42 is at revision 1042, and the ring maps it to server B.
2Ana and Ben type at the same moment, each sees their own change at once, and each sends it with
base_rev1042.3Ben's operation arrives first and is based on the latest revision, so server B stores it unchanged as revision 1043, then acknowledges Ben and sends it to Ana.
4Ana's operation arrives based on revision 1042, so server B transforms it against revision 1043, stores it as 1044, acknowledges Ana and sends it to Ben.
5Ben types again as seq 10, but server B hangs before it logs the operation, so Ben's client keeps it unacknowledged.
6Server B's heartbeats stop, the ring maps document 42 to server C, and the clients reconnect after a random delay with
since=1044.7Server C loads the snapshot at revision 1000 and the 44 operations after it, and stores Ben's resent seq 10 as revision 1045.
8Server B was only paused. It wakes up and tries to store an operation as revision 1045, but the insert fails because that revision exists.
9Server B sees that C owns the document and closes its connections, so those clients retry on C and the log never forks.
Deep dives
Merging concurrent edits with OT or a CRDT
Suppose the document is dog. Ana inserts s at position 3, and at the same moment Ben inserts my at position 0. If each client applies the other's operation as it was sent, Ana ends with my dogs, but Ben applies "insert s at 3" to my dog and gets my sdog. The copies have diverged, because Ben's insert moved the text that Ana's position referred to.
Operational transformation (OT) repairs the position before an operation is applied. For two inserts, if the other insert landed before yours, yours moves right by the length of the other one, and at the same position the one committed first goes left. In the example, the server commits Ben's insert as revision 8, sees that Ana's operation was based on revision 7, and moves her insert from position 3 to 3 + 3 = 6. Ana's client moves her pending operation the same way, and every copy shows my dogs. Deletes need their own rules, such as overlapping deletes shrinking each other, and these cases are where real implementations get hard. A central server keeps OT manageable, because one order for all operations means the transform only has to make "A then transformed B" equal "B then transformed A". Peer-to-peer OT has no such order and needs a much harder condition.
A CRDT (conflict-free replicated data type) removes positions altogether. Every character gets a permanent unique id, such as (ben, 1), and an insert says "place this after the character with id X". Ana's s is stored as "after the id of g", which stays true whatever is inserted elsewhere. Operations can be applied in any order once the character they refer to has arrived, applying one twice changes nothing, and two inserts at the same place are ordered by id. A deleted character stays as a hidden tombstone, because a later insert may refer to it. The cost is extra metadata: every character carries an id, tombstones pile up until they are compacted, and some algorithms interleave two people's words when both type at the same place.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| OT with a central server Usual default | Operations are small, and the server is one place for ordering and access checks. | An owner must be online for each open document, and a long offline session transforms against many operations. | A hosted product with one server per document. This is the choice here. |
| CRDT | No ordering server is needed, so edits can merge in any order. | Per-character ids and tombstones add metadata, and concurrent inserts can interleave. | Offline-first or peer-to-peer apps, or several regions that all accept writes to one document. |
I choose OT, because this design needs one owner per document anyway for ordering, access checks and cursors, so the main cost of OT is already paid. The choice would change for offline-first or peer-to-peer requirements, where no server can order the edits.
Routing every editor of a document to one server
The merge only works if all operations of a document are ordered in one place, so each document needs exactly one owner at a time. One option is to let any server accept any edit and claim the next revision number with a conditional insert into the log. This needs no ownership, but every operation costs a database round trip and racing claims retry, so it suits only low edit rates, such as a shared to-do list.
The second option is to hash the document id onto a consistent-hash ring of document servers, with the ring membership kept in a small strongly consistent store that gateways cache and watch. Ordering then happens in one process's memory, and adding a 41st server moves only about 1/41 of the documents, roughly 24,000 of 1 million, where hash mod N would move almost all of them. The weakness is that one very busy document cannot be moved on purpose.
The third option is an owner directory that records which server owns each document, which allows a busy document to be placed on a quiet server. It costs a lookup on every open and needs a highly available directory, so it pays off only when load is very uneven. I choose consistent hashing for many small documents.
The remaining problem is a stale owner. A server paused by garbage collection can wake up and still believe it owns a document after the ring has given it to another server. A lease makes this rare, because an owner stops serving when its lease expires and the lease expires before reassignment. A paused process cannot notice that its lease expired, so the log also acts as a fence: each revision can be written only once, so two servers can never both commit revision 1045, and the one whose insert fails checks the ring and steps down. Consensus and leader election explains why leases alone are not enough. For durability, the owner acknowledges an operation only after it is stored on the shard leader and its synchronous replica, since an owner that acknowledged first and then died would lose an operation the client believes is saved.
Storing operations and compacting them
Replaying a long log on every open would be slow, so a compactor writes a snapshot of the full text every 1,000 operations. Opening a document then reads one 50 KB snapshot and at most 999 operations, about 150 KB in total. The log is kept for 30 days. To show last Tuesday's version, take the nearest earlier snapshot and apply operations up to that moment.
Cursors, reconnecting and offline editing
Cursors are not operations. They live only in the owner's memory and are never logged, because losing one is harmless. A cursor message carries the revision it refers to, so when Ben inserts 3 characters before Ana's cursor, the same transform moves her cursor right by 3. With 100 editors each sending 10 updates a second to 99 others, that would be 100 × 10 × 99 = 99,000 messages a second, so the owner sends each client one combined update every 500 ms, which is 100 × 2 = 200 a second.
Reconnecting reuses the normal edit path. The client reconnects with its last known revision, as in since=1044, receives the operations it missed, transforms its unacknowledged operation against them, and resends it with its original (client, seq) so a duplicate is ignored. Offline editing is the same over a longer gap, with the offline edits sent as one operation with the old base_rev. If that revision is older than the 30-day log, the server answers reload, and the client fetches a snapshot and either merges the changes or saves them as a separate copy.
Bottlenecks and failures
At 10 times the load, which is 10 million operations a second, you add gateways and document servers, and the log grows to about 500 shards. The real limit is the owner of a single document. With 100 editors at 0.5 operations a second each, one document produces 50 operations a second, or about 5,000 messages a second to the other editors, which one server handles easily.
| Component that fails | What happens | What you do |
|---|---|---|
| A document server | The 25,000 documents it owned lose their owner, and clients keep typing locally without acknowledgements. | The ring reassigns the documents, and the 50,000 editors reconnect with a random delay and resend their unacknowledged operations. |
| A gateway | Its connections drop. | Clients reconnect through another gateway and catch up. |
| A log shard leader | Documents on that shard cannot commit, so their edits wait unacknowledged. | The synchronous replica becomes the leader, and clients resend what was not acknowledged. |
| The membership store | Ownership cannot change, but owners keep working. | Gateways keep using their cached ring. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Saves the whole document on each change and, with prompting, sees that concurrent saves overwrite each other. |
| Mid-level | Sends operations, explains OT or CRDTs with an example, and keeps an operation log with snapshots. |
| Senior | Ties the merge choice to the architecture, fences a stale owner with the log, keeps cursors out of the log, and prices offline editing and a 100-editor document. |
Many people say CRDTs are the modern answer. Why did you choose OT?
I already need one owner per document for ordering, cursors and access checks, so OT only has to make pairs of operations agree. A CRDT would remove that server but adds an id for every character. For days of offline editing or peer-to-peer sync, I would switch.
What if the owner crashes right after it acknowledges an edit?
The edit is not lost, because the owner acknowledges only after the operation is stored on the shard leader and its synchronous replica. The new owner rebuilds the document from the snapshot and the log, and the acknowledged edit is already in it.
Follow-up questions
How does undo work with several editors?
Undo should reverse only the user's own edits. The client keeps the inverse of each of its operations, such as a delete for an insert, transforms that inverse against everything committed since, and sends it as a new operation.
Why not lock the paragraph someone is typing in?
Locking works for forms but not for a shared document, because it makes people wait and a lock held by a closed laptop blocks everyone else.
How would you add formatting such as bold?
Add range operations, such as "bold from position 10 to 18", whose ends the transform moves when text changes before or inside the range. The rest of the design stays the same.
What happens when someone loses access while editing?
The metadata service tells the document's owner, which closes that user's connection and rejects the user's pending operations. Every operation passes through the owner, so nothing else has to enforce it.
How would you run this in several regions?
Each document's owner lives in one region. Editors in other regions see remote edits one cross-region round trip later. If two regions must both accept writes to one document, the single-owner design no longer works and a CRDT is the better choice.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".