Build a Multi-User Live Text Editor Backend
System DesignModel answerLast updated
Design a backend that lets many people edit one document at once with fast sync, offline tolerance, durable storage, and version history.
Build a Multi-User Live Text Editor Backend
Design the backend for a shared document editor in the spirit of a web-based office suite or a notes app. Several people open the same document, type at the same moment, and each of them must end up looking at an identical document.
What the system must do
- Keep the content of every participant in sync in near real time, at the level of characters or blocks.
- Store documents durably so nothing acknowledged is ever lost.
- Resolve edits that happen at the same time, with clearly defined behavior.
- Let users browse earlier versions and roll back to one of them.
Quality targets
- Latency: an edit made by one person shows up for the others in under 200 ms.
- Resilience: if a user's connection drops briefly, they can keep typing and nothing is lost when the connection returns.
- Scale: thousands of documents are open at once. Most have a few editors, a few are very busy.
What your answer should cover
- The overall architecture and which transport protocol you pick, and why.
- The data model for documents, operations, snapshots and versions.
- The synchronization approach (for example Operational Transformation versus CRDTs) and the reasons for your choice.
- Persistence, conflict handling and version history.
- What happens when a client goes offline and later comes back.
State your assumptions about scale with numbers, and point out the trade-offs you are making.
Hints
Hint 1
Begin by estimating load: how many operations per second, how large each one is, and how fast the log grows. These numbers justify batching, snapshots and compaction.
Hint 2
Give each document a single authoritative owner (for example through a lease plus consistent hashing). That gives you a total order of operations without distributed locking on the hot path.
Hint 3
Compare OT and CRDTs on offline support, metadata overhead, and implementation risk. Whichever you choose, spell out the rule for concurrent inserts at the same spot and for delete versus insert.
Hint 4
Think about reconnects: how does a client resend un-acknowledged edits safely, and how does the server avoid applying them twice?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale assumptions
- About 10k documents open at once. Most have 1-5 editors; hot ones reach ~100 editors and 1,000+ read-only viewers.
- A typing user produces ~5 ops/s. Clients batch for ~50 ms, so the server sees tens of thousands of messages/s rather than ~250k raw ops/s.
- Ops are ~50-100 bytes, so ingest is ~10-25 MB/s and the raw log can reach hundreds of GB to ~1 TB/day at peak. That mandates snapshots and compaction.
- Latency budget (200 ms): ~50 ms client to server, <10 ms processing, ~50 ms fan-out, remainder as network tail slack.
- Consistency model: strong eventual consistency with optimistic local apply, so typing never waits on the network.
2. Transport and API
Control plane (REST): create/get document, list versions, restore a version, update permissions.
Data plane (WebSocket per document):
join {docId, token, lastServerSeq or stateVector}returns a snapshot or just the missing ops.op {clientId, clientSeq, baseSeq, ops[]}returnsack {clientSeq, serverSeq}.broadcast {serverSeq, clientId, ops[]}to other participants.presence {cursor, selection}is ephemeral and never stored.
WebSockets give full-duplex, low-overhead frames suited to keystroke traffic. SSE plus POST works but needs two paths. Peer-to-peer WebRTC complicates auth, persistence and NAT traversal.
3. Data model
documents(doc_id PK, owner_id, title, head_seq, latest_snapshot_seq)
doc_ops(doc_id, server_seq, client_id, client_seq, payload, ts)
PK (doc_id, server_seq); UNIQUE (doc_id, client_id, client_seq)
snapshots(doc_id, seq, blob_url, created_at) -- blobs in object storage
versions(doc_id, version_id, snapshot_seq, label, author_id, created_at)
permissions(doc_id, principal_id, role)
server_seq is a per-document total order. The unique (client_id, client_seq) key makes retries idempotent.
4. Architecture
Clients -> LB -> WS Gateways (stateless) -> Session Server (owns doc)
|-> op log (append)
|-> snapshots (object store)
|-> pub/sub to gateways
Metadata/ACL DB, lease registry (etcd/ZooKeeper)
- Gateways terminate sockets (50-100k per node), authenticate, and route by
hash(doc_id). No document logic, so they scale horizontally. - Session server is the single owner of a document, held via a lease. It keeps live state in memory, validates, orders and merges ops, appends to the log, acks the sender and publishes to gateways.
- Failover: when an owner dies its lease expires in seconds. The new owner loads the latest snapshot, replays the log tail, and clients reconnect and resend un-acked ops. Dedup via the unique key makes this safe.
5. Sync algorithm: OT vs CRDT
OT: ops are sent against a baseSeq; the server transforms them against everything committed since, assigns server_seq and broadcasts. Clients keep one in-flight op plus a buffer. Pros: compact ops, small memory. Cons: needs a central server, transform functions for rich text are error-prone, and long offline sessions mean transforming against thousands of ops.
CRDT (Yjs/Automerge style): each character or block gets a unique ID (clientId, counter); inserts reference neighbor IDs; deletes leave tombstones. Merge is commutative, associative and idempotent, so order of delivery does not matter. Pros: no transform logic, natural offline support. Cons: metadata overhead, tombstone growth, possible interleaving anomalies.
Recommendation: a sequence CRDT relayed through the authoritative session server. The CRDT delivers convergence and robust offline editing; the server still supplies auth, total ordering for the log, persistence and fan-out. OT with a central server is also defensible if you explain the offline rebasing cost.
Explicit conflict rules:
- Concurrent inserts at the same position: deterministic order, e.g. by
clientIdtiebreak. - Concurrent formatting of the same attribute: last-writer-wins using a Lamport timestamp.
- Delete concurrent with an insert inside the deleted range: the insert survives.
6. Persistence and versioning
Write path: batch ops per document for 20-50 ms, append to the log, ack only after the durable write, then broadcast. Broadcasting before durability saves a few ms but risks showing edits that vanish after an owner crash, so persist first.
Snapshots: every ~1,000 ops or ~5 minutes of activity, serialize state to object storage. Loading a document is snapshot plus replay of ops after snapshot_seq, which bounds load time. Old log segments can be compacted once covered by a snapshot (keep what history policy requires).
Version history: a version is a pointer to a snapshot, created automatically (hourly or per session) or named by a user. Viewing an arbitrary moment means taking the nearest earlier snapshot and replaying forward.
Revert: implement as a new forward change that turns the current state into the old one, not by deleting history. Other collaborators then receive it like any other edit, and the audit trail stays intact.
7. Offline and reconnect
- The client applies edits locally and queues them with increasing
clientSeq. - On reconnect it sends
joinwith its last knownserverSeq(or CRDT state vector), receives missing remote ops, then resends the queue. - With a CRDT, the queued ops merge without rebasing. With OT, they must be transformed against every op committed since
baseSeq, which is costly for long offline periods; cap the offline window or fall back to a snapshot-and-merge flow. - The server drops duplicates using the unique key, so retries are safe.
8. Scaling and hot spots
- Shard documents by
hash(doc_id)across session servers; rebalance by moving leases. - For hot documents with 1,000+ viewers, viewers subscribe through pub/sub fan-out and are read-only, so only editors hit the session server's write path.
- Throttle presence updates (e.g. 10-20 Hz) and coalesce them.
9. Common mistakes
- Saying "the CRDT just merges" without defining tie-break and delete-vs-insert behavior.
- Acknowledging before the write is durable.
- No idempotency key, so retries duplicate text.
- Replaying the full log on every load instead of using snapshots.
- Persisting cursor/presence data.
- Implementing revert as history rewriting.
- Ignoring tombstone growth; mention periodic garbage collection once all clients have seen a deletion.