Build a Multi-User Live Text Editor That Never Loses Edits
System DesignModel answerLast updated
Design a browser-based rich-text editor where many people edit one document simultaneously, stay in sync, keep durable history, and survive disconnects and server failures.
Design a web-based word processor where several people can work in the same document at once. Every collaborator should see the others' changes within moments, all open copies must converge to identical content, and no edit that the system has confirmed may ever be lost.
Treat the following scope as assumptions and confirm them before designing:
- Users create rich-text documents (plain text plus bold, headings, lists) and open them in a browser.
- Anyone with edit rights can type concurrently, including at the very same position.
- Collaborators can see who else is in the document, along with their cursors and selections.
- An owner shares a document with named people as viewer, commenter or editor.
- Users can browse a document's version history and restore an earlier version.
- A client that briefly goes offline keeps accepting local edits and catches up on reconnect.
Your answer should cover:
- Requirements and a rough capacity estimate (state your own numbers and label them as assumptions).
- Main components and the data model.
- How concurrent edits are ordered and merged, and why you chose that approach over the main alternative.
- How documents and history are stored.
- How the system scales and recovers from failures.
Out of scope unless raised: comment threads, spreadsheets, slides, cross-document search.
Questions worth asking up front: how many simultaneous editors per document and how large a document can get; how long a client may stay offline; the target latency for propagating an edit; how fine-grained and how long-lived history must be; whether link or organization-wide sharing exists and whether revoking access must cut off an already open session.
Hints
Hint 1
Rule out locking and last-write-wins first by saying what each does to two people typing at the same spot, then pick either operational transformation with a central sequencer or a sequence CRDT and commit to it.
Hint 2
Separate the data into three kinds: durable edits (append-only log plus periodic snapshots), ephemeral presence and cursors (in-memory, never persisted), and metadata and permissions (a regular database). Version history and fast loading both fall out of the log-plus-snapshot design.
Hint 3
Distinguish scaling across millions of documents (shard by document ID, route each document to one owner process) from the single hot document with many editors (one sequencer is fine for edits, but fan-out and presence need batching and throttling). For failures, think about idempotent resubmission with client-generated operation IDs and how a new sequencer takes over without forking history.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
Functional: rich-text editing, concurrent edits with guaranteed convergence, presence and cursors, sharing roles (viewer, commenter, editor), version history with restore, offline tolerance.
Non-functional:
- Convergence: all replicas reach identical content once they have seen the same edits.
- Durability: an acknowledged edit survives a server crash.
- Latency: remote edits visible in roughly 100-300 ms on a healthy network; local typing is applied instantly.
- Availability: editing continues locally during network trouble.
Assumed numbers (to be confirmed): 50M monthly users, 5M daily active, about 1M documents open at peak, typically 1-5 editors each, up to about 100 editors on a hot document. A typing user generates 2-5 operations per second after batching keystrokes. Peak: 1M open docs, perhaps 2M active typists, around 5M ops/s globally. Each operation is about 100 bytes, so roughly 500 MB/s of log ingest at that extreme. Realistic averages are much lower, but the number shows why sharding is needed. A typical document is under 1 MB of text; the cap might be a few MB.
2. Architecture
- Clients keep a local replica and an outbox of unacknowledged operations. They connect over WebSocket.
- Gateway tier terminates WebSockets, authenticates, and routes by document ID. It is stateless apart from the connections.
- Document session service is the core. Consistent hashing assigns each active document to exactly one owner process (the sequencer). That process holds the in-memory document state, orders operations, appends them to the log, and broadcasts them.
- Operation log store is an append-only, partitioned store keyed by
(doc_id, revision). - Snapshot store is an object store holding periodic full-document snapshots.
- Metadata DB holds documents, ACLs and users.
- Presence service is in-memory, for example Redis pub/sub or the session process itself.
Data model: Document(id, owner, title, head_revision, created_at), ACL(doc_id, principal, role), Op(doc_id, revision, client_id, client_seq, payload, ts), Snapshot(doc_id, revision, blob_ref).
3. Concurrency control
Why not simpler options: a lock per document blocks collaboration. Last-write-wins on whole documents or paragraphs silently discards one person's typing. Both break the "no acknowledged edit is lost" requirement.
Chosen approach: operational transformation (OT) with a central sequencer. Because every document already has a single owner process, a server-ordered OT design is the simplest correct choice.
- Each client sends
(client_id, client_seq, base_revision, op). - The sequencer transforms the op against all ops committed after
base_revision, assigns the next revision number, appends it to the log, acks the sender, and broadcasts the transformed op. - Clients keep at most one op in flight and buffer the rest, transforming incoming remote ops against their pending ones. This is the standard client/server OT scheme and keeps the transform matrix manageable.
- Same-position tie: two inserts at index 5 are ordered by a deterministic rule, such as the order the sequencer received them, falling back to client ID. Every replica applies the same rule, so they converge.
Main alternative: a sequence CRDT (for example RGA or Logoot-style identifiers). Each character gets a unique, ordered ID, so operations commute and no central ordering is needed. Pros: true peer-to-peer and long offline editing merge naturally. Cons: per-character metadata overhead, tombstones that need garbage collection, and harder rich-text semantics. If the interviewer says offline sessions last hours or peer-to-peer matters, switch to a CRDT. For a server-centric product with short disconnects, OT has lower overhead and simpler history.
4. Write path and durability
- Client sends op over WebSocket.
- The gateway forwards it to the document's owner process.
- The owner checks permission, transforms, assigns a revision.
- The owner appends to the replicated log and waits for a quorum write before acking. Only then is the edit "acknowledged".
- Broadcast to other connected clients, in revision order.
Acking after the durable write is slower by a few milliseconds but guarantees no acknowledged edit is lost. Broadcasting can happen in parallel with the write if you accept that peers may briefly see an edit that is rolled back on a crash. The safer choice is to broadcast after the commit.
5. Storage and history
- Load a document by fetching the latest snapshot plus log entries after its revision, then replaying them.
- Create a snapshot every N operations (say 500) or every few minutes of activity, in the background.
- Version history: named versions are markers on revisions. Auto-grouped versions are time-bucketed (for example, collapse edits into one entry per editing session). Viewing a past version means loading the nearest earlier snapshot and replaying to the target revision.
- Restore: do not rewrite history. Compute the diff from head to the old version and apply it as a new operation, so restore is itself an undoable, auditable edit.
- Compaction: old log segments can be compacted into snapshots according to a retention policy, keeping coarse granularity for old history.
6. Presence and cursors
Presence is ephemeral: stored in memory on the owner process, broadcast at a throttled rate (for example 5-10 updates per second per user), expired with a heartbeat timeout, and never written to the log. Cursor positions must be transformed against incoming ops so they stay anchored to the right text.
7. Permissions
Check the ACL on connect and on every operation. Cache ACLs in the session process, and have the metadata service push invalidations so revocation closes or downgrades a live session within seconds. Viewers get a read-only subscription, and the server rejects ops from them regardless of what the client does.
8. Scaling
- Many documents: shard owner processes by document ID with consistent hashing; most documents have one to five editors, so load spreads evenly. Idle documents are evicted from memory.
- One hot document: a single sequencer handles 100 editors easily (a few hundred ops/s). The bottleneck is fan-out, so batch broadcasts every 20-50 ms, throttle presence, and for read-heavy "thousands watching" cases add read-only relay nodes fed from the sequencer.
9. Failure handling
- Reconnect: the client sends its last known revision and its pending ops. Ops carry
(client_id, client_seq), so the server deduplicates resubmissions and applies each at most once. - Sequencer crash: a coordination service (lease or consensus) elects a new owner. The new owner rebuilds state from the log and uses the log's revision as a fence, so a stale former owner cannot append (fenced writes via conditional append on the expected revision). This prevents forked history.
- Divergence detection: clients periodically send a hash of their document at a given revision. A mismatch triggers a resync from snapshot.
- Observability: op latency percentiles, log append latency, reconnect rate, resync count, per-document queue depth.
Common mistakes
- Choosing last-write-wins or locking and not noticing the lost-edit problem.
- Acking before the edit is durable.
- Persisting cursor positions in the main log.
- Ignoring duplicate delivery on reconnect.
- Treating the hot-document case the same as the many-documents case.
- Implementing restore by deleting later history.