Build the Backend for a Multi-User Live Text Editor
System DesignModel answerLast updated
Design a backend that lets many people edit one text document at once, keeps every replica converged, persists edits with history, and recovers cleanly from disconnects and server crashes.
You are asked to design the server side of a shared online word processor. Multiple people can open the same document together, type at the same time, and see one another's changes and cursor positions within a short delay. When everyone stops typing, all copies must show identical text, and the document must be stored durably with a browsable revision history.
The discussion should go deep on live collaboration and the backend architecture behind it. Account management, document creation and sharing settings are secondary and need only a short mention.
Assumptions
- The document is plain text. Formatting can be treated as attributes attached to ranges of characters, so the core design can reason about a sequence of characters.
- A user's own keystrokes must show on their screen immediately, without waiting for a server round trip.
Questions you should settle (or state assumptions for)
- How many people edit one document at the same time, typically and at the extreme? How many documents are open concurrently?
- What delay is acceptable before a collaborator sees an edit?
- Must editing work offline, with changes merged when the user reconnects?
- Are comments, suggestions and revision history in scope?
- If a server crashes, may a user lose the last instant of typing, or must every acknowledged edit survive?
What to cover
- The concurrency-control model, with a worked example showing two conflicting edits converging.
- Where each document's live state lives, how clients reach it, and how a single order of edits is established.
- What is persisted per edit, how a long-lived document still opens quickly, and how history is served.
- Behavior on reconnect, duplicate or missing edits, and a crash of the server holding the live state.
- Scaling across many documents and for one document with many collaborators.
- Presence and cursors, plus access checks on connect and on each edit (brief).
Hints
Hint 1
Start from the conflict: two users insert at the same index at the same time. If each applies the other's raw edit, the copies diverge. Decide whether you will transform operations against each other (OT) or give characters stable identities (CRDT), and pick one.
Hint 2
Make one server the single owner of each document at a time, route all clients of that document to it, and let it stamp edits with a monotonically increasing revision number. A total order makes the transform logic and recovery much simpler.
Hint 3
Treat the persisted operation log as the source of truth, and periodically write snapshots so opening a document means loading the latest snapshot plus a short tail of operations. Keep cursors and presence in an ephemeral channel that never touches the log.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Requirements and assumptions
I will assume a typical document has 1 to 10 active editors, with a worst case of a few hundred (mostly viewers) on one document. Millions of documents exist, and perhaps a few hundred thousand are open at once. Collaborators should see an edit within roughly 100 to 200 ms. Offline editing is a stretch goal that the same design supports. Every edit the server has acknowledged must survive a crash, while unacknowledged typing may be resent by the client.
Concurrency model: Operational Transformation with a central sequencer
Each edit is an operation such as insert(pos, text) or delete(pos, len). Clients apply their own edits locally right away (optimistic), then send them to the server tagged with the revision they were based on.
The server is the single authority for ordering. For an incoming operation based on revision r when the document is at revision n > r, the server transforms it against operations r+1..n, applies it, assigns revision n+1, persists it, and broadcasts the transformed result. Each client also transforms incoming remote operations against its own unacknowledged local operations.
Worked example. The document is "AB" at revision 5. User 1 inserts "X" at position 1 and user 2 inserts "Y" at position 1, both based on revision 5.
- The server receives user 1's edit first: the document becomes
"AXB"at revision 6. - User 2's edit is based on revision 5, so it is transformed against
insert(1,"X"). Same position, so a deterministic tie-break (for example, lower user ID goes first) shifts it to position 2:insert(2,"Y"). The document becomes"AXYB"at revision 7. - User 1 receives the transformed
insert(2,"Y")and applies it, getting"AXYB". User 2 receivesinsert(1,"X"), transforms it against its pendinginsert(1,"Y")using the same tie-break, giving position 1, and ends with"AXYB". Both copies converge.
Alternative: CRDT. Sequence CRDTs (RGA, Logoot, Yjs-style) give each character a unique ID and ordering rule, so operations commute with no central transform. This is better for offline and peer-to-peer use, but metadata overhead and tombstone garbage collection are costs. With a server-centric product, OT with a sequencer is simpler and has less per-character overhead. I would mention the CRDT as the choice if offline-first were a primary requirement.
Live state and routing
- A document session service holds the in-memory state for open documents: current text, revision number, and a window of recent operations.
- Clients connect via WebSocket to a gateway. The gateway looks up the document's owner in a routing layer (consistent hashing over session servers, or a lease in a coordination store such as etcd or ZooKeeper) and forwards to that server.
- Only the lease holder sequences operations for a document. Leases prevent split brain: a server that loses its lease stops accepting writes, and fencing tokens on log writes reject stale owners.
- When the last client leaves, the session is flushed and evicted.
Persistence and history
- On each operation the owner appends to a durable operation log (partitioned by document ID, key
(doc_id, revision)) before acknowledging. Group commits batch writes to keep latency low. - Snapshots of the full text are written every N operations (say 500) or every few minutes. Opening a document loads the latest snapshot and replays the tail, bounded to a few hundred operations.
- Revision history is served from snapshots plus operations: to view revision
k, load the nearest earlier snapshot and replay forward. Named versions and a coarser "grouped by author and time" view are built asynchronously from the log. - Old operations can be compacted into snapshots after a retention window, while keeping the coarse history.
Reconnect, duplicates, and failure
- Each client operation carries a client ID and a per-client sequence number. The server deduplicates retries by remembering the last sequence number per client.
- On reconnect, the client sends its last known server revision. The server replies with the missing operations, or a fresh snapshot if the gap is too large. The client then resends unacknowledged operations, which get transformed as usual.
- If the owning server crashes, the lease expires, another server takes over, loads the latest snapshot plus log tail, and reaches the exact last acknowledged revision. Clients detect the dropped connection, reconnect through the gateway, and resync as above. Because acknowledgement follows durable append, no acknowledged edit is lost.
Scaling
- Across documents: shard by document ID. Sessions are independent, so capacity grows by adding session servers. Memory per open document is small (text plus a recent-operations window).
- One hot document: the sequencer is single-threaded per document, which is fine for dozens of editors because transforms are cheap. For hundreds of viewers, fan out through read-only relay nodes that subscribe to the owner's stream, so the owner sends each operation once per relay and not once per viewer. Beyond a limit, viewers can be put in a lower-frequency or read-only mode.
- Batch operations from a rapid typist (for example, merge consecutive inserts within 50 ms) to cut message volume.
Presence and cursors
Cursor positions and selections are ephemeral. They go over the same connection but on a separate channel, are not logged, are throttled (for example, to 10 updates per second), and are held in memory only. Positions are transformed against incoming operations so they stay anchored. Losing them in a crash is harmless since clients re-announce on reconnect.
Access control (brief)
Check permissions when the WebSocket connects and again on each operation, since sharing can change mid-session. The server revokes the connection or downgrades it to read-only when permissions change.
Trade-offs and common mistakes
- Applying remote operations without transforming them (or transforming against the wrong revision range) causes divergence. Always track the base revision.
- Waiting for the server before showing local typing makes the editor feel laggy. Use optimistic local application.
- Acknowledging before the durable write risks losing acknowledged edits on a crash.
- Replaying the entire log on every open is slow. Snapshots are essential.
- Storing cursors in the document log bloats history and adds write load for no benefit.
- Ignoring split brain without leases and fencing can produce two competing orderings for one document.
- OT's transform functions are notoriously hard to get right for rich text, so keep the operation set small and test with randomized convergence tests. CRDTs trade that complexity for memory overhead and garbage collection.