Backend design for live multi-user text editing with conflict handling
System DesignModel answerLast updated
Design a server that orders and merges simultaneous keystrokes from many editors on one document, converges all replicas, and survives failures.
A product team is building a shared writing tool where several people can type into the same page at the same moment. Your job is to design the backend. The main focus is the mechanism that handles simultaneous edits to one document, not the front end.
Requirements:
- Many users can open the same document and edit it together.
- Other users should see each change within a few hundred milliseconds.
- Nothing is silently lost or duplicated, and every participant ends up looking at identical content, even when messages arrive late or out of order.
- The system should tolerate high network latency and brief disconnects.
Cover the following in your answer:
- Architecture. How clients connect and receive live updates, which backend services exist, and which storage you use for document state and edit history.
- Data model. How you represent the document content and how you encode individual edits (inserts, deletes, and formatting changes).
- Concurrency control (the core). How concurrent edits are ordered or merged. Explain at least one approach in real depth: a server-assigned global sequence, Operational Transformation, or a CRDT. Show why replicas converge even when operations arrive out of order.
- Trade-offs. What consistency guarantees you offer, and how you keep latency low without forcing users to wait on each other.
- Scale and reliability. How the design handles millions of documents, hundreds of simultaneous editors on a single hot document, and server crashes without losing acknowledged edits.
Assume WebSockets (or a similar persistent connection) on the client side.
Hints
Hint 1
Decide which party owns the ordering of operations for a given document. If a single owner exists per document, you can avoid the hardest correctness problems.
Hint 2
Think about what a client needs to know about the revision an edit was written against. Without that, the server cannot tell how to shift positions when merging.
Hint 3
Walk through a concrete two-user example on paper: both users edit the same starting text, one edit lands first at the server, and check that both final states match.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and rough numbers
Assume about 100M documents, 1M concurrent sessions at peak, and roughly 500K users actively typing. If each typist sends about 2 batched operations per second, the system handles around 1M ops/s. At about 100 bytes per op, that is roughly 100 MB/s of log writes. This is easy to shard by doc_id. The hard part is not aggregate throughput but the per-document concurrency protocol and hot documents with hundreds of editors. I would spend most of the interview time there.
2. Architecture
- Gateway tier. Terminates WebSockets and routes each session to the shard that owns its
doc_id. Routing is stable (consistent hashing or a lookup table) so a document's traffic lands on one place. - Collaboration service. Each shard holds the in-memory state for its documents. For any document there is exactly one active owner, enforced with a lease in a coordination store. That owner is the sequencer.
- Operation log. A partitioned, durable, append-only store keyed by
(doc_id, rev). Cassandra, Spanner, or sharded Postgres all work. The log is both version history and the recovery source. - Snapshot store. Object storage holding serialized documents at revision N, written every ~1,000 ops or when the document goes idle. This lets a new client or a new owner load quickly without replaying the full log.
- Metadata and ACLs. A relational database for ownership, titles, and sharing.
- Presence service. Cursors and "who is online" are ephemeral and lossy. They go over the same socket but are never written to the log.
3. Data model
The document is a linear sequence of characters, each with optional formatting attributes. An edit is a list of components that walk the document left to right:
retain(n, attrs?): skipncharacters, optionally applying formatting.insert(text, attrs?): add text at the cursor.delete(n): removencharacters.
Formatting changes are just a retain with attributes, so inserts, deletes, and styling all use one algebra. Every op carries a client_id, a per-client sequence number client_seq, and base_rev, the revision of the document it was written against. The first two make submissions idempotent; the last one tells the server how to adjust the op.
4. Concurrency control: server-sequenced OT
I would choose server-sequenced Operational Transformation, the model used by Jupiter and Google Docs.
Server algorithm. When an op arrives with base_rev = r and the server is at revision R:
- Transform the op against the committed ops
r+1 … R, producingop'. - Apply
op', assign it revisionR+1, and durably append it to the log. - Ack the sender with the new revision and broadcast
op'to everyone else.
Client algorithm. Each client tracks three things: server_rev, at most one inflight op that has been sent but not acked, and a buffer of local edits made since then (composed into a single op). Local edits apply immediately, so typing has no visible delay. When a remote op arrives, the client transforms it against inflight and buffer, applies it, and transforms its own pending ops so they remain valid. On ack, the buffer becomes the next inflight op.
Worked example. The document is "hello" at revision 5.
- Alice inserts
"!"at position 5 (the end), based on rev 5. Locally she sees"hello!". - Bob deletes position 0 (the
h), based on rev 5. Locally he sees"ello".
Bob's op reaches the server first. It becomes rev 6 with content "ello". Alice's op has base_rev = 5, so the server transforms it against Bob's delete. One character before her insertion point disappeared, so the insert moves from position 5 to position 4. The result is rev 7, "ello!".
Alice's client already shows "hello!". It receives Bob's delete at position 0, which lies before her pending insert, so it shifts her view to "ello!". Both replicas agree. If two inserts land at the same position, the server's arrival order breaks the tie, which is deterministic because the server is the single source of truth.
Why this converges despite reordering:
- One total order. Only the server assigns revisions, so every client applies the same ops in the same sequence.
- Only TP1 is required. With a central server, the transform function only needs to satisfy
apply(apply(S,a), T(b,a)) = apply(apply(S,b), T(a,b)). Peer-to-peer OT also needs TP2, which is famously difficult. Centralizing avoids that. - Gap detection. Revisions are contiguous. A client that jumps from rev 7 to rev 9 buffers rev 9 and fetches rev 8 via
GET /docs/{id}/ops?from=7. Network reordering therefore never corrupts state; it only delays it. - Idempotent retries.
(client_id, client_seq)lets the server recognize a resent op and return the existing ack instead of inserting twice. - Reconnect. The client reports its
server_revand pending ops. It pulls missing ops, rebases its pending ops locally, and resubmits. A very long offline period becomes a snapshot load plus a shorter rebase.
Alternative: CRDT (Yjs, Automerge, RGA). Each character gets a globally unique ID (site, counter). Inserts reference a neighbor's ID and deletes leave tombstones. Merges are commutative and idempotent, so no server transform is needed and peer-to-peer or offline-first work naturally. The costs are per-character metadata, tombstone garbage collection, and occasional interleaving artifacts when two people insert at the same spot. Undo and history are also harder.
For a cloud product with a central server, I would pick OT or a sequencer. For heavy offline or edge sync, I would consider a CRDT, or a hybrid where a CRDT provides convergence and the server still orders and persists operations.
5. Consistency and latency trade-offs
Guarantees per document:
- Committed operations have a single linearizable order, assigned by the owner.
- Clients get strong eventual consistency: they apply optimistically and converge once all operations are delivered.
- Authors get read-your-writes, since their edits are reflected locally at once.
- No cross-document guarantees are needed.
Keeping latency low:
- Optimistic local apply gives authors zero perceived delay.
- Transforms resolve conflicts automatically. Nothing is locked or rejected.
- One op in flight per client, with pending edits composed into one op, keeps transform cost bounded and batches keystrokes.
- The server coalesces broadcasts within a few milliseconds to reduce fan-out overhead on hot documents.
6. Scale and reliability
- Sharding. Documents spread across shards by
doc_id. Thousands of documents per shard are fine. - Hot documents. Viewers who only read can attach to read replicas or a broadcast tier that fans out from the sequencer. Only active editors need the sequencer's direct connection.
- Durability. An op is acknowledged only after it is committed to a replicated log (for example, a quorum write). Anything acked survives any single server crash.
- Failover. If the owner dies, the lease expires and a new owner loads the latest snapshot, replays committed log entries, and resumes at the next revision. Clients reconnect, resend unacked ops with their original
client_seq, and the deduplication logic prevents double application. - Snapshots. Written periodically so recovery and new joins replay only a bounded tail of the log.
Common mistakes
- Using last-writer-wins on whole documents, which silently drops edits.
- Locking the document during edits, which adds latency and blocks typing.
- Failing to define how operations are positioned relative to a revision, which makes merges impossible.
- Ignoring duplicate delivery after a timeout.
- Treating presence and cursors as durable data, which wastes write capacity.
- Acknowledging an op before it is durable, which can lose text after a crash.