Real-Time Multi-User Document Editing Backend
Medium · System Design · Software Engineer · Onsite
Prompt
Architect the backend service powering a live, multi-user rich-text editor where collaborators view and modify shared documents together. Center your design on the concurrency and synchronization engine that reconciles simultaneous edits rather than on browser UI details.
Your design must allow many participants to work inside the same document concurrently, broadcast peer edits with sub-second latency (a few hundred milliseconds), and guarantee convergence—meaning characters are never silently lost or duplicated, and every connected client settles on identical text once edits finish propagating. Collaborators should also be able to keep editing smoothly across high-latency links and temporary connection drops, using standard web or mobile clients over persistent channels like WebSockets.
Scope & Expectations
- System topology & persistence: How clients maintain real-time sessions, which backend services coordinate active documents, and how both current content and historical revisions are stored.
- Document & operation schema: Which data structures represent rich text in memory and how primitive edits (character insertions, deletions, and style changes) are encoded.
- Concurrency & consistency model: A deep dive into serializing or merging simultaneous edits (such as server-ordered logs, Operational Transformation, or CRDTs), guaranteeing convergence despite delayed delivery, and balancing low local typing latency against consistency.
- Scale & fault tolerance: Scaling horizontally across millions of stored documents and thousands of simultaneous viewers on a single popular document, while recovering cleanly from server crashes without losing acknowledged work.
Step-by-step walkthrough
Clarify requirements, consistency goals, and scope
The prompt asks us to focus heavily on concurrent editing, so we pin down product scope quickly and dedicate our deepest design time to the synchronization and merge protocol.
Functional requirements:
- Collaborators can join a shared document concurrently, read its live text, and edit simultaneously.
- Supported edits: inserting characters, deleting characters/ranges, and formatting text spans (bold, italic, headings, links).
- Low-latency sync: peer keystrokes and live collaborator cursors (presence) propagate to other participants within ~100–300 ms.
- Network resilience: users can keep typing through high latency or brief Wi-Fi/mobile drops (seconds to a few minutes), and their queued edits merge cleanly upon reconnect.
- Version history: users can browse and restore earlier checkpoints of a document.
Non-functional requirements:
- Convergence: once everyone stops typing and all in-flight messages are delivered, every connected client displays the exact same character sequence—no characters are silently dropped, duplicated, or scrambled.
- Intent preservation: if Alice fixes a typo in paragraph 2 while Bob deletes paragraph 1 above her, Alice's fix still lands on the exact word she intended in paragraph 2.
- Zero-latency local typing: a user's own keystrokes appear on their screen immediately (
0 ms), never blocking on a server round trip. - Durability: once the server acknowledges an edit, that edit survives server crashes and restarts.
- Scale:
100Mtotal stored documents,1Mconcurrently open documents at peak, and up to5,000concurrent viewers (~100simultaneously typing) on a single hot company-wide doc.
Key scoping assumptions confirmed up front:
- Server-mediated vs. peer-to-peer? All clients sync through our backend servers rather than direct browser-to-browser connections. Having a central server path per document dramatically simplifies edit ordering.
- Offline duration? Optimized for live editing and brief disconnects (seconds to minutes); multi-day airplane-mode editing is treated as an extension.
- Permissions? Role-based (
owner,editor,commenter,viewer), verified when opening a session and enforced before accepting any write.
Back-of-the-envelope numbers: per-document vs. fleet-wide scale
Documents & storage Total stored documents 100M docs x ~50 KB compressed snapshot = ~5 TB object storage Open documents at peak 1M docs (99% have 1-3 users; a few all-hands docs have 5,000) Connections & active typists Concurrent WebSocket sessions 3M open tabs across ~60-80 gateway servers (~40k-50k sockets/node) Users actively typing at once 10% of 3M = 300,000 typists Client keystroke batching 1 batch every ~100 ms while typing (~2 op batches/s average) Fleet-wide inbound edit rate 300,000 typists x 2 batches/s = 600,000 op batches/s Operation log throughput & memory Average op batch size ~150 bytes -> 600,000 x 150 B = 90 MB/s peak (~2.6 TB/day pre-compaction) RAM per open document on owner ~50 KB text tree + ~50 KB recent ops & client table = ~100 KB 1M open documents in RAM 1M x 100 KB = ~100 GB total across ~50 document session servers One hot document (5,000 open tabs, 100 people typing at once) Inbound ops to document owner 100 typists x 2 batches/s = 200 op batches/s (trivial for 1 CPU core!) Naive outbound broadcast 200 ops/s x 5,000 sockets = 1,000,000 messages/s (would melt 1 process!) End-to-end latency budget (same region) Author -> Gateway (30 ms) + Gateway -> Owner (1 ms) + Durable WAL append (5 ms) + Owner -> Gateways -> Peers (35 ms) = ~70-120 ms totalThree architectural decisions fall directly out of this math:
- Single-writer per document is plenty fast. Even on a chaotic 100-typist document,
200 op batches/stakes less than 5% of a single CPU thread. Assigning one owning server process per open document gives us a strict sequential edit order without distributed locks on every keystroke. - Hot-document fan-out is a network bottleneck, not an ordering bottleneck. Sending
1,000,000WebSocket frames/s from one owner process is too expensive, so the owner should batch outbound ops every50 msand send one copy per gateway server, letting gateways fan out to their local sockets. - Fleet-wide
600,000 writes/srequires sharded log storage plus group commit. Because those600,000writes/s are spread across ~250,000 separate documents, no single SQL server canfsync600,000 individual transactions per second. Sharding the op log bydoc_idacross 32–64 partitions (~10k–20k writes/sper shard) and using WAL (Write-Ahead Log) group commit—where each database shard flushes dozens of concurrent document appends to disk in a singlefsyncevery 1–2 ms—keeps writes both durable and fast.
- Single-writer per document is plenty fast. Even on a chaotic 100-typist document,
API and real-time WebSocket protocol
Clients load initial snapshots and version history over HTTP REST, and stream live edits over a WebSocket—a persistent, full-duplex TCP connection that lets client and server push small JSON/binary frames to each other instantly without HTTP polling overhead.
REST endpoints POST /v1/docs -> { doc_id } GET /v1/docs/{doc_id} -> { rev: 1017, snapshot_uri_or_body, title, role } GET /v1/docs/{doc_id}/ops?from_rev=1017&limit=500 -> [ { rev, client_id, ops } ] (reconnect catch-up) GET /v1/docs/{doc_id}/versions -> [ { rev, created_at, author_summary } ] WebSocket frames on /v1/docs/{doc_id}/stream (JWT + ACL checked during handshake) Client -> Server { type: "hello", client_id: "tab_9f2", last_rev: 1017 } Client -> Server { type: "submit", client_id: "tab_9f2", client_seq: 43, base_rev: 1017, ops: [...] } Server -> Author { type: "ack", client_seq: 43, new_rev: 1018 } Server -> Peers { type: "op", rev: 1018, author_id: "u_7", client_id: "tab_9f2", ops: [...] } Both directions { type: "presence", client_id: "tab_9f2", cursor: 120, selection: [120, 134] } Server -> Client { type: "resync", reason: "TOO_FAR_BEHIND" }Every field in
submithas a specific correctness job:rev(server revision): a strictly sequential integer (1, 2, 3, ...) per document assigned by the document's owning server. Revisionnmeans "the exact document after applying the firstnaccepted operation batches."base_rev: the latest server revision the client had incorporated when the user typed these edits. If the server is now at revision1020and receives an edit withbase_rev = 1017, the server knows this edit missed revisions1018,1019, and1020—and must be transformed across those exact three batches.(client_id, client_seq): an idempotency key—a unique identifier per browser tab (client_id) and batch number (client_seq) ensuring that if a client's connection drops before receivingackand it resends batch43, the server recognizes(tab_9f2, 43)and returns the originalackinstead of inserting the text twice.
Data model: document text, edit operations, and durable storage
In-memory document representation: Storing a 100,000-character document as a plain string makes inserting a character at index 10 copy 99,990 characters (
O(N)). Instead, both client and server store open text in a rope or piece table—a balanced binary tree of short character chunks annotated with subtree character lengths and formatting attributes ({"bold": true}). Looking up character indexpos, inserting, or deleting takesO(log N)time. Paragraph breaks and list markers are represented as structural newline characters inside the same indexed sequence so paragraphs and inline text share one unified coordinate system.Edit operations: Conceptually, every edit decomposes into positional primitives:
ins(pos, text, attrs, client_id) Insert `text` right before 0-based index `pos` del(pos, length) Delete `length` characters starting at `pos` fmt(pos, length, attr_key, val) Set formatting attribute (e.g., bold=true) across [pos, pos+length)On the wire, production editors pack a batch into compact retain / insert / delete spans (for example,
[retain(5), insert("very "), retain(12, {bold: true})]). In our merge code below, we show single-characterinsanddeloperations because the math is crystal clear and range operations follow the exact same shifting rules span by span.Persistent database schemas (sharded by
doc_id):documents doc_id PK, title, acl_id, latest_rev, owner_epoch, latest_snapshot_rev, updated_at doc_ops doc_id, rev PRIMARY KEY (doc_id, rev) client_id, client_seq UNIQUE (doc_id, client_id, client_seq) author_id, base_rev, ops_blob, created_at doc_snapshots doc_id, rev PRIMARY KEY (doc_id, rev) object_store_uri, byte_size, created_at doc_leases doc_id PK -> owner_server_id, owner_epoch, expires_at (in etcd / ZooKeeper) presence In-memory only on the document owner (never written to disk): client_id -> { user_id, cursor_pos, selection_range, color, updated_at }Notice how two database constraints enforce consistency down at the storage metal:
PRIMARY KEY (doc_id, rev)guarantees two servers can never accidentally commit two different edits as revision1018.UNIQUE (doc_id, client_id, client_seq)guarantees a retried network packet can never duplicate characters in the log, even across an owner server crash and failover.
High-level architecture: gateways and single-owner document sessions
We separate connection management (millions of idle WebSockets) from document ordering state (one active state machine per open document):
Web / Mobile Clients (optimistic local apply + 1 pending batch in flight) | | | WebSocket (/stream) | HTTPS REST (load snapshot, history) v v +-----------------------+ lookup doc_id -> owner +------------------------+ | WebSocket Gateways | --------------------------> | Coordination Service | | (~70 stateless nodes) | | (etcd: leases & epochs)| | - Terminates TLS/WS | +------------------------+ | - Local fan-out tree | ^ +-----------------------+ | renew lease every 3 s | internal RPC (submit / ack / batched op broadcast) | v | +-----------------------------------------------------------------+ | Document Session Servers (~50 stateful nodes, consistent-hashed)| | - Exactly ONE active owner process per open doc_id | | - Holds rope text, recent op ring buffer, & presence in RAM | | - Sequentially transforms ops, appends to log, emits broadcasts | +-----------------------------------------------------------------+ | | | conditional append (rev + owner_epoch) | async snapshot every ~1,000 ops v v [ Sharded Op-Log DB ] [ Object Storage (S3/GCS) ] (32-64 shards by doc_id, (Compressed full snapshots sync-replicated, WAL group commit) + compacted version history)Walk through one keystroke batch from Alice (
tab_1) while Bob (tab_2) watches:- Alice types
"!"; her browser applies"!"locally in0 msand sendssubmit(client_seq=9, base_rev=50, ops=[...])over her WebSocket. - Alice's gateway looks up (and caches) which session server owns
doc_idand forwards thesubmitRPC. - The session server runs a single-threaded loop per
doc_id: it transforms Alice's ops past any revisions committed after50(say51), applies the transformed ops to its in-memory rope asrev = 52, and appendsrev = 52todoc_ops. - Once the log shard confirms the durable write, the owner sends
ack(client_seq=9, new_rev=52)back to Alice and includesop(rev=52, ...)in the next50 msbroadcast batch to gateways holding peer sockets like Bob's. - Bob's browser transforms
rev = 52past any unacknowledged local edits of his own and updates his screen.
- Alice types
Deep dive 1: why raw positions fail — locks vs. OT vs. CRDTs
Suppose both Alice and Bob start with
"cat"atrev = 7:Initial state on all machines (rev 7): "c a t" 0 1 2 3 Alice wants "cats" -> locally runs ins(pos=3, "s") -> Alice sees "cats" Bob wants "at" -> locally runs del(pos=0) -> Bob sees "at"Watch what goes wrong if the server blindly forwards raw operations without rewriting indices:
- Alice (
"cats") receives Bob'sdel(0)-> deletes'c'-> gets"ats". - Bob (
"at", length 2!) receives Alice'sins(3, "s")-> index3is now out of bounds (or if clamped/misaligned on longer text, inserts's'inside the wrong word next door)!
Why did it break? Because
pos = 3meant "after't'in revision 7", not "at index 3 of whatever text Bob happens to have later." Oncedel(0)removed'c'in front of index3,'t'moved left by 1 slot, so Alice's insert must becomeins(pos=2, "s")when applied after Bob's delete!Let's compare the three industry mechanisms for concurrent edits:
Mechanism How it resolves concurrency Trade-offs 1. Pessimistic lock or reject Lock doc/paragraph, or reject stale Terrible UX: typing stalls on on stale base_rev base_rev and force client retry 100 ms RTT or discards work. 2. Central server sequence + Owner assigns total rev order; transform() Tiny memory & wire footprint; Operational Transformation (OT) shifts indices past missed revisions. easy server ACL/validation; [CHOSEN] Needs only TP1 property (explained next). requires server to commit. 3. CRDT (Conflict-Free Replicated Every character gets a permanent unique ID Merges in any order (great for Data Type, e.g., Yjs / RGA) (e.g. (client_id, clock)) and inserts link P2P & multi-day offline), but to left/right neighbor IDs; deletes leave adds per-char metadata + dead invisible "tombstone" markers. tombstone RAM/GC overhead.Why server-sequenced OT is the sweet spot here: Historically, OT got a reputation for complexity because decentralized peer-to-peer OT requires a tricky 3-way puzzle property called
TP2. Because every edit in our architecture passes through one owning session server per document, there is a single canonical server order—which mathematically eliminatesTP2and requires only the straightforward 2-way diamond property (TP1). We get small payloads, zero tombstone bloat, and clean server-side validation. (If requirements later shifted to peer-to-peer local-first sync or weeks of offline editing, swapping the merge engine to a run-compressed CRDT like Yjs while keeping the exact same gateway/snapshot architecture would be the right call.)- Alice (
Deep dive 2: Operational Transformation (`transform`) rules and code
Given two operations
aandbthat were both authored against the exact same starting string,transform(a, b)returnsa'—the rewritten version ofato run afterbhas already been applied. Convergence requires the TP1 diamond equation:Starting doc: "cat" (rev 7) / \ Alice: a = ins(3,'s') Bob: b = del(0) / \ "cats" "at" \ / b' = transform(b, a) = del(0) a' = transform(a, b) = ins(2,'s') \ / v v Final converged doc: "ats"In plain formula form:
apply(apply(doc, a), transform(b, a)) == apply(apply(doc, b), transform(a, b)).Here is the complete, self-contained transformation logic:
from dataclasses import dataclass, replace @dataclass(frozen=True) class Op: kind: str # "ins", "del", or "noop" pos: int # 0-based character index in the base text char: str = "" # character to insert when kind == "ins" client_id: str = "" # unique per browser tab/session (breaks ties deterministically!) def apply_ops(text: str, ops: list[Op]) -> str: """Apply a sequential list of single-character operations to `text`.""" for op in ops: if op.kind == "ins": text = text[:op.pos] + op.char + text[op.pos:] elif op.kind == "del": text = text[:op.pos] + text[op.pos + 1:] return text def transform(a: Op, b: Op) -> Op: """Rewrite op `a` so it preserves its intent when applied AFTER `b` (assuming `a` and `b` were both created on the same starting text).""" if a.kind == "noop" or b.kind == "noop": return a # Case 1: Insert vs. Insert # If `b` inserted strictly before `a`, `a` shifts right by 1. # If both inserted at the EXACT same index, break the tie deterministically # using unique per-tab `client_id` so every machine picks the same winner! if a.kind == "ins" and b.kind == "ins": if b.pos < a.pos or (b.pos == a.pos and b.client_id < a.client_id): return replace(a, pos=a.pos + 1) return a # Case 2: Insert vs. Delete # If `b` deleted a character strictly before `a`'s insertion point, shift left by 1. if a.kind == "ins" and b.kind == "del": if b.pos < a.pos: return replace(a, pos=a.pos - 1) return a # Case 3: Delete vs. Insert # If `b` inserted at or before the character `a` wants to delete, that target # character shifted right by 1 (note `<=`: inserting AT pos pushes existing char right!). if a.kind == "del" and b.kind == "ins": if b.pos <= a.pos: return replace(a, pos=a.pos + 1) return a # Case 4: Delete vs. Delete if b.pos < a.pos: return replace(a, pos=a.pos - 1) if b.pos == a.pos: # Both users deleted the exact same character! Turn the second into a no-op # so we do NOT accidentally delete the neighboring character instead. return replace(a, kind="noop") return a def transform_batch(a_ops: list[Op], b_ops: list[Op]) -> tuple[list[Op], list[Op]]: """Transform two multi-op batches made on the same starting text across each other. Returns (a_after_b, b_after_a).""" cur_a = list(a_ops) b_after_a: list[Op] = [] for b in b_ops: next_a: list[Op] = [] cur_b = b for a in cur_a: next_a.append(transform(a, cur_b)) cur_b = transform(cur_b, a) cur_a = next_a b_after_a.append(cur_b) return cur_a, b_after_aLook closely at three critical bug-preventing details in
transform:- Tie-break on
client_id(tab session ID), NEVERuser_id! If Alice opens the same document on her laptop (tab_A) and tablet (tab_B) and both tabs insert at index5while on spotty Wi-Fi, tying onuser_idwould evaluateuser_id < user_idasFalseon both sides, producing"XY"on one tab and"YX"on the other—permanent divergence! Uniqueclient_ids guarantee a strict<ordering everywhere. - Asymmetry between Case 2 (
<) and Case 3 (<=). Inserting'X'at index1of"ab"produces"aXb"—the old character'b'that lived at index1is now at index2(b.pos <= a.posshiftsdel(1)todel(2)), whereas an existing insert at index1vsdel(1)stays at index1(b.pos < a.posisFalse). - Double-delete collapses to
noop. If Alice and Bob both backspace the same character,b.pos == a.posneutralizes the second delete so"cat"loses one character, not two. (For range deletes in production, ifdel(2, 5)overlaps a concurrentins(4, "hi"), the range delete splits into two deletes around"hi"so newly typed text is never swallowed.)
Formatting spans (
fmt) shift their[pos, pos + length)endpoints by the exact same insert/delete rules. If two users concurrently set"bold"to different values on overlapping characters, the batch assigned the higher server revision wins (when a client transforms an incoming server op past its own unacknowledged local op—which will receive an even higher server revision later—the local op keeps priority on the overlap).- Tie-break on
Deep dive 3: client-server sync (`pending` + `buffer`) and delayed messages
Even with a bug-free
transform(), naive client networking can diverge if a client fires off 5 separate unacknowledged packets in a row and transforms incoming remote edits in a different 2D order than the server. Google Docs solves this with the Jupiter single-in-flight-batch invariant:- Each client holds at most one unacknowledged batch on the wire (
pending). - Any new keystrokes typed while
pendingawaits itsackaccumulate locally inbuffer(and still render on screen immediately in0 ms!). - As soon as
ackarrives forpending,bufferis promoted topendingand sent as a single batch.
Client local document invariant at all times: client.text == apply_ops(apply_ops(server_text_at[client.rev], client.pending), client.buffer)class DocumentOwnerSession: """Single-threaded state machine running on the server that owns one open document.""" def __init__(self, initial_text: str): self.text = initial_text # history[r] stores the transformed op batch that moved rev r -> rev r + 1 self.history: list[list[Op]] = [] # Deduplication map: client_id -> (last_client_seq, assigned_rev) self.last_seen: dict[str, tuple[int, int]] = {} def submit( self, client_id: str, client_seq: int, base_rev: int, ops: list[Op] ) -> tuple[int, list[Op] | None]: # Idempotency guard: if client retried an already-applied batch after reconnect prev = self.last_seen.get(client_id) if prev is not None and client_seq <= prev[0]: return prev[1], None # Transform incoming ops across every server revision the client had not seen yet transformed = ops for missed_batch in self.history[base_rev:]: transformed, _ = transform_batch(transformed, missed_batch) self.text = apply_ops(self.text, transformed) self.history.append(transformed) new_rev = len(self.history) self.last_seen[client_id] = (client_seq, new_rev) # In production: append to durable op-log shard BEFORE returning ack/broadcast! return new_rev, transformed class EditorClient: """Client-side state machine keeping 0 ms local typing in sync with the owner.""" def __init__(self, client_id: str, initial_text: str, rev: int): self.client_id = client_id self.text = initial_text self.rev = rev self.pending: list[Op] = [] # At most 1 batch in flight awaiting server ack self.buffer: list[Op] = [] # Local edits typed while `pending` is in flight self.seq = 0 def on_local_keystroke(self, ops: list[Op]) -> None: # Optimistic apply: user sees their keystroke in 0 ms self.text = apply_ops(self.text, ops) self.buffer.extend(ops) def flush_to_network(self) -> tuple[str, int, int, list[Op]] | None: if self.pending or not self.buffer: return None self.pending, self.buffer = self.buffer, [] self.seq += 1 return self.client_id, self.seq, self.rev, list(self.pending) def on_server_ack(self, new_rev: int) -> None: self.rev = new_rev self.pending = [] def on_remote_op(self, rev: int, remote_ops: list[Op]) -> None: # Slide the incoming server batch across `pending`, then across `buffer` self.pending, remote_after_pending = transform_batch(self.pending, remote_ops) self.buffer, remote_for_screen = transform_batch(self.buffer, remote_after_pending) self.text = apply_ops(self.text, remote_for_screen) self.rev = revWhy network delays and disconnects never break convergence:
- Delayed / out-of-order arrivals across users: Suppose Alice (
base_rev = 7) is on slow satellite Wi-Fi while Bob submitsrev 8,rev 9, andrev 10. When Alice's packet arrives 3 seconds late,base_rev = 7tellsDocumentOwnerSession.submitto transform her batch acrosshistory[7:](rev 8, 9, 10) in exact server order. Meanwhile Alice's client receivedrev 8, 9, 10viaon_remote_opand transformedself.pendingacross those exact same three batches in the exact same order. - Reconnect & retry: Notice a subtle invariant in
on_remote_op: every time a remote revision arrives,self.pendingis transformed forward so its base is alwaysself.rev! On a dropped WebSocket, the client persists(rev, seq, pending, buffer)inIndexedDB, reconnects withhello(last_rev=self.rev), streams missed revisions (if one of them was its ownpendingbatch, the server sendsack!), and ifpendingis still unacknowledged after catching up, resends(client_id, seq, base_rev=self.rev, ops=self.pending). Even if theackwas lost earlier,last_seen(backed byUNIQUE (doc_id, client_id, client_seq)indoc_ops) prevents double insertion.
- Each client holds at most one unacknowledged batch on the wire (
Reliability, fencing stale owners, and crash recovery
Having a single owning session server per open document makes ordering simple, provided we guard against split-brain—where an old owner server freezes during a garbage-collection pause or network partition, loses its lease, wakes up 12 seconds later, and tries to keep writing revisions alongside the new owner.
We prevent split-brain with lease epochs (fencing tokens)—a monotonically increasing integer (
owner_epoch = 1, 2, 3, ...) stored on thedocumentsrow whenever a new session server claims ownership:- Claiming ownership: When a new session server takes over
doc_idafter the previous10 slease expires in etcd, it atomically incrementsowner_epochin the database (say from4to5), loads the latest snapshot from object storage plus anydoc_opsrows afterlatest_snapshot_rev(rebuildinglast_seenfrom those rows), and begins serving. - Fenced, durable-before-ack writes: Every revision append executes as a conditional database transaction on
doc_id's log shard before anyackoropframe leaves the owner:
BEGIN; UPDATE documents SET latest_rev = 1019 WHERE doc_id = 'doc_42' AND latest_rev = 1018 AND owner_epoch = 5; -- Rejects zombie owner still holding epoch 4! -- Abort if UPDATE matched 0 rows! INSERT INTO doc_ops (doc_id, rev, client_id, client_seq, author_id, base_rev, ops_blob) VALUES ('doc_42', 1019, 'tab_9f2', 43, 'u_7', 1017, ...); COMMIT;Why never broadcast before
COMMIT? If an owner broadcastrev = 1019from memory and crashed beforeCOMMIT, peers would incorporate1019into their text while the replacement owner would assign a completely different edit to1019, causing permanent corruption. Waiting~5 msfor the sharded WAL commit guarantees acknowledged history never rolls back.Failure event System recovery Data lost? Client Wi-Fi drops (30 s) Edits stay in local buffer/IndexedDB; hello(last_rev) Zero catches up and resends pending with same client_seq. Gateway node crashes Clients auto-reconnect to another gateway in ~1-2 s. Zero Document owner crashes 10 s lease expires; new owner bumps epoch + 1, loads Zero (clients keep snapshot + tail ops; clients replay unacked pending. typing locally!) Stalled "zombie" owner wakes DB rejects its UPDATE (owner_epoch mismatch); zombie Zero drops memory state and closes internal RPC channel.- Claiming ownership: When a new session server takes over
Scaling to millions of documents, hot-document fan-out, and trade-offs
Scaling horizontally across 100M documents (
1Mopen):- Consistent hashing—mapping
hash(doc_id)onto a virtual ring of the ~50 session servers—spreads the1Mactive documents evenly (~20,000docs =~2 GBRAM per server), and adding or removing one server migrates only~2%of open documents via graceful lease handoff (write snapshot -> release lease -> reload on new node). Idle documents consume0 Bof RAM. - Compaction and snapshots: Every
~1,000revisions (and when the last active tab closes), a background worker serializes a fresh snapshot to object storage so opening or failing over a document never replays more than1,000small ops (< 20 ms). Rawdoc_opsare retained for 30 days to support reconnect catch-up and fine-grained playback, then compacted into coarser version-history checkpoints. - Sharded op log with group commit: Partitioning
documentsanddoc_opsbyhash(doc_id)across 32–64 database shards reduces600,000fleet writes/s to~10,000–20,000writes/s per shard, where storage-level WAL group commit batches concurrent appends into 1 disk flush every 1–2 ms; on a single hot document (200 ops/s), the owner also batches multiple ops arriving during an in-flight DB write into the next revision transaction.
Scaling a single hot document (
5,000concurrent users):- Two-tier gateway fan-out + 50 ms batching: Instead of sending
200 ops/s x 5,000 users = 1,000,000messages/s directly, the owner coalesces accepted revisions every50 ms(20 batches/s) and sends one message per subscribed gateway (20 x 50 gateways = 1,000 messages/sout of the owner—a 1,000x reduction!). Each gateway then writes the frame to its local ~70–100 client sockets. - Editor cap + viewer tiering: Cap simultaneous write sessions per document at ~200–300 active editors (promoting additional joiners to low-frequency
100–200 msread-only viewers, just as Google Docs does in massive company all-hands docs). - Presence throttling:
5,000moving cursors would dwarf actual text edits. Never persist presence, throttle cursor updates to at most2–4/sper active editor, coalesce superseded cursor positions on the gateway, and render read-only viewers as an aggregate avatar count.
Consistency and performance summary:
- Strong per-document sequential log, optimistic eventual screens: Every document has one linearizable revision history (
rev 1..N) in storage, while clients enjoy0 msread-your-writes locally and converge to identical screens within one round trip (~100 ms) once typing pauses. - Core trade-offs: Server-sequenced OT trades offline peer-to-peer autonomy (where CRDTs shine) for tiny document memory, zero tombstone garbage collection, and simple server-side access control; single-owner leases trade a brief
< 10 scommit pause during rare owner crashes (masked by local buffered typing) for simple, lock-free ordering.
- Consistent hashing—mapping
Intuition & how it works
Imagine two editors revising the same sentence on separate notepads while a single coordinator keeps an official, sequentially numbered ledger of edits. To make typing feel effortless, each editor writes directly on their own page in 0 ms and mails instructions like "insert 's' at slot 3" to the coordinator; if someone else's instruction ("delete slot 0") entered the ledger one moment earlier, the coordinator simply shifts the slot number (3 -> 2) before applying it, just like updating a seat number after a chair is removed from the front of a row.
Naive ways of sharing a document fail fast in real-time collaboration. Overwriting the whole file on every save ("last writer wins") silently erases a teammate's paragraph, while locking the document forces every keystroke to stall on a 100 ms network round trip. Even broadcasting raw character operations (insert(3, 's') and delete(0)) directly between browsers breaks because character positions only make sense relative to the exact revision the author was looking at when they typed.
Trace a concrete two-user example starting from "cat" at server revision rev 7:
- Both type locally (
0 ms): Alice (tab_1) types's'at index3(ins(3, 's', base_rev=7)) and immediately sees"cats". At the exact same moment, Bob (tab_2) deletes'c'at index0(del(0, base_rev=7)) and immediately sees"at". - Owner orders Bob first (
rev 8): One dedicated server process owns this document. Bob'sdel(0)arrives first onbase_rev = 7(no missed edits), commits to the durable operation log asrev 8("at"), sendsack(rev=8)to Bob, and broadcastsdel(0)to Alice. - Owner transforms Alice (
rev 9): Alice'sins(3, 's', base_rev=7)arrives next. Seeingbase_rev = 7 < 8, the server runs Operational Transformation (OT)—a function that adjusts an edit's character index to account for concurrent edits that landed before it—shiftingins(3, 's')left by 1 pastrev 8'sdel(0)intoins(2, 's'), applies it to"at"to produce"ats"(rev 9), sendsack(rev=9)to Alice, and broadcastsins(2, 's')to Bob. - Both screens converge: Alice transformed Bob's incoming
del(0)past her pendingins(3, 's')(stilldel(0)) on"cats"->"ats", while Bob appliedins(2, 's')to"at"->"ats". Both screens show"ats"with zero lost or duplicated characters.
Key trade-offs
- Server-sequenced OT vs. CRDTs. With a central document owner assigning one revision order, OT only needs a simple two-way diamond property (
TP1), keeps document state compact, and lets the server validate permissions on every edit, at the cost of needing the server reachable to commit. CRDTs (Conflict-Free Replicated Data Types)—data structures that attach a permanent unique ID to every character and keep invisible "tombstone" markers for deleted characters so edits merge in any order—shine for peer-to-peer or multi-day offline editing, but cost extra per-character memory and tombstone garbage collection. - Single owner per document vs. multi-server active-active writes. Routing all edits for one
doc_idto a single session server turns ordering into an in-memory counter (200 ops/seven for 100 simultaneous typists) and avoids distributed locks per keystroke. The trade-off is a brief< 10 scommit pause if that owner server crashes while its lease expires—masked on the client because users continue typing into their local buffer. - Optimistic local apply (
0 ms) vs. synchronous server confirmation. Applying keystrokes locally before the server responds makes typing feel native even across continents, at the cost of momentary screen divergence (~50–150 ms) and running OT on the client as well as the server. - At most one unacknowledged batch in flight (
pending+buffer) vs. pipelining every keystroke. Holding new keystrokes in a localbufferwhile onependingbatch awaits itsackguarantees client and server transform across the exact same sequence of edits without complex multi-state tracking, adding at most one network round trip to how fast collaborators see your next burst. - Acknowledge after durable log write vs. acknowledge from RAM. Appending each revision to a replicated WAL (Write-Ahead Log)—an append-only disk log where database shards batch concurrent writes into a single
fsyncevery few milliseconds—adds~5 msof latency, but guarantees that an acknowledged edit can never disappear and cause connected clients to diverge after a server crash. - Append-only op log + periodic snapshots vs. storing only the latest text. Saving snapshots every
~1,000ops bounds document startup and failover replay to< 20 ms, while keeping 30 days ofdoc_opsrows enables fast reconnect catch-up, idempotency checks, and granular version playback. - Two-tier gateway broadcast vs. direct owner broadcast. Batching outbound ops every
50 msand sending one frame per WebSocket gateway (a server holding persistent two-way browser connections) cuts a 5,000-viewer hot document's outbound load on the owner from1,000,000messages/s to1,000messages/s, trading<= 50 msof visual batching delay for 1,000x scalability.
Common mistakes
- Forwarding raw character indices without transforming them, causing concurrent edits to land inside the wrong word or crash with out-of-bounds indices.
- Overwriting the whole document ("last writer wins") or locking paragraphs, which either silently deletes a collaborator's typing or freezes the editor on every network hiccup.
- Breaking insert ties with
user_idinstead of a unique per-tabclient_id, which causes permanent text divergence whenever the same user edits a document in two browser tabs at once. - Letting a double-delete shift and erase a neighboring character, instead of turning the second concurrent
delat the exact same character into anoop. - Streaming multiple unacknowledged batches from one client without queuing (
pending+buffer), breaking the 2D transformation symmetry between client and server. - Broadcasting an edit to peers before the database log write commits, so an owner crash leaves browsers holding an edit that the replacement server never heard of.
- Skipping idempotency keys
(client_id, client_seq)or fencing tokens (owner_epoch), allowing a retried packet after a Wi-Fi drop to duplicate text or a stalled old server ("zombie") to overwrite a new owner's revision number. - Persisting or unthrottled-broadcasting cursor movements, letting 5,000 moving cursors generate 25x more traffic than the actual text edits.
Follow-up questions
- How would your architecture change if collaborators needed to edit documents offline during multi-hour flights or multi-day disconnects? Our OT client can persist its
base_revand local op buffer in browserIndexedDB, then on reconnect fetch all misseddoc_opssincebase_revvia paginated REST calls and transform its offline ops locally before submitting—as long as the offline period is shorter than our 30-day raw op-log retention window. However, rebasing thousands of positional edits across days of heavy structural changes can produce confusing human merges (such as editing a sentence inside a paragraph a coworker deleted), so if multi-day offline editing is a core requirement, switching the document model to a run-compressed CRDT (like Yjs or Automerge) and presenting a visual "review merged offline changes" diff on reconnect is much cleaner. - How should per-user undo (
Ctrl+Z) work so that reverting my own recent typing never erases edits a teammate made moments later? Global revision rollback would erase Bob's work, so each client maintains a personal undo stack storing the inverse of Alice's own batches (the inverse ofins(5, "hi")isdel(5, 2); the inverse ofdel(5, "hi")isins(5, "hi")). Every time a remote edit from Bob arrives, Alice's client runstransform_batchover the operations sitting in her undo stack so their indices track the moving text; when Alice pressesCtrl+Z, her client pops the already-transformed inverse and submits it as a brand-new forward edit (rev N + 1), ensuring everyone converges normally. - How do live collaborator cursors, text selections, and anchored margin comments stay aligned as paragraphs above them are edited or deleted? Model every cursor or selection endpoint as a zero-width position marker and shift it through the exact same
transformrules as an insert (edits before it shift it right or left; deleting across a selection shrinks it). Ephemeral cursors stay in memory only, whereas durable inline comments are stored directly inside the document's formatting/annotation spans (carryingcomment_id) so every text transformation and snapshot automatically moves and saves the comment's anchor; if a user deletes the entire highlighted phrase, mark the commentresolved/detachedrather than silently losing the discussion thread.
Follow-up questions
- How would your architecture change if collaborators needed to edit documents offline during multi-hour flights or multi-day disconnects?
- How should per-user undo (`Ctrl+Z`) work so that reverting my own recent typing never erases edits a teammate made moments later?
- How do live collaborator cursors, text selections, and anchored margin comments stay aligned as paragraphs above them are edited or deleted?
Similar questions
- Multi-Tenant Programmatic Outbound Calling Platform
- Smooth Multi-Tenant Outbound Call Pacing Engine
- Extensible In-Memory SQL Query Engine
- Voice Agent Webhook Tools for Customer Issue Tracking
- Translating Technical Trade-Offs for Business Stakeholders
- Stack-Based Postfix Integer Interpreter
More Retell AI interview questions
- Translating Technical Trade-Offs for Business Stakeholders Easy
- Stack-Based Postfix Integer Interpreter Easy
- Voice Agent Webhook Tools for Customer Issue Tracking Medium Pro
- Multi-Tenant Programmatic Outbound Calling Platform Hard Pro
- Smooth Multi-Tenant Outbound Call Pacing Engine Medium Pro
- Extensible In-Memory SQL Query Engine Hard Pro
- Multi-Column Range Queries on Static Records Medium Pro