Multi-User Collaborative Document Editor
Medium · System Design · Software Engineer · Onsite
Prompt
Design a cloud-based rich-text document service where many participants can edit the same file concurrently in real time.
Your design should satisfy the following product capabilities and operational targets:
- Live multi-user editing: up to
100active editors may type inside a single document at once. Collaborators should typically observe remote keystrokes in under500 ms, with an end-to-end ceiling of1–2 seconds. - Automatic conflict merging: when multiple participants modify overlapping words or adjacent lines simultaneously, the system merges their edits cleanly without locking sections or discarding text.
- Collaborator presence: viewers and editors see who is currently active in the file along with live cursor carets and highlighted text ranges.
- Version timeline: users can inspect historical revisions of a document and restore an earlier state safely.
- Offline resilience: users who lose network connectivity can continue editing locally and have their changes reconciled automatically once connectivity returns.
- Consistency and durability: every replica that has incorporated the same set of edits must converge to the exact same document state (strong eventual consistency), and no acknowledged keystroke may ever be lost.
Use the following traffic and storage baseline for capacity planning:
2 millionconcurrent editing sessions at peak, each generating40edit operations per minute (50–200 bytesper operation).500 milliontotal persisted documents with an average size of50 KBper document.
Scope & Expectations
- Derive throughput, bandwidth, memory, and storage estimates from the baseline figures and use them to motivate your service topology.
- Define client-server APIs, real-time wire messages, and the concurrency/conflict-resolution algorithm that guarantees convergence across simultaneous and offline edits.
- Design the storage schema, snapshot/log lifecycle, version restoration workflow, and low-overhead presence delivery path.
- Address hot-document scaling, server or database failover without split-brain corruption, and the principal architectural trade-offs.
Step-by-step walkthrough
Clarify requirements and scope
Before drawing boxes, pin down what "a document" is and what consistency guarantee we owe users, because both conflict resolution and storage layout flow directly from those two choices.
Document model and scope
- Rich text as a character sequence: a document is an ordered string of characters where formatting (
bold,heading,link) attaches as key-value attributes on character ranges. Embedded images or tables occupy a single special placeholder character, so one unified character-offset algorithm handles text, formatting, and media together. - Client-server architecture: browser and mobile editors sync through our cloud servers (no peer-to-peer LAN mode or end-to-end encryption in v1; we cover how those change the algorithm in follow-ups).
- Access roles:
OWNER,EDITOR,COMMENTER, andVIEWER.
Functional requirements
- Real-time collaborative editing: up to 100 concurrent editors can type in the same document simultaneously and see one another's edits within
1–2 seconds(targeting< 500 ms). - Graceful conflict resolution: concurrent edits in the same sentence merge automatically without losing anyone's typing.
- Version history: browse named or auto-grouped past versions with timestamps and authors, preview any version, and restore it.
- Presence awareness: see active collaborators, their live cursor carets, and highlighted text selections.
- Offline editing: keep editing seamlessly without internet and merge automatically upon reconnecting.
Non-functional requirements
- Strong eventual consistency: a guarantee that once any two devices have received the same set of edits, they are mathematically guaranteed to display the exact same document with zero manual conflict resolution.
- Zero data loss: local typing is saved to on-device disk immediately, and the server acknowledges an edit only after replicating it to durable storage.
- Instant local feel: local typing applies on screen in
0 ms(optimistic UI — updating the local screen before the server replies), while remote edits arrive in< 500 ms. - High availability: a server crash causes at most a brief
"Reconnecting..."indicator while users keep typing uninterrupted.
- Rich text as a character sequence: a document is an ordered string of characters where formatting (
Back-of-the-envelope numbers
Start from the prompt's numbers (
2Mconcurrent editing sessions,40 ops/minper session,500Mstored documents at50 KBaverage) and compute the rates that drive our architecture:1. Live edit operation rate Peak edit rate 2,000,000 sessions x 40 ops/min = 80M ops/min = ~1.33M ops/s Inbound bandwidth 1.33M ops/s x 50–200 B = ~70–270 MB/s (tiny bandwidth, huge op rate!) Active open documents ~2 sessions per open doc avg = ~1,000,000 open docs in RAM at peak Outbound edit fan-out ~1 other viewer/editor avg = ~1.33M op messages/s out 2. Hottest single document (100 concurrent editors) Average typing rate 100 editors x 40 ops/min = ~67 ops/s inbound (~6,600 fan-out msgs/s) Worst-case nonstop typing 100 editors x 5 keystrokes/s = ~500 ops/s inbound -> Crucial insight: 500 tiny ops/s takes < 5% of ONE CPU core! One server can sequence a whole document. 3. Ephemeral presence (cursors & selections) Throttled cursor updates 1 update per 150 ms while moving (~1 update/s avg across 2M sessions) Inbound presence rate ~2,000,000 updates/s -> outnumbers durable edits, so keep off disk! 4. Durable storage (assuming daily average load is ~1/3 of peak = ~450,000 ops/s = ~39B ops/day) Current document corpus 500M docs x 50 KB = 25 TB Append-only op log 39B ops/day x ~100 B = ~3.9 TB/day Snapshots every 100 ops (39B / 100) x 50 KB = ~19.5 TB/day (5x bigger than the op log!) Snapshots every 1,000 ops (39B / 1,000) x 50 KB = ~1.95 TB/day (10x cheaper, < 10 ms replay) 5. Fleet sizing (planning baseline) WebSocket gateways 2M sockets / 50,000 per node = 40 min -> run 60 across 3 availability zones Collaboration servers 1M open docs x ~150 KB RAM = ~150 GB RAM across 64 stateful serversFour architectural conclusions jump straight out of these numbers:
- One server can own one active document: even 100 editors typing furiously generate at most ~500 ops/s, so routing every session of
doc_idto a single document owner server eliminates cross-server locking on the hot path. - 1.33M durable writes/s is the primary backend bottleneck: we cannot run 1.33 million separate database transactions per second — we must shard the operation log and batch writes using group commit (flushing a few milliseconds of edits together in one transaction).
- Snapshot interval must be chosen by byte math: snapshotting every 1,000 ops (plus once when the last editor closes the document) saves ~17.5 TB/day of writes compared to snapshotting every 100 ops while still loading in milliseconds.
- Presence must stay in memory: 2M cursor moves/s have zero value 30 seconds later and must never touch durable databases.
- One server can own one active document: even 100 editors typing furiously generate at most ~500 ops/s, so routing every session of
API: REST for metadata, WebSocket for live editing
Use standard HTTPS REST endpoints for document management and version history, and one WebSocket (a persistent, two-way TCP connection) per open document tab for sub-second edits and cursors.
HTTPS REST API (via API Gateway) POST /v1/docs {title} -> {doc_id} GET /v1/docs/{doc_id} -> {title, role, head_rev} PUT /v1/docs/{doc_id}/acl {principal, role} GET /v1/docs/{doc_id}/versions?cursor=... -> [{end_rev, started_at, ended_at, authors, name}] GET /v1/docs/{doc_id}/versions/{rev} -> {rev, content} POST /v1/docs/{doc_id}/versions/{rev}/name {name} POST /v1/docs/{doc_id}/restore {rev} -> {new_rev} WebSocket frames: wss://collab.example.com/v1/docs/{doc_id} client -> server hello {client_id, rev, inflight: {seq, op} | null} sent on connect and reconnect op {seq, base_rev, op, selection} at most 1 unacknowledged op in flight presence {rev, anchor, head} throttled to 150 ms when idle (no inflight op) server -> client welcome {head_rev, content | ops_since_rev, peers} full snapshot if new, delta ops if reconnecting ack {seq, rev} confirms your op is durable at server revision rev op {rev, user_id, op} another editor's committed & transformed op presence {rev, cursors: [{session_id, user_id, color, anchor, head}]} coalesced every 100 ms checksum {rev, crc32} sent every 100 revisions to verify convergence error {code: FORBIDDEN | TOO_MANY_EDITORS | RELOAD}Three protocol details prevent subtle bugs:
(client_id, seq)is an idempotency key: an idempotency key is a unique identifier generated by the client before sending so retrying after a dropped connection never inserts the same words twice.base_revtells the server what the user saw: sendingbase_rev = 42tells the server "the user typed this edit while looking at revision 42," which tells the server exactly which newer revisions (43, 44, ...) to transform the edit against.- Restoring an old version is a forward edit, not a database overwrite:
POST /restorecomputes the diff from the current document back to the old version and submits it through the document owner as a brand-new operation (head_rev + 1). Active collaborators stay smoothly connected, and even a restore can be undone!
Data model
We split persistence across four stores matched to each workload:
-- 1. Relational metadata & history index: PostgreSQL (1 primary + read replicas) CREATE TABLE documents ( doc_id UUID PRIMARY KEY, owner_id BIGINT NOT NULL, title TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, deleted_at TIMESTAMPTZ ); CREATE TABLE doc_acl ( doc_id UUID NOT NULL, principal_id BIGINT NOT NULL, role TEXT NOT NULL, -- OWNER | EDITOR | COMMENTER | VIEWER PRIMARY KEY (doc_id, principal_id) ); CREATE TABLE snapshots ( doc_id UUID NOT NULL, rev BIGINT NOT NULL, -- exact revision stored at s3_key kind TEXT NOT NULL, -- LOAD (fast open) | CHECKPOINT (permanent history) s3_key TEXT NOT NULL, size_bytes INT NOT NULL, PRIMARY KEY (doc_id, rev) ); CREATE TABLE versions ( -- human-readable rows shown in the Version History sidebar doc_id UUID NOT NULL, start_rev BIGINT NOT NULL, end_rev BIGINT NOT NULL, started_at TIMESTAMPTZ NOT NULL, ended_at TIMESTAMPTZ NOT NULL, author_ids BIGINT[] NOT NULL, name TEXT, PRIMARY KEY (doc_id, end_rev) ); -- 2. Sharded Operation Log: 64 PostgreSQL shards (routed by hash(doc_id)), each with a sync standby CREATE TABLE doc_heads ( doc_id UUID PRIMARY KEY, head_rev BIGINT NOT NULL -- single-writer fencing counter per document ); CREATE TABLE ops ( doc_id UUID NOT NULL, rev BIGINT NOT NULL, -- gap-free 1, 2, 3, ... per document client_id UUID NOT NULL, client_seq BIGINT NOT NULL, user_id BIGINT NOT NULL, op BYTEA NOT NULL, -- transformed operation as committed created_at TIMESTAMPTZ NOT NULL ) PARTITION BY RANGE (created_at); -- daily partitions so 7-day cleanup is an instant DROP CREATE INDEX ops_doc_rev_idx ON ops (doc_id, rev);3. Object storage (S3) snapshots/{doc_id}/{rev}.zst compressed document state (~15–50 KB) oplog/{yyyy-mm-dd}/{doc_id}.zst archived daily op segments (kept up to day 30) 4. Ephemeral presence & event bus Redis presence:{doc_id} sorted set (member = session_id, score = heartbeat_ts, 30 s TTL) Kafka topic doc-ops keyed by doc_id; feeds version-history builder, search & archiver Browser IndexedDB local persistent queue {doc_id, client_id, rev, inflight, buffer}Why this separation works cleanly:
- The append-only
opslog is the single source of truth, and snapshots are simply a speedup cache so opening a 50,000-revision document loads the snapshot at revision50,000instead of replaying from revision1. - Gap-free per-document
rev(1, 2, 3, ...): catching up fromrev = 1200is a single fast range scan (WHERE doc_id = $1 AND rev > 1200), and any downstream consumer immediately spots a missing revision.
- The append-only
High-level architecture
Browser / Mobile Editor (Optimistic UI + local OT + IndexedDB offline queue) | HTTPS REST | WebSocket (TLS) v v +---------------+ +----------------------------------+ | API Gateway | | Stateless WebSocket Gateways (60)| +---------------+ | routes doc_id via rendezvous hash| | +----------------------------------+ v | multiplexed internal gRPC stream +--------------------+ v | Document Service | +-----------------------------------------------+ | metadata, ACLs, |--------->| Stateful Collaboration Servers (64) | | history, restore | submit | ONE active owner per open doc_id: | +--------------------+ restore | 1. dedupe -> 2. OT transform -> 3. assign rev | | | 4. 5 ms group commit -> 5. ack + broadcast | v | 6. 100 ms batched cursor presence relay | +--------------------+ +-----------------------------------------------+ | Metadata Postgres | | fenced batch | snapshots | events | 10 s TTL | docs, ACL, | v v v v | snapshots,versions | +----------------+ +--------+ +---------+ +--------------+ +--------------------+ | 64 PG Op Shards| | S3 | | Kafka | | Redis | ^ | + sync standbys| +--------+ | doc-ops | | doc list | | +----------------+ ^ +---------+ | avatars (30s)| | | | +--------------+ +-------------------------------------------+-------------+ Async workers: History Builder, Archiver, Search IndexerHow one keystroke flows end to end in ~60 ms:
- Instant local apply (
0 ms): Ana types"s". Her browser immediately inserts"s"on screen and writes the pending operation to IndexedDB (the browser's built-in on-disk database, surviving tab crashes or Wi-Fi drops). - Send with
base_rev: if no earlier edit is waiting for anack, the browser sendsop{seq, base_rev, op}over its WebSocket. - Deterministic routing: the stateless WebSocket Gateway looks up which Collaboration Server owns
doc_idusing rendezvous hashing (a hashing formula over live servers inetcdthat maps everydoc_idto one server and moves only1/Nof documents if a server joins or dies). - Single-threaded sequencing (
< 1 ms): the owner transforms Ana's op against any ops committed sincebase_rev, incrementshead_rev, updates its in-memory document, and places the op into its 5 ms group commit buffer. - Durable write before broadcast (
~5–10 ms): once the sharded PostgreSQL primary and its synchronous standby commit the batch, the owner sendsackto Ana, broadcastsopto the other 99 editors, and publishes to Kafka. - Remote reconciliation: other editors transform the incoming op against any unacknowledged local typing in their own buffers and render
"s"on screen.
- Instant local apply (
Deep dive 1: conflict resolution — Operational Transformation vs. CRDTs
Why naive index edits scramble text. Suppose the document at
rev 10is"cat"(length 3), and Ana and Ben type at the exact same millisecond:Start at rev 10: "cat" (0:'c', 1:'a', 2:'t') Ana appends 's' at index 3: wants "cats" op_A = [retain 3, insert "s"] Ben deletes 'c' at index 0: wants "at" op_B = [delete 1, retain 2] What breaks without transformation: Server applies Ben first -> "at" (length 2). Now Ana's "retain 3" points past the end of "at"! How Operational Transformation (OT) fixes both sides: transform(op_A, op_B) rewrites each op assuming the other already happened: op_A' = [retain 2, insert "s"] (shifted left by 1 because Ben deleted 'c': "at" -> "ats") op_B' = [delete 1, retain 3] (steps over Ana's new 's': "cats" -> "ats") Both editors converge to the exact same string: "ats"!Operational Transformation (OT) represents every edit as a left-to-right walk across the whole string using three tiny building blocks:
("retain", n)(keepncharacters),("insert", text)(add characters), and("delete", n)(removencharacters). Here isapplyandtransformin plain Python:from collections import deque def apply(doc, op): """Apply a full-span OT operation to `doc` and return the new string.""" pieces = [] pos = 0 for kind, value in op: if kind == "retain": pieces.append(doc[pos : pos + value]) pos += value elif kind == "insert": pieces.append(value) else: # kind == "delete": skip `value` characters without copying them pos += value if pos != len(doc): raise ValueError("Operation length does not match document length") return "".join(pieces) def consume_front(queue, count): """Consume `count` characters from the retain/delete component at queue[0].""" kind, remaining = queue[0] if remaining == count: queue.popleft() else: queue[0] = (kind, remaining - count) def transform(op_a, op_b): """Rewrite concurrent ops (op_a, op_b) made on the same revision into (op_a_prime, op_b_prime) so apply(apply(doc, op_a), op_b_prime) == apply(apply(doc, op_b), op_a_prime) (TP1). Tie-breaker when both insert at the exact same offset: op_a's text goes first.""" qa = deque(op_a) qb = deque(op_b) op_a_prime = [] op_b_prime = [] while qa or qb: # Process inserts before deletes/retains so text typed inside a deleted range survives if qa and qa[0][0] == "insert": text = qa.popleft()[1] op_a_prime.append(("insert", text)) op_b_prime.append(("retain", len(text))) # op_b must step past op_a's inserted text elif qb and qb[0][0] == "insert": text = qb.popleft()[1] op_a_prime.append(("retain", len(text))) # op_a must step past op_b's inserted text op_b_prime.append(("insert", text)) else: # Both fronts are retain or delete; advance by the smaller span kind_a, len_a = qa[0] kind_b, len_b = qb[0] step = min(len_a, len_b) consume_front(qa, step) consume_front(qb, step) if kind_a == "retain" and kind_b == "retain": op_a_prime.append(("retain", step)) op_b_prime.append(("retain", step)) elif kind_a == "delete" and kind_b == "retain": op_a_prime.append(("delete", step)) elif kind_a == "retain" and kind_b == "delete": op_b_prime.append(("delete", step)) # If both deleted the same `step` characters, neither prime needs to delete them again! return op_a_prime, op_b_primeWhy a central server makes OT simple, and why we choose OT over CRDTs here. Peer-to-peer OT requires a notorious second rule called TP2 (transforming three concurrent ops across arbitrary peer arrival orders must converge), which caused subtle bugs in early academic OT algorithms. When one Collaboration Server sequences every op for a document, every transform only ever compares a client's op against the linear server log — so TP1 (the two-operation rule above) is 100% sufficient!
Compare that against a CRDT (Conflict-free Replicated Data Type — a data structure such as RGA or Yjs that assigns every character a permanent unique ID and neighbor pointers so edits merge in any order without a central coordinator):
Dimension Centralized OT (Jupiter style) Sequence CRDT (RGA / Yjs style) Central sequencer needed? Yes (one document owner server) No; merges peer-to-peer in any order Document state overhead Zero metadata — plain text + formatting Unique ID per character/run + tombstones (hidden markers kept for deleted text) Snapshot size & load speed Compact (~50 KB plain document) Larger unless tombstones are compacted End-to-end encryption (E2EE) Impossible (server must inspect ops to transform) Supported (server relays encrypted deltas blindly) Because our product already uses a central server for permissions, history, and durability — and does not require peer-to-peer sync or E2EE — Centralized OT gives us compact 50 KB snapshots, zero tombstone bloat, and battle-tested simplicity.
Deep dive 2: Jupiter client-server sync and offline editing
The single-in-flight rule. In the Jupiter protocol, each client keeps at most one unacknowledged operation (
inflight) on the wire at a time, merging any new keystrokes typed while waiting for thatackinto a single localbuffer:[ SYNCHRONIZED ] --- user types ---> [ AWAITING_ACK ] --- user types again ---> [ AWAITING_ACK + BUFFER ] inflight = None inflight = op1 inflight = op1, buffer = op2+op3 ^ | | +----------- ack arrives -------------+------ ack arrives (send buffer!) ----------+This single constraint does two wonderful things at once: it prevents two client ops from crossing out of order on the network, and on a slow 300 ms train connection it automatically batches rapid typing into one compact operation per round trip!
class EditorClient: def __init__(self, rev, content): self.rev = rev # Latest server revision incorporated locally self.content = content # Text shown on screen right now (includes local edits) self.inflight = None # (seq, op) currently waiting for server ack, or None self.buffer = None # Composed local edits typed while inflight != None self.seq = 0 def on_local_edit(self, op): """Apply immediately for 0 ms feel, persist to IndexedDB, and send if wire is clear.""" self.content = apply(self.content, op) if self.inflight is None: self.send_op(op) elif self.buffer is None: self.buffer = op else: # Merge consecutive local edits into one op while waiting for inflight's ack self.buffer = compose(self.buffer, op) save_to_indexeddb(self) def send_op(self, op): self.seq += 1 self.inflight = (self.seq, op) ws_send({"type": "op", "seq": self.seq, "base_rev": self.rev, "op": op}) def on_server_ack(self, committed_rev): """Server confirmed `inflight` at `committed_rev`; flush `buffer` if user kept typing.""" self.rev = committed_rev self.inflight = None if self.buffer is not None: next_op = self.buffer self.buffer = None self.send_op(next_op) save_to_indexeddb(self) def on_remote_op(self, committed_rev, server_op): """Transform incoming remote edit past `inflight` AND `buffer` before applying locally. Note argument order `transform(local, server)` matches the server's `transform(client, log)`!""" if self.inflight is not None: seq, my_inflight = self.inflight my_inflight, server_op = transform(my_inflight, server_op) self.inflight = (seq, my_inflight) if self.buffer is not None: self.buffer, server_op = transform(self.buffer, server_op) self.content = apply(self.content, server_op) self.rev = committed_rev save_to_indexeddb(self)On the Collaboration Server, each document's single event loop processes incoming ops one by one:
- Deduplicate for free: scan
opsfrombase_rev + 1tohead_rev(already in memory for active docs, or loaded from Postgres/S3 if a client was offline). If any op already has(client_id, client_seq), simply re-sendack— retries never double-apply! - Transform forward: run
op, _ = transform(op, log_op)for eachrevfrombase_rev + 1tohead_rev(for an online user, usually 0–2 iterations!). - Commit before broadcast: assign
head_rev + 1and wait ~5–10 ms for the replicated group commit before sendingackor broadcastingop. Broadcasting before disk commit would risk showing collaborators a phantom revision if the server crashed a millisecond later.
Offline editing works with the exact same state machine. While offline,
inflightstays unacknowledged, every keystroke composes cleanly intobufferin IndexedDB, and on reconnecthelloreplays missed server revisions and sendsbufferas one composed operation:- 30-day automatic merge window: as long as
base_revis within our 30-day archived op log, the server transforms and merges offline edits automatically. For large offline merges (> 500changed characters), the server automatically saves a namedCHECKPOINTversion ("Before Ana's offline sync") so teammates can inspect or revert semantic clashes in one click. - Graceful fallback past 30 days or revoked permissions: if a laptop reconnects after 45 days offline (past raw op retention) or after its user's
EDITORpermission was revoked, we never drop text silently — the UI opens their offline draft side by side (or offers"Save as a new copy").
- Deduplicate for free: scan
Deep dive 3: fenced group commit, snapshots, and cursor presence
Self-fencing group commit. At ~21,000 ops/s per Collaboration Server, running one SQL transaction per keystroke would choke PostgreSQL. Instead, each server batches ops for
5 msper shard and executes a fenced CTE (Common Table Expression) per document:-- Atomically advance head_rev ONLY IF no other server took ownership since rev 1039; -- if another server took over (split-brain!), `fenced` is empty and 0 ops are inserted! WITH fenced AS ( UPDATE doc_heads SET head_rev = 1042 WHERE doc_id = $1 AND head_rev = 1039 RETURNING doc_id ) INSERT INTO ops (doc_id, rev, client_id, client_seq, user_id, op, created_at) SELECT f.doc_id, v.rev, v.client_id, v.client_seq, v.user_id, v.op, now() FROM fenced f CROSS JOIN (VALUES (1040, $2::uuid, 81, 501, $3::bytea), (1041, $4::uuid, 14, 502, $5::bytea), (1042, $2::uuid, 82, 501, $6::bytea) ) AS v(rev, client_id, client_seq, user_id, op) RETURNING rev;Why this fencing check (
WHERE head_rev = 1039) is essential: during a network hiccup, an old Collaboration Server might freeze for 6 seconds whileetcdassignsdoc_idto a new server. When the old server unfreezes and tries to flush its batch,head_revhas already moved past1039—fencedreturns zero rows, zero split-brain ops are written, other healthy documents in the 5 ms batch still commit cleanly, and the stale server drops its in-memory copy and redirects clients to the real owner.Snapshots and tiered version history
- Snapshot every 1,000 ops + on tab close: writing a 50 KB
LOADsnapshot to S3 every1,000ops (instead of every100) cuts snapshot bandwidth 10x (~2 TB/dayvs.~19.5 TB/day), and writing one snapshot when the last editor closes the document means cold opens usually replay zero ops (at worst< 1,000ops in< 10 ms). Always upload the S3 object before inserting the PostgreSQLsnapshotspointer row so readers never hit a missing S3 key. - Human-friendly versions & 30-day tiering: an async Kafka consumer groups raw keystrokes into
versionsrows (closing a version after5 minutesof idle time or30 minutesof continuous editing) and saves a compressedCHECKPOINTsnapshot in S3. Keep per-keystrokeopsin PostgreSQL for0–7 days(fast reconnects), compressed daily S3 files for7–30 days(offline sync + exact history), andCHECKPOINTsnapshots indefinitely after day 30.
Cursor and selection presence. A cursor offset like
index = 120only makes sense at a specificrev— if someone inserts 10 characters at the top of the page, that cursor belongs at130. That is why we route live cursors through the document owner on the same ordered WebSocket stream rather than an unordered side channel:- Clients throttle cursor frames to once per
150 mswhile moving (piggybacking cursor position ontoopframes while actively typing). - The owner shifts any slightly lagging cursor forward to
head_revusingtransform_cursorbelow and broadcasts one coalescedpresenceframe every100 ms(<= 10 frames/sper viewer even with 99 co-editors, instead of660 frames/s!). - Separately, every
10 sthe owner updatespresence:{doc_id}in Redis with a30 sTTL (time-to-live) to power "who's currently inside this doc" avatars on folder dashboards; if a laptop lid slams shut without closing TCP, its ghost cursor disappears automatically after 30 seconds.
def transform_cursor(index, op): """Advance a cursor offset `index` through canonical OT operation `op` (where inserts precede deletes at the same position, matching `transform`).""" chars_before_cursor = index new_index = index for kind, value in op: if chars_before_cursor < 0: break if kind == "retain": chars_before_cursor -= value elif kind == "insert": # Inserts before (or right at) the cursor push the caret right new_index += len(value) else: # kind == "delete" # Subtract only the deleted characters that lay strictly before the cursor new_index -= min(chars_before_cursor, value) chars_before_cursor -= value return new_index- Snapshot every 1,000 ops + on tab close: writing a 50 KB
Scaling, failure handling, and trade-off summary
Scaling bottlenecks and multi-region latency
- 100 editors vs. 10,000 company-wide viewers: we enforce the 100-concurrent-editor cap (the 101st person joins in
VIEWERmode). If 10,000 employees open an all-hands doc as read-only viewers, the Collaboration Server sends each committedoponce per WebSocket Gateway (~60 copies) rather than 10,000 times, and each gateway fans the bytes out to its local viewers. - Multi-region placement: a document's owner lives in the region of the first user who opens it (migrating cleanly if most active editors are on another continent). Cross-continent editors pay ~150 ms of fiber round-trip time — local typing still feels
0 msthanks to optimistic UI, and remote edits still arrive well inside< 500 ms.
Failure modes and self-healing
Failure User experience How correctness is preserved Collaboration Server crashes 2–5 s "Reconnecting..."badge; typing never pausesetcdlease expires; new owner loads latest snapshot +<= 1,000ops; clients resendinflightviahelloand(client_id, seq)deduplicatesSplit-brain during owner handoff Brief reconnect UPDATE doc_heads WHERE head_rev = expectedfences out the stale owner atomicallyOp-log Postgres primary dies 10–20 s sync pause Synchronous standby already holds every acked op; uncommittedinflightops stay in client IndexedDB and retry cleanlyKafka / Redis / S3 outage Live editing continues normally Kafka lag only delays the history sidebar; S3 skips new snapshots (cold opens replay more ops); Redis outage hides folder-view avatars only Subtle client OT bug Automatic reload Every 100 revisions, idle clients compare local crc32against the server'schecksumframe, auto-reloading and logging an alert on mismatchSummary of key trade-offs
- Centralized OT vs. CRDT: keeps documents as compact plain text (~50 KB) with simple TP1 transforms, giving up peer-to-peer offline merging and end-to-end encryption.
- Single owner per document +
doc_headsfencing: eliminates distributed locks on every keystroke (~67 ops/sfits on a fraction of a core), trading a ~2–5 s reconnect pause when an owner node dies. - Replicated group commit (
5 ms) beforeack/broadcast: adds ~5–10 ms of latency (well under< 500 ms) to guarantee zero data loss and zero phantom revisions. - Snapshots every
1,000ops + tab close, and7d / 30dtiered op retention: slashes snapshot write volume 10x (~2 TB/dayvs.~19.5 TB/day) while supporting instant cold opens and 30-day automatic offline sync.
- 100 editors vs. 10,000 company-wide viewers: we enforce the 100-concurrent-editor cap (the 101st person joins in
Intuition & how it works
Think of a collaborative document editor like a meeting room with one master whiteboard moderator, while every participant also writes on a personal scratchpad at their desk. The instant you type a letter, you write it on your desk scratchpad so your screen updates in 0 milliseconds (optimistic UI — showing local changes before the server replies). At the same time, you hand a small note to the moderator saying: "Looking at whiteboard version #10, keep the first 3 letters and insert 's'." If a teammate's note ("Looking at version #10, delete the 1st letter") reached the moderator half a millisecond earlier as version #11, the moderator adjusts your note's character offset ("keep 2 letters instead of 3, then insert 's'"), stamps it into a permanent logbook as version #12, and announces it so everyone's scratchpad converges to the exact same text.
Why do simpler approaches fail? Overwriting the whole document on each save ("last writer wins") silently erases your teammate's words whenever two people type in the same paragraph, and locking paragraphs makes collaboration feel like taking turns on a walkie-talkie. Making the screen wait for a server round-trip before showing each letter makes typing feel broken on 100 ms Wi-Fi, while sending raw character positions (insert 's' at index 3) without transforming them scrambles sentences whenever an earlier edit shifts character offsets.
Walk through a concrete 4-step trace starting from "cat" at server revision rev = 10 (0:'c', 1:'a', 2:'t'):
- Concurrent local edits (
0 msperceived lag): Ana types's'at the end (her screen immediately shows"cats", savingop_A = [retain 3, insert "s"]withbase_rev = 10to browser IndexedDB, an on-disk browser database). At the exact same moment, Ben deletes'c'at the start (his screen shows"at", sendingop_B = [delete 1, retain 2]withbase_rev = 10). - Ben arrives first ->
rev = 11: The document's single Collaboration Server seesbase_rev == head_rev (10), needs no transformation, commitsop_Basrev = 11("at"), sendsack(rev=11)to Ben, and broadcastsop_Bto Ana. - Ana arrives second -> transformed into
rev = 12: The server sees Ana'sbase_rev = 10is behindhead_rev = 11, so it runs Operational Transformation (OT) (an algorithm that shifts an operation's character spans to account for concurrent edits) againstrev = 11(op_B), rewritingop_Ainto[retain 2, insert "s"]. It commits that asrev = 12("ats"), sendsack(rev=12)to Ana, and sends[retain 2, insert "s"]to Ben. - Strong eventual consistency achieved: Meanwhile, when Ana received Ben's
op_B, her browser transformedop_Bpast her unacknowledgedop_Ainto[delete 1, retain 3]and applied it ("cats" -> "ats"), while Ben applied[retain 2, insert "s"]("at" -> "ats"). Both screens now show"ats"atrev = 12!
Key trade-offs
- Centralized Operational Transformation (OT) vs. Sequence CRDTs. With one server sequencing each document, OT stores plain text with zero per-character metadata and needs only two-operation convergence (TP1, the rule that applying A then transformed-B equals applying B then transformed-A). A CRDT (Conflict-free Replicated Data Type — a structure that gives every character a unique ID and ordering pointers so replicas merge in any order without a central server) shines for peer-to-peer sync or end-to-end encryption, but adds per-character IDs and tombstones (hidden markers kept for deleted characters) that bloat snapshots unless compacted.
- Single document owner vs. multi-node active-active writers. Routing all editors of
doc_idto one stateful Collaboration Server gives gap-free revisions (1, 2, 3, ...), lock-free sequencing (100editors average only~67 ops/s), and revision-aligned cursors. The trade-off is needing ownership handoff on deploys/crashes and a database fencing check (a conditionalUPDATE doc_heads WHERE head_rev = expectedthat blocks an evicted server during a split-brain). - Durable group commit (
~5–10 ms) before broadcast vs. broadcast immediately. Collecting 5 ms of edits into one replicated SQL batch before sendingackor broadcasting adds ~5–10 ms of latency (tiny inside a 500 ms budget), in exchange for guaranteeing zero data loss and ensuring no collaborator ever receives a phantom revision that failed to hit disk. - At most one unacknowledged op in flight per client (Jupiter protocol) vs. pipelining every keystroke. Holding new keystrokes in a local composed
bufferuntil the currentinflightop gets itsackkeeps client-server state synchronization to 3 simple states and automatically batches rapid typing on slow cellular links, at the minor cost that teammates see a remote user's typing in smooth 1-round-trip bursts (~50–100 ms). - Snapshots every
1,000ops (plus on close) vs. every100ops. Writing a 50 KB snapshot every 100 ops writes ~19.5 TB/day — 5x more bytes than the op log itself! Snapshotting every 1,000 ops plus when the last editor leaves cuts snapshot writes 10x (~2 TB/day) while keeping cold opens near-instant (0ops replayed normally,<= 1,000ops /< 10 msafter a crash). - Tiered op-log retention (
7dSQL ->30dS3 -> version checkpoints) vs. keeping every keystroke forever. Raw keystrokes grow at ~4 TB/day. Keeping 30 days of raw ops supports exact recent audit trails and automatic 30-day offline merges, while older history keeps compressed version checkpoints (5 minidle /30 minmax) at a fraction of the storage bill. - Relaying cursors through the document owner vs. Redis Pub/Sub. Sending
100 mscoalesced cursor batches over the same ordered WebSocket stream asopframes ensures cursor offsets always match the exact text revision on screen and avoids a network hop for 2M cursor moves/s; Redis is used only with a 30 s TTL (time-to-live) for lightweight "who's viewing" avatars in folder lists.
Common mistakes
- Using "last writer wins" or paragraph locks, which either silently deletes a collaborator's concurrent edits or ruins real-time flow.
- Waiting for server round-trips before updating the local editor, making typing laggy instead of applying edits optimistically in
0 msand saving them in IndexedDB. - Omitting an idempotency key
(client_id, seq)on operations, so resending an unacknowledged edit after a brief Wi-Fi drop duplicates paragraphs. - Inconsistent tie-breaking in
transform(a, b): if the server breaks same-position insert ties in favor ofclient_opwhile the client breaks ties in favor ofserver_op, their documents permanently diverge! Both sides must pass arguments in consistent priority order (and verify convergence with periodiccrc32checksums). - Broadcasting edits to peers before the durable database commit, which leaves online browsers holding a revision that disappears when someone refreshes after a server crash.
- Writing cursor presence updates to PostgreSQL or Kafka, flooding durable storage with 2,000,000 ephemeral updates/s that expire in 30 seconds anyway.
- Sending raw cursor indices without a
rev, causing remote cursors to jump onto the wrong word whenever edits happen earlier in the document. - Implementing version restore by overwriting document storage directly, which corrupts the state of every currently connected editor instead of applying restore as a normal new forward operation.
- Forgetting offline edge cases: revoked permissions while offline, laptops reconnecting after the 30-day op-log retention window, and giant offline merges that need an automatic pre-merge version checkpoint.
Follow-up questions
- How should per-user undo (Ctrl+Z) work when three collaborators are editing the same paragraph concurrently? Global undo ("revert revision 1042") would accidentally erase your coworker's typing, so collaborative undo must be per-user local undo. Whenever a user makes an edit, their client records its inverse operation in a local undo stack (saving any deleted characters so the inverse can re-insert them). When the user presses
Ctrl+Z, the client pops that inverse operation, transforms it forward through every local and remote operation that happened since then, and sends the result to the server as a brand-new forward operation (head_rev + 1). - How would you keep margin comments and suggested-edit highlights attached to the intended text span as surrounding paragraphs shift? Represent each comment anchor either as a
{start_offset, end_offset}span tied to a revision (shifted forward through every committedopusingtransform_cursor) or as invisible zero-width start/end marker characters embedded directly in the document model so standard OT moves them automatically. If another editor deletes the entire highlighted phrase (start_offset == end_offsetand surrounding text was deleted), mark the comment thread"resolved / detached"in the sidebar alongside a cached quote of the original text rather than silently losing the discussion. - Which parts of the architecture must change if enterprise tenants demand end-to-end encryption (E2EE) so servers never see plaintext? Centralized OT stops working because the server cannot inspect encrypted operations to transform character offsets. You must switch the document engine to a Sequence CRDT (such as Yjs or Automerge): clients encrypt each CRDT update delta with a document key shared only among authorized users, and the server acts as an untrusted relay and storage log that orders and stores opaque encrypted blobs and periodically asks an active client to upload a compacted, encrypted snapshot. Server-side full-text search and server-generated version diffs must either move to the client or be disabled.
Follow-up questions
- How should per-user undo (Ctrl+Z) work when three collaborators are editing the same paragraph concurrently?
- How would you keep margin comments and suggested-edit highlights attached to the intended text span as surrounding paragraphs shift?
- Which parts of the architecture must change if enterprise tenants demand end-to-end encryption (E2EE) so servers never see plaintext?
Similar questions
- Global Live Video Streaming Platform
- Durable Task Scheduler
- Incremental Sequence Numbering Across Backfills and Late Arrivals
- Thread-Safe Tumbling-Window Log Batcher
- Retry-Safe Job Worker with Jittered Backoff and DLQ
- Monthly Regional Revenue Pivot with Historical FX Rates
More Other interview questions
- Global Live Video Streaming Platform Medium
- Thread-Safe Tumbling-Window Log Batcher Medium
- Monthly Regional Revenue Pivot with Historical FX Rates Medium Pro
- Retry-Safe Job Worker with Jittered Backoff and DLQ Medium Pro
- Test Digit String Divisibility by Eight Easy Pro
- Reclaiming All Docker Host Resources Safely Easy Pro
- String Equality After Backspace Edits Medium Pro
- Markov Step Queries and Matrix Estimation Medium Pro
- Markov Chain Power and Empirical Matrix Easy Pro
- Basket Total After Single-Item Discount Medium Pro