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

  1. 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: 100M total stored documents, 1M concurrently open documents at peak, and up to 5,000 concurrent viewers (~100 simultaneously 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.
  2. 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 total
    

    Three architectural decisions fall directly out of this math:

    1. Single-writer per document is plenty fast. Even on a chaotic 100-typist document, 200 op batches/s takes 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.
    2. Hot-document fan-out is a network bottleneck, not an ordering bottleneck. Sending 1,000,000 WebSocket frames/s from one owner process is too expensive, so the owner should batch outbound ops every 50 ms and send one copy per gateway server, letting gateways fan out to their local sockets.
    3. Fleet-wide 600,000 writes/s requires sharded log storage plus group commit. Because those 600,000 writes/s are spread across ~250,000 separate documents, no single SQL server can fsync 600,000 individual transactions per second. Sharding the op log by doc_id across 32–64 partitions (~10k–20k writes/s per shard) and using WAL (Write-Ahead Log) group commit—where each database shard flushes dozens of concurrent document appends to disk in a single fsync every 1–2 ms—keeps writes both durable and fast.
  3. 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 submit has a specific correctness job:

    • rev (server revision): a strictly sequential integer (1, 2, 3, ...) per document assigned by the document's owning server. Revision n means "the exact document after applying the first n accepted operation batches."
    • base_rev: the latest server revision the client had incorporated when the user typed these edits. If the server is now at revision 1020 and receives an edit with base_rev = 1017, the server knows this edit missed revisions 1018, 1019, and 1020—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 receiving ack and it resends batch 43, the server recognizes (tab_9f2, 43) and returns the original ack instead of inserting the text twice.
  4. 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 index pos, inserting, or deleting takes O(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-character ins and del operations 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:

    1. PRIMARY KEY (doc_id, rev) guarantees two servers can never accidentally commit two different edits as revision 1018.
    2. 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.
  5. 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:

    1. Alice types "!"; her browser applies "!" locally in 0 ms and sends submit(client_seq=9, base_rev=50, ops=[...]) over her WebSocket.
    2. Alice's gateway looks up (and caches) which session server owns doc_id and forwards the submit RPC.
    3. The session server runs a single-threaded loop per doc_id: it transforms Alice's ops past any revisions committed after 50 (say 51), applies the transformed ops to its in-memory rope as rev = 52, and appends rev = 52 to doc_ops.
    4. Once the log shard confirms the durable write, the owner sends ack(client_seq=9, new_rev=52) back to Alice and includes op(rev=52, ...) in the next 50 ms broadcast batch to gateways holding peer sockets like Bob's.
    5. Bob's browser transforms rev = 52 past any unacknowledged local edits of his own and updates his screen.
  6. Deep dive 1: why raw positions fail — locks vs. OT vs. CRDTs

    Suppose both Alice and Bob start with "cat" at rev = 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's del(0) -> deletes 'c' -> gets "ats".
    • Bob ("at", length 2!) receives Alice's ins(3, "s") -> index 3 is 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 = 3 meant "after 't' in revision 7", not "at index 3 of whatever text Bob happens to have later." Once del(0) removed 'c' in front of index 3, 't' moved left by 1 slot, so Alice's insert must become ins(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 eliminates TP2 and 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.)

  7. Deep dive 2: Operational Transformation (`transform`) rules and code

    Given two operations a and b that were both authored against the exact same starting string, transform(a, b) returns a'—the rewritten version of a to run after b has 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_a
    

    Look closely at three critical bug-preventing details in transform:

    1. Tie-break on client_id (tab session ID), NEVER user_id! If Alice opens the same document on her laptop (tab_A) and tablet (tab_B) and both tabs insert at index 5 while on spotty Wi-Fi, tying on user_id would evaluate user_id < user_id as False on both sides, producing "XY" on one tab and "YX" on the other—permanent divergence! Unique client_ids guarantee a strict < ordering everywhere.
    2. Asymmetry between Case 2 (<) and Case 3 (<=). Inserting 'X' at index 1 of "ab" produces "aXb"—the old character 'b' that lived at index 1 is now at index 2 (b.pos <= a.pos shifts del(1) to del(2)), whereas an existing insert at index 1 vs del(1) stays at index 1 (b.pos < a.pos is False).
    3. Double-delete collapses to noop. If Alice and Bob both backspace the same character, b.pos == a.pos neutralizes the second delete so "cat" loses one character, not two. (For range deletes in production, if del(2, 5) overlaps a concurrent ins(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).

  8. 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 pending awaits its ack accumulate locally in buffer (and still render on screen immediately in 0 ms!).
    • As soon as ack arrives for pending, buffer is promoted to pending and 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 = rev
    

    Why 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 submits rev 8, rev 9, and rev 10. When Alice's packet arrives 3 seconds late, base_rev = 7 tells DocumentOwnerSession.submit to transform her batch across history[7:] (rev 8, 9, 10) in exact server order. Meanwhile Alice's client received rev 8, 9, 10 via on_remote_op and transformed self.pending across 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.pending is transformed forward so its base is always self.rev! On a dropped WebSocket, the client persists (rev, seq, pending, buffer) in IndexedDB, reconnects with hello(last_rev=self.rev), streams missed revisions (if one of them was its own pending batch, the server sends ack!), and if pending is still unacknowledged after catching up, resends (client_id, seq, base_rev=self.rev, ops=self.pending). Even if the ack was lost earlier, last_seen (backed by UNIQUE (doc_id, client_id, client_seq) in doc_ops) prevents double insertion.
  9. 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 the documents row whenever a new session server claims ownership:

    1. Claiming ownership: When a new session server takes over doc_id after the previous 10 s lease expires in etcd, it atomically increments owner_epoch in the database (say from 4 to 5), loads the latest snapshot from object storage plus any doc_ops rows after latest_snapshot_rev (rebuilding last_seen from those rows), and begins serving.
    2. Fenced, durable-before-ack writes: Every revision append executes as a conditional database transaction on doc_id's log shard before any ack or op frame 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 broadcast rev = 1019 from memory and crashed before COMMIT, peers would incorporate 1019 into their text while the replacement owner would assign a completely different edit to 1019, causing permanent corruption. Waiting ~5 ms for 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.
    
  10. Scaling to millions of documents, hot-document fan-out, and trade-offs

    Scaling horizontally across 100M documents (1M open):

    • Consistent hashing—mapping hash(doc_id) onto a virtual ring of the ~50 session servers—spreads the 1M active documents evenly (~20,000 docs = ~2 GB RAM 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 consume 0 B of RAM.
    • Compaction and snapshots: Every ~1,000 revisions (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 than 1,000 small ops (< 20 ms). Raw doc_ops are 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 documents and doc_ops by hash(doc_id) across 32–64 database shards reduces 600,000 fleet writes/s to ~10,000–20,000 writes/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,000 concurrent users):

    • Two-tier gateway fan-out + 50 ms batching: Instead of sending 200 ops/s x 5,000 users = 1,000,000 messages/s directly, the owner coalesces accepted revisions every 50 ms (20 batches/s) and sends one message per subscribed gateway (20 x 50 gateways = 1,000 messages/s out 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 ms read-only viewers, just as Google Docs does in massive company all-hands docs).
    • Presence throttling: 5,000 moving cursors would dwarf actual text edits. Never persist presence, throttle cursor updates to at most 2–4/s per 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 enjoy 0 ms read-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 s commit pause during rare owner crashes (masked by local buffered typing) for simple, lock-free ordering.

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:

  1. Both type locally (0 ms): Alice (tab_1) types 's' at index 3 (ins(3, 's', base_rev=7)) and immediately sees "cats". At the exact same moment, Bob (tab_2) deletes 'c' at index 0 (del(0, base_rev=7)) and immediately sees "at".
  2. Owner orders Bob first (rev 8): One dedicated server process owns this document. Bob's del(0) arrives first on base_rev = 7 (no missed edits), commits to the durable operation log as rev 8 ("at"), sends ack(rev=8) to Bob, and broadcasts del(0) to Alice.
  3. Owner transforms Alice (rev 9): Alice's ins(3, 's', base_rev=7) arrives next. Seeing base_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—shifting ins(3, 's') left by 1 past rev 8's del(0) into ins(2, 's'), applies it to "at" to produce "ats" (rev 9), sends ack(rev=9) to Alice, and broadcasts ins(2, 's') to Bob.
  4. Both screens converge: Alice transformed Bob's incoming del(0) past her pending ins(3, 's') (still del(0)) on "cats" -> "ats", while Bob applied ins(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_id to a single session server turns ordering into an in-memory counter (200 ops/s even for 100 simultaneous typists) and avoids distributed locks per keystroke. The trade-off is a brief < 10 s commit 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 local buffer while one pending batch awaits its ack guarantees 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 fsync every few milliseconds—adds ~5 ms of 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,000 ops bounds document startup and failover replay to < 20 ms, while keeping 30 days of doc_ops rows enables fast reconnect catch-up, idempotency checks, and granular version playback.
  • Two-tier gateway broadcast vs. direct owner broadcast. Batching outbound ops every 50 ms and 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 from 1,000,000 messages/s to 1,000 messages/s, trading <= 50 ms of 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_id instead of a unique per-tab client_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 del at the exact same character into a noop.
  • 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_rev and local op buffer in browser IndexedDB, then on reconnect fetch all missed doc_ops since base_rev via 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 of ins(5, "hi") is del(5, 2); the inverse of del(5, "hi") is ins(5, "hi")). Every time a remote edit from Bob arrives, Alice's client runs transform_batch over the operations sitting in her undo stack so their indices track the moving text; when Alice presses Ctrl+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 transform rules 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 (carrying comment_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 comment resolved/detached rather than silently losing the discussion thread.

Follow-up questions

Similar questions

More Retell AI interview questions

All 8 Retell AI questions →