Build a Real-Time Multi-User Document Editing Platform
System DesignModel answerLast updated
Design a platform where many people edit one document simultaneously, covering merge rules, live streaming, durable history, reconnect, and periodic Git checkpoints.
Build a Real-Time Multi-User Document Editing Platform
You are asked to design a service in which several people can edit the same document at the same moment, see each other's changes almost immediately, and keep working through brief network drops.
Walk through your design for the following areas:
- Client side: how the document is represented and tokenized, how local edits are turned into change records, how cursors and selections are handled, and how the UI applies edits optimistically.
- Server side: how changes are streamed between participants, how each accepted change gets a stable identity and a defined position in the history, and how session data is journaled.
- Merge behavior: what rule guarantees that two people typing in the same region end up with the same text, deterministically.
- Storage: compare saving full snapshots as blobs with keeping an append-only stream of changes. Explain what you would combine and why.
- Git integration: how the document's history relates to Git commits.
Assumptions
- Multiple users may edit one document concurrently, and any of them may disconnect for a short while and come back.
- Every accepted change must have a stable identity and either a global order or a deterministic merge rule.
- Git commits act as durable milestones. They are not the low-latency channel that carries live edits.
Questions you should consider asking up front
- Is the content plain text, rich text, or structured blocks?
- Does editing need to work fully offline?
- What conflict and consistency behavior do users expect to see?
State your assumptions about these, then give a design with its trade-offs.
Hints
Hint 1
Pick one merge approach (central ordering with transformation, or a replicated data type with unique element IDs) and be explicit about how it makes concurrent edits converge to identical text.
Hint 2
Think of the durable state as two layers: an append-only journal of acknowledged changes that is the source of truth, plus periodic snapshots that bound how much of the journal must be replayed on load or reconnect.
Hint 3
Reconnect should be driven by sequence numbers: the client reports the last sequence it saw plus any unacknowledged local changes, and the server replies with either the missing tail of the journal or a recent snapshot plus the tail. Git commits should be cut from snapshots at milestones, not per keystroke.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I will assume rich-ish text (a sequence of characters with inline formatting), online-first editing with tolerance for short disconnects, and "everyone converges to the same text, and no one's accepted edit is silently lost" as the consistency goal. Full offline editing for long periods pushes the design toward a CRDT; I note that choice below.
High-level architecture
- Client: editor model, local operation buffer, WebSocket connection.
- Collaboration service: stateless gateways terminating WebSockets, plus a per-document session owner (one logical sequencer per document, found via consistent hashing on document ID).
- Journal: append-only log of accepted operations per document.
- Snapshot store: object storage holding periodic full-document blobs.
- Git bridge: async worker that turns snapshots into commits.
- Metadata/auth service: permissions, document registry, versions.
Client
- Document model: a tree or flat sequence of blocks and characters with attributes. Tokenization (for syntax highlighting, mentions, links) runs locally and incrementally on the changed range only, on a worker thread or idle callback, so typing is never blocked.
- Operations: every edit becomes a small record such as
insert(pos, text),delete(pos, len), orformat(range, attrs), tagged withclientIdand a client-local counter. That pair is the operation's identity before the server sees it. - Optimistic updates: apply locally at once, add to a pending buffer, and send. When an acknowledgment arrives, remove it from pending. When remote operations arrive, transform them against pending local operations (OT) or simply integrate them (CRDT).
- Cursors and selections: stored as positions anchored to the document (relative to element IDs in a CRDT, or transformed through each operation in OT). Presence updates are ephemeral, throttled (e.g. 10-20 per second), and never journaled.
Merge semantics
Two realistic options:
| OT with central sequencer | CRDT (e.g. sequence CRDT with unique IDs) | |
|---|---|---|
| Ordering | Server assigns a global revision number | No central order needed |
| Offline | Weak; long divergence is painful | Strong |
| Complexity | Transform functions are hard to get right for rich types | Metadata overhead, tombstones, need GC |
| Latency | One hop to server | Peer or server relay |
For an online-first product I would choose OT with a per-document sequencer: the server applies each operation against the head revision, transforming it over any operations the client had not yet seen, assigns rev = n+1, and broadcasts. Convergence follows from the transform properties plus a single total order. Tie-break for concurrent inserts at the same position is deterministic: by clientId. If offline editing is a hard requirement, I would switch to a CRDT, accepting the metadata cost.
Streaming protocol
- Client sends
{docId, clientId, opId, baseRev, op}. - Server transforms, appends to the journal, assigns
rev, and acks the sender with{opId, rev}. - Server broadcasts the transformed op with
revto others. - Duplicate
opIds are ignored (idempotent), which makes retries safe. - Client keeps at most one in-flight batch and buffers the rest, which keeps transformation bounded.
Backpressure: batch operations in 20-50 ms windows, and coalesce adjacent single-character inserts.
Journal and snapshots
- Journal (source of truth):
(docId, rev, opId, clientId, userId, timestamp, op), append-only, partitioned by document. It gives exact history, audit, undo, and replay. - Snapshots: every N operations (say 500) or T minutes, the owner materializes the document at
revand writes a blob. - Trade-off: blob-only storage is simple to load and cheap to read but loses fine-grained history and makes each save large (rewriting a 1 MB document per keystroke is wasteful). Log-only keeps everything and writes tiny records, but load time grows with history and bugs in replay are costly. Use both: load = latest snapshot + journal tail; compaction = delete or archive journal entries older than the oldest snapshot you need for retention and undo.
Reconnect
The client stores lastSeenRev and its unacknowledged operations. On reconnect it sends both. The server:
- if
lastSeenRevis within the retained tail, sends operations(lastSeenRev, head], and the client transforms its pending ops over them and resends; - otherwise sends the latest snapshot plus tail and the client rebases.
Because operations carry opId, anything that had actually been accepted before the drop is deduplicated.
Failover
The sequencer is the only writer per document. Ownership is held with a lease. On owner failure, a new owner is elected, reads the journal head, and continues from head+1. The journal write must be durable (replicated) before the ack is sent, otherwise an acknowledged edit could vanish.
Git integration
Git is a milestone store, not the transport: commit latency and object churn make it unsuitable for per-keystroke writes. A worker creates a commit when a user hits "save version", on a timer after quiet periods, or at publish. The commit contains the snapshot at a specific rev; the message or a trailer stores docId and rev so the journal and Git history cross-reference. Squash a burst of edits into one commit, and attribute authorship through co-author trailers drawn from the journal. Inbound changes from Git (e.g. a pull request edit) are diffed against the current head and injected as a synthetic operation set by a bot user, going through the same sequencer.
Security and operations
- Authorize at connection and per operation (view / comment / edit roles), and validate operation shape and size.
- Rate-limit per client.
- Metrics: op latency p50/p99 (target under 100 ms intra-region), reconnect rate, journal lag, transform errors, snapshot age.
- Convergence tests: randomized multi-client fuzzing that asserts all replicas end identical.
Common mistakes
- Using wall-clock timestamps for ordering.
- Acknowledging before the journal write is durable.
- Putting live edits through Git.
- Journaling cursor movements.
- Forgetting idempotency on retries.
- Never compacting, so loads get slower forever.
- Using integer positions in a CRDT instead of stable element IDs.