Real-Time Collaborative Document Editor Backend

Medium · System Design · Software Engineer · Onsite

Prompt

Architect the real-time collaboration backend for a browser-based shared document editor where multiple authors open and type into the same document concurrently. Every participant sees their own typing instantaneously on screen (0 ms local echo), observes collaborators' text changes and cursor positions within moments, and converges to identical document content backed by durable storage and version history. Keep standard control-plane plumbing—such as user accounts, file creation, and sharing ACLs—brief so your design focuses deeply on live collaboration and distributed state management.

Modeling assumptions and open questions to clarify: - Character-sequence document model: Treat the document body as an ordered list of characters; rich-text styling (bold, links, headings) can be represented as key-value attributes over character spans. - Scale and fan-out: Establish typical versus peak simultaneous editors on a single document alongside total concurrently open documents system-wide. - Latency and offline behavior: Define the target edit-propagation latency between co-editors and whether authors can continue typing offline with automatic reconciliation on reconnect. - Collaboration scope and crash durability: Clarify how revision history (vs. comments or suggestion mode) fits in, and guarantee whether every server-acknowledged edit must survive node crashes.

Scope & Expectations

  • Concurrent edit convergence: Specify the conflict-resolution model (such as Operational Transformation or CRDTs), where transformation/merging executes, and how simultaneous edits at identical character offsets converge.
  • Session routing and presence: Design how live document sessions map to backend servers, how cursor presence is broadcast, and how stale servers are fenced during failovers.
  • Operation storage and fast loading: Detail what gets persisted per edit versus periodically snapshotted so documents with years of edit history still open quickly.
  • Disconnect and crash recovery: Trace how clients and servers recover cleanly from flaky networks, offline editing sessions, and session-host crashes without losing acknowledged work.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Storing static text files is easy; the hard part of a Google Docs-style backend is real-time convergence: letting several people type into the exact same sentence at the exact same millisecond—each seeing their own keystrokes instantly on screen—and guaranteeing that every browser tab ends up with the exact same character sequence without losing any acknowledged work.

    Keep control-plane plumbing (user accounts, folder listings, permission sharing) brief—a standard REST API over a relational database—and spend our interview depth on the collaboration engine.

    Functional requirements

    • Instant local typing + real-time collaboration: A user's own keystrokes appear on screen in 0 ms without waiting for a network round trip, while collaborators see those edits and live cursors within moments.
    • Strong eventual convergence: Once edits stop arriving, every connected user's document copy converges to the exact same text and formatting.
    • Durable persistence & revision history: Every acknowledged edit is saved durably; users can browse historical versions and restore an earlier revision without destroying intermediate history.
    • Document representation: Model the document as an ordered sequence of characters; rich-text formatting (bold, italic, links) attaches as key-value attribute maps on character ranges.

    Clarifying questions and design assumptions

    • Concurrency per document & fleet scale: Typically 1–5 simultaneous editors per document; up to 100 active editors in the worst case (beyond 100, extra joiners enter read-only viewer mode). 1,000,000 documents open concurrently at peak.
    • Collaboration latency target: Under 500 ms (p99) between collaborators in the same region.
    • Offline support: Yes—users can keep typing during temporary disconnects (up to ~1 hour), storing unacknowledged edits locally in browser IndexedDB and merging cleanly on reconnect.
    • Durability guarantee: Zero acknowledged edits lost across process or availability-zone crashes. Any edit not yet acknowledged by the server remains safely buffered on the client tab and resends automatically.

    Non-functional requirements

    • Fast document open regardless of age: Opening a 5-year-old document with 500,000 past edits must still take < 200 ms server-side.
    • High availability: If the server hosting a live document crashes, clients reconnect transparently within a few seconds with zero lost keystrokes.
  2. Back-of-the-envelope numbers

    Size both the single-document loop (which decides whether one server can sequence a document) and the aggregate fleet load (which decides storage and sharding).

    1. Connections & active typing rate
       Open documents at peak          1,000,000 documents
       Connected tabs per open doc     ~1.3 average -> ~1,300,000 open WebSocket connections
       Actively typed-in documents     assume 10% at any second -> ~100,000 active typists
       Operation batch rate per typist client keeps <= 1 batch in flight (~1 batch every 300 ms)
                                       -> ~3 op messages/s per active typist
       Fleet-wide operation rate       100,000 typists x 3 ops/s = ~300,000 ops/s at peak
    
    2. Storage write rate & daily growth
       Encoded op row size             ~200 bytes (doc_id, rev, op spans, author, client_id, seq, ts)
       Peak op-log write throughput    300,000 ops/s x 200 B = ~60 MB/s
       Daily op-log volume             60 MB/s x 86,400 s = ~5.2 TB/day at 24h peak;
                                       at ~1/3 daily average utilization -> ~1.7 TB/day
    
    3. Memory & fast-open math
       Per open doc in server RAM      current text (~50 KB) + last 1,000 ops (~200 KB) = ~250 KB
       1,000,000 open docs in RAM      1,000,000 x 250 KB = ~250 GB total (~1.25 GB across 200 servers)
       Snapshot every 500 ops          300,000 ops/s / 500 = ~600 background snapshot writes/s (~30 MB/s)
       Cost to open ANY document       1 snapshot (~50 KB) + <= 500 tail ops (~100 KB) = ~150 KB read!
    

    Three architectural truths fall directly out of these numbers: 1. One document is tiny: Even 100 simultaneous editors typing nonstop generate only 100 x 3 = 300 ops/s—trivial for a single in-memory server process. Routing all editors of one document to a single owner process is completely feasible! 2. Fleet write rate is huge: 300,000 durable appends/s require a horizontally partitioned distributed database keyed by doc_id. 3. Snapshots decouple open speed from history length: Capping tail replay at 500 ops guarantees a 5-year-old novel opens just as fast as a brand-new note.

  3. API and WebSocket wire protocol

    Control plane (REST, brief): POST /v1/docs, GET /v1/docs/{id} (metadata), PUT /v1/docs/{id}/acl (Access Control List—who may view or edit, verified when joining a session).

    Real-time collaboration protocol runs over WebSockets (persistent two-way TCP connections between browser tab and server so edits flow both ways without HTTP header overhead):

    Client -> Server
      join      { doc_id, client_id, last_seen_rev? }
      submit_op { doc_id, client_id, client_seq: 42, base_rev: 1907,
                  op: [retain(120), insert("hello"), retain(3150)] }
      presence  { doc_id, rev: 1907, cursor: { anchor: 125, head: 125 } }
      checksum  { doc_id, rev: 2000, sha256_prefix }      // periodic sanity check every 100 revs
    
    Server -> Client
      joined    { head_rev: 1907, snapshot_or_missed_ops, active_editors: [...] }
      ack       { client_seq: 42, assigned_rev: 1908 }
      remote_op { rev: 1909, author_id, client_id, client_seq, op: [...] }
      presence  { user_id, rev, cursor }
      resync    { reason }                                // forces clean snapshot reload on checksum mismatch
    

    Revision history REST API (served by stateless history readers, off the live edit path):

    GET  /v1/docs/{id}/revisions?before_rev=2000&limit=50   -> grouped timeline entries for sidebar
    GET  /v1/docs/{id}/content?rev=1450                     -> reconstructed document at rev 1450
    POST /v1/docs/{id}/restore  { target_rev: 1450, idempotency_key }
    

    Why every field in submit_op matters: - base_rev tells the server which exact document revision the client was looking at when it generated op, so the server knows which newer concurrent revisions (base_rev + 1 .. head_rev) op must be adjusted against. - (client_id, client_seq) uniquely identifies the edit so retries after a Wi-Fi drop or server failover are never applied twice. Notice remote_op echoes (client_id, client_seq) too: if the server saved an edit right before a disconnect and the ack was lost, the reconnecting client recognizes its own (client_id, client_seq) in the catch-up stream and treats it as an ack instead of inserting "hello" twice! - Span-based operations (retain(n) skips n characters, insert(s) inserts text, delete(n) deletes n characters) describe edits across the full document length so multiple keystrokes while waiting for an ack compose cleanly into a single compact batch.

  4. Data model

    documents (relational control-plane DB)
      doc_id PK, owner_id, title, home_region, latest_snapshot_rev, created_at
    
    doc_ops (distributed partitioned wide-column / KV store, partitioned by doc_id, sorted by rev)
      PRIMARY KEY (doc_id, rev)
      op_bytes, author_id, client_id, client_seq, created_at
      -- Always written via conditional append: INSERT ONLY IF (doc_id, rev) DOES NOT EXIST!
    
    doc_snapshots (metadata in DB; payload in S3/GCS Object Storage)
      PRIMARY KEY (doc_id, rev)
      object_key ("docs/{doc_id}/snapshots/{rev}.bin"), byte_size,
      recent_client_seqs_json,   -- maps { client_id -> [last_client_seq, assigned_rev] }
      created_at
    
    revision_groups (built asynchronously by background history indexer)
      PRIMARY KEY (doc_id, start_rev)
      end_rev, author_ids[], started_at, ended_at, custom_label NULL
    
    shard_leases (etcd / ZooKeeper coordination store, 4,096 virtual shards)
      shard_id (0..4095) -> { owner_server_id, epoch, lease_expires_at }
    

    Key design choices in this schema: - The append-only doc_ops log is the single source of truth: Revision R of a document is defined mathematically as applying rev 1 .. R in order. Snapshots are purely read-acceleration caches that can always be regenerated from doc_ops. - Conditional insert on (doc_id, rev) doubles as our split-brain fence: Because the database allows each (doc_id, rev) slot to be written at most once, two servers that briefly disagree about shard ownership can never silently overwrite each other's revisions. - Cursors (presence) are never written to disk: Cursor coordinates are ephemeral (short-lived in-memory state rebuilt within a second after reconnect).

  5. High-level architecture

      [ Browser Tab ]
        Instant local echo + 3-state OT buffer + IndexedDB crash/offline persistence
            |
            | Persistent WebSocket (TLS)
            v
      [ Stateless Edge Gateways (~50 nodes, ~26k WebSockets each) ]
        Authenticates user, checks ACL on join, routes doc_id -> hash(doc_id) % 4096 -> Owner Server
            |                                                       ^
            | internal RPC stream                                   | watch shard map (4,096 entries)
            v                                                       |
      [ Stateful Session Servers (~200 nodes) ] <---------> [ Coordination Store (etcd) ]
        Single active owner per document shard.               (10s shard leases, renewed every 3s)
        Holds in RAM per open doc (~250 KB):
          - current document text & head_rev
          - ring buffer of last ~1,000 ops
          - { client_id -> (last_seq, assigned_rev) }
          - live collaborator sockets & cursors
            |
            | conditional quorum append: (doc_id, next_rev) IF ABSENT (~5-10 ms)
            v
      [ Partitioned Op-Log Store (100+ partitions keyed by doc_id, 3x quorum replication) ]
            |                                       |
            | async background tail                 | async background tail
            v                                       v
      [ Snapshot Workers ]                    [ History Group Indexer ]
        Every 500 ops (or on session idle):     Merges consecutive same-author ops
        writes snapshot -> [ Object Storage ]   (< 5 min gap) into revision_groups
    
  6. Deep dive 1: concurrent edits at the same index (Operational Transformation)

    Why naive position replay corrupts documents. Suppose revision 7 of a document contains "the cat" (indices 0..6), and Alice and Bob both type at index 4 (right before 'c') at the exact same moment:

                             Revision 7: "the cat"
                            /                     \
       Alice types ins(4, 'A')                   Bob types ins(4, 'B')
       Alice sees: "the Acat"                    Bob sees: "the Bcat"
                            \                     /
                 NAIVE REPLAY WITHOUT ADJUSTING POSITIONS:
       Alice applies ins(4, 'B') -> "the BAcat"  !=  Bob applies ins(4, 'A') -> "the ABcat"  (DIVERGED!)
    

    Locking the document before every keystroke ruins instant local typing, and "last writer wins" deletes Alice's or Bob's work.

    How Operational Transformation (OT) with a single server sequencer solves this. Operational Transformation is a pure function transform(op, other_op, op_goes_first) that rewrites an operation created on an older text state so it achieves its original intent after other_op has already been applied. Because one session server assigns a strict total order (rev 8, rev 9, ...) to every edit on a document, we only need the simple two-operation convergence rule:

    Applying A then transformed(B)  MUST EQUAL  Applying B then transformed(A)
    

    Here is the complete single-character transform logic (production span lists apply these exact rules across character runs):

    def transform(op, other, op_goes_first):
        """Rewrite `op` so it achieves the same edit AFTER `other` has already executed.
    
        Both `op` and `other` were created against the same starting document revision.
        Each op is either ("ins", pos, char) or ("del", pos), or None (a no-op).
        """
        # Chained transforms can turn a duplicate delete into None; preserve no-ops safely.
        if op is None:
            return None
        if other is None:
            return op
    
        kind, pos = op[0], op[1]
        other_kind, other_pos = other[0], other[1]
    
        if other_kind == "ins":
            if kind == "ins":
                # Shift right if `other` inserted strictly before us, OR at the exact same spot
                # and `other` wins the tie-breaker (for example, server-sequenced op wins).
                should_shift = (pos > other_pos) or (pos == other_pos and not op_goes_first)
            else:
                # A delete at `pos >= other_pos` always shifts right by 1 because `other`
                # inserted a new character at or before the character we want to delete.
                should_shift = pos >= other_pos
            if should_shift:
                pos += 1
        else:  # other_kind == "del"
            if kind == "del" and pos == other_pos:
                # Both users deleted the exact same character; nothing left for `op` to delete!
                return None
            if pos > other_pos:
                # `other` removed a character strictly before `pos`, pulling our index left by 1.
                pos -= 1
    
        return (kind, pos) + op[2:]
    

    Trace Alice and Bob again with OT (rule: the op sequenced earlier by the server always gets priority op_goes_first = True):

    1. Both start at rev 7: "the cat"
    2. Alice applies ins(4, 'A') locally ("the Acat") and sends (base_rev=7, ins(4, 'A')).
       Bob   applies ins(4, 'B') locally ("the Bcat") and sends (base_rev=7, ins(4, 'B')).
    3. Server receives Alice's op first -> base_rev 7 matches head 7 -> stores as rev 8: ins(4, 'A').
       Server acks Alice (rev 8) and broadcasts rev 8: ins(4, 'A') to Bob.
    4. Server receives Bob's op (base_rev=7, while head is now 8!):
       Server runs transform(Bob=ins(4,'B'), rev8=ins(4,'A'), op_goes_first=False) -> ins(5, 'B')!
       Server stores rev 9: ins(5, 'B'), acks Bob (rev 9), and broadcasts rev 9: ins(5, 'B') to Alice.
    5. Alice (at "the Acat") applies remote rev 9 ins(5, 'B')               -> "the ABcat"
       Bob   (at "the Bcat", with ins(4,'B') still unacked) receives rev 8 ins(4, 'A'):
             Bob transforms incoming rev 8 against pending ins(4,'B') (server wins tie -> stays ins(4,'A'))
             and applies ins(4, 'A') to "the Bcat"                          -> "the ABcat"!
    

    Where OT runs—and why clients allow at most ONE op in flight: Both the server and browser run the exact same transform function. To keep client transformation tiny and bug-free, each client maintains a 3-state machine (Synchronized, Awaiting Ack, Awaiting Ack with Local Buffer): while one submit_op is in flight over the network, any new keystrokes the user types are composed into a single local buffer rather than sent immediately. Whenever a remote_op arrives, the client only ever has to transform across at most two local operations (the 1 in-flight op + the 1 composed buffer), keeping client CPU cost O(1) in history depth!

    (Why OT over a CRDT—a Conflict-free Replicated Data Type that assigns every character a permanent fractional/tree ID so edits merge without a central server? CRDTs shine in peer-to-peer or multi-day offline apps, but store per-character metadata IDs and deleted-character tombstones that bloat RAM and snapshots 3–10x. Because we already route each live document to one session server, central-server OT keeps ops tiny and avoids tombstone garbage collection.)

  7. Deep dive 2: one session owner per document and fencing stale servers

    What single-server ownership buys: - Zero-lock revision numbering: One process increments head_rev (1907 -> 1908 -> 1909) in RAM. - Zero database reads per keystroke: The last ~1,000 ops sit right in a RAM ring buffer for instant transform lookups. - Cheap local broadcast & presence: Relaying edits and cursor coordinates is an in-memory loop over connected sockets.

    What it costs—and how we handle shard routing: - Stateful routing: Edge gateways hash shard_id = hash(doc_id) % 4096 and look up the shard's current owner_server_id from a cached etcd watch table (4,096 shard leases of 10 s TTL renewed every 3 s is tiny for etcd, whereas 1,000,000 per-document leases would overload it). Each of our ~200 session servers owns ~20 shards (~5,000 active documents, ~1.25 GB RAM) and loads individual documents lazily on first join.

    How the op log fences a "zombie" owner without trusting clocks: What if Server 1 freezes in a 15-second garbage-collection pause, its 10 s etcd lease expires, Server 2 takes over Shard 17 at rev 1908, and then Server 1 wakes up trying to write its own rev 1908? 1. Every write to doc_ops uses conditional insert-if-absent on PRIMARY KEY (doc_id, rev) across a quorum (at least 2 of 3 storage replicas must confirm on disk). 2. A session server never sends ack or remote_op until after the quorum append succeeds. 3. If both Server 1 and Server 2 race to insert (doc_id, rev=1908), the database accepts strictly one and rejects the loser with KeyAlreadyExists: - If stale Server 1 loses, it re-checks its etcd lease, sees its epoch expired, unloads the shard, and disconnects its sockets so clients reconnect to Server 2. - Even if Server 1 snuck 1908 in 1 ms before realizing its lease expired, Server 2 catches KeyAlreadyExists, reads 1908 from doc_ops, transforms its pending edit against 1908, and cleanly writes 1909!

    Thus etcd leases are purely a performance optimization to prevent collisions; correctness comes 100% from conditional (doc_id, rev) quorum appends.

  8. Deep dive 3: durable op-log writes and opening years-old documents fast

    Critical path on every edit (only ~200 bytes written): On each edit batch, the session server writes only one tiny doc_ops row—never rewriting the full 50 KB document! Grouping concurrent appends targeting the same op-log partition into 2–5 ms micro-batches keeps quorum disk latency at ~5–10 ms, invisible behind instant local echo on the user's screen.

    Background snapshotting + bounded tail replay on open: Every 500 revisions (and whenever a document's last editor disconnects), a background worker serializes the in-memory document state—plus {client_id -> (last_seq, assigned_rev)} for active tabs—to object storage at docs/{doc_id}/snapshots/{rev}.bin, and only after the upload completes inserts the pointer row into doc_snapshots (so a crash mid-upload never leaves a dangling pointer).

    Opening any document—whether created 5 minutes ago or edited daily for 8 years—executes the exact same bounded 4-step recipe:

    Step 1: Query latest pointer in doc_snapshots for doc_id        -> snapshot_rev = 482,500
    Step 2: Fetch docs/{doc_id}/snapshots/482500.bin (~50 KB)       -> full text at rev 482,500
    Step 3: Range-scan doc_ops WHERE doc_id = ? AND rev > 482500    -> at most 500 small rows (~100 KB)
    Step 4: Apply those <= 500 ops sequentially in memory           -> live head state in < 50 ms!
    

    Revision history & storage compaction: A background indexer groups consecutive ops by the same author (with < 5 min idle gaps) into revision_groups for the "Version History" sidebar. Viewing any historical revision R fetches the nearest snapshot <= R and replays at most 500 ops forward. To bound multi-year storage (~1.7 TB/day raw), ops older than 30 days can optionally be compacted into one composed delta op per revision_group—preserving full sidebar history and diffs at ~10x smaller size without storing every individual typo and backspace from years ago.

  9. Presence, scaling, failure handling, and trade-off summary

    Live cursors (presence): Each client throttles cursor updates to <= 5/s only while moving. Because edits shift character indices, both the server and clients transform remote {anchor, head} cursor coordinates through applied ops using the exact same transform shift math as inserts! Above ~25 simultaneous editors, O(N^2) cursor fan-out dominates bandwidth, so the session server batches cursor updates on a 100 ms tick and filters to cursors near each user's visible viewport.

    Failure recovery matrix:

    Failure event                        User experience & why zero acknowledged edits are lost
    -----------------------------------------------------------------------------------------------------
    User's Wi-Fi drops briefly           Types locally uninterrupted; IndexedDB holds pending op; resends
                                         same (client_id, client_seq) on reconnect.
    Server appends rev 1908, crashes     Within ~10s lease expiry, new owner loads snapshot + tail (which
    before sending ack                   includes 1908 and client_seq map). Client resends seq 42 -> new
                                         owner sees seq 42 == rev 1908 and immediately returns ack(1908)!
    Edge gateway crashes                 Browser auto-reconnects via load balancer in <1s; zero state lost.
    Client/server subtle OT bug          Periodic 100-rev SHA-256 checksum catches drift -> clean resync.
    Entire cloud region goes dark        Async cross-region replication may lag ~1s (or enable sync cross-
                                         region quorum at +60-100ms ack latency for enterprise zero-RPO).
    

    Core trade-offs summarized: Central-sequencer OT keeps operation payloads compact and transformation O(1) per client; single-owner session sharding makes ordering and presence in-memory fast while conditional (doc_id, rev) quorum appends prevent split-brain corruption; and append-only doc_ops paired with every-500-op snapshots deliver both keystroke durability and < 200 ms document opens after years of editing.

Intuition & how it works

Imagine two co-authors editing the same recipe card from separate rooms while a single managing editor sits at a central desk holding the master ledger. Each author writes on their own local copy immediately so their pen never feels laggy, and mails short sticky-note instructions ("based on version 7, insert 'A' at position 4") to the managing editor. Whenever two notes arrive that were both written while looking at version 7, the managing editor stamps the first note as version 8, mathematically adjusts the character position on the second note so it accounts for version 8's new letter before stamping it as version 9, and mails the numbered updates out so every room ends up with the exact same text.

A naive design fails immediately under concurrent typing. Saving the entire document file on every keystroke overwrites your teammate's sentences ("last writer wins") and turns a 1-byte keystroke on a 100 KB doc into a 100,000x write amplification problem; locking the document while someone types ruins real-time responsiveness; and blindly replaying character indices (insert at index 4) without adjusting for concurrent insertions shifts characters onto the wrong words so users' screens permanently diverge.

Here is how our design converges concurrent edits and opens old documents fast step by step: 1. Instant local echo (t = 0 ms): Starting from "the cat" (rev 7), Alice types 'A' at index 4 ("the Acat") and Bob simultaneously types 'B' at index 4 ("the Bcat"). Each browser updates its screen immediately, saves its unacknowledged edit in browser IndexedDB (persistent client-side storage that survives tab crashes), and sends submit_op with base_rev = 7 over a WebSocket (a persistent two-way connection). 2. Single-owner sequencing & OT (t = 15 ms): Both edits route to the single Session Server owning that document's shard. Alice's op arrives first, matches head_rev == 7, and is written via a quorum conditional append (saved to at least 2 of 3 database replicas only if (doc_id, rev=8) is still empty) before sending ack(rev=8). 3. Position adjustment (t = 18 ms): Bob's op (base_rev = 7) arrives when head is now 8. The server runs Operational Transformation (OT)—rewriting ins(4, 'B') past rev 8's ins(4, 'A') into ins(5, 'B')—stores it durably as rev 9, and broadcasts it. Alice applies ins(5, 'B') to "the Acat" -> "the ABcat"; Bob transforms Alice's ins(4, 'A') with server priority -> "the ABcat". Both screens match! 4. Fast open after years of edits: Every 500 ops, a background worker writes a full snapshot to object storage, so opening a 500,000-revision document reads just 1 snapshot (499,500) + at most 500 tail ops in < 50 ms.

Key trade-offs

  • Central-server Operational Transformation (OT) vs. CRDTs. A CRDT (Conflict-free Replicated Data Type) assigns every character a permanent unique identifier (and keeps deleted characters around as hidden tombstones) so peers can merge edits in any order without a central server—ideal for peer-to-peer apps or multi-week offline editing, at the cost of 3–10x larger memory and snapshot overhead. Because we already assign one live Session Server per open document, central-sequencer OT requires only the simple two-op transform rule, keeps ops tiny (plain integer offsets), and never accumulates character tombstones.
  • Single Session Server per document vs. stateless multi-server writes. Routing all editors of doc_id to one owner process gives lock-free sequential revision numbers (1, 2, 3...), keeps the recent op history hot in RAM (~250 KB/doc), and turns cursor relay into a fast local loop. The trade-off is maintaining a shard routing map (4,096 virtual shards leased in etcd) and enduring a brief ~5–10 second reconnect pause if that Session Server crashes.
  • Fencing via conditional (doc_id, rev) log append vs. trusting etcd leases alone. Distributed leases (time-bounded ownership locks) can overlap if an old server suffers a long garbage-collection pause or clock skew. Enforcing INSERT IF (doc_id, rev) IS ABSENT in the op-log database makes the storage layer the ultimate referee—leases prevent wasted work 99.99% of the time, while conditional appends guarantee split-brain safety 100% of the time.
  • Acking after quorum op-log write (~5–10 ms) vs. acking from server RAM (< 1 ms). Waiting 5–10 ms for a quorum disk append before sending ack is completely imperceptible to the typist (because local echo already drew the letter in 0 ms), yet guarantees zero acknowledged edits are lost if the Session Server dies. Across continents, synchronous cross-region quorum adds ~60–100 ms, so most deployments use synchronous multi-AZ quorum inside the document's home region plus asynchronous cross-region backup.
  • At most one op batch in flight per client vs. streaming every keystroke immediately. Holding newer keystrokes in a single composed client buffer until the in-flight op is acknowledged bounds network chatter to one message per round-trip time and limits client-side OT work to at most two pending operations, at the minor cost of batching edits into ~50–200 ms chunks on high-latency links.
  • Snapshot frequency (every 500 ops) and history compaction. Snapshotting every 50 op batches makes opens slightly faster but multiplies object-storage writes 10x; every 5,000 ops cuts snapshot writes 10x but slows document opens. Similarly, compacting ops older than 30 days into one delta op per revision_group slashes multi-year storage ~10x while preserving version-history browsing, trading away keystroke-by-keystroke replay of ancient sessions.

Common mistakes

  • Sending raw character positions without base_rev or transformation. Whenever two people type concurrently before hearing from each other, unadjusted indices insert or delete at shifted positions, corrupting the document permanently.
  • Blocking the UI until the server acknowledges a keystroke, or saving the whole document per edit. Waiting on a 50 ms round trip makes typing feel broken, and overwriting the full 50 KB document at 300,000 ops/s both loses concurrent teammates' work and demands 15 GB/s of database writes instead of 60 MB/s.
  • Replaying from rev 1 on every document open. Without periodic snapshots, open latency grows linearly O(total_lifetime_edits) until active documents time out on load.
  • Missing duplicate protection on BOTH server and client during reconnects. If the server stored (client_id, client_seq=42) as rev 1908 right before the network dropped the ack, two bugs lurk: the server must check {client_id -> (last_seq, assigned_rev)} so a retry returns ack(1908) instead of inserting twice, AND the client must recognize its own (client_id, client_seq) inside catch-up remote_op streams as an implicit ack instead of applying its own edit a second time!
  • Persisting live cursor updates (presence) to the database. Cursors move up to 5 times per second per user and have zero historical value; writing them to disk multiplies database load for data that clients regenerate within 200 ms of reconnecting.
  • Forgetting to transform cursors and comment highlights alongside text. If Alice inserts 20 characters at the top of page 1 and Bob's cursor or comment anchor on page 2 is not shifted by +20, every remote cursor and comment drifts onto the wrong sentence.

Follow-up questions

  • Suppose an author keeps typing offline for 60 minutes before reconnecting—how do you reconcile their local changes, and what is the computational cost? While offline, the browser remembers its starting base_rev = B and composes the entire hour of local keystrokes into a single compact span operation C persisted in IndexedDB. Upon reconnecting, the client submits (base_rev = B, op = C); the Session Server loads missed operations B + 1 .. head_rev (composing them or stepping through them), transforms C past the missed server history in time linear O(|C| + |missed_ops|) in span count rather than quadratic in raw keystrokes, appends the transformed C' as one new revision, and sends the transformed missed ops back to bring the client up to head_rev. Because OT guarantees syntactic convergence (identical strings) rather than human semantic sense when two authors rewrite the exact same paragraph offline, the UI highlights the merged region with a diff banner—and if B is older than our retained fine-grained op window (e.g., > 30 days offline), safely saves the offline draft as a separate conflict copy or side branch.
  • If the session node hosting an active document dies mid-keystroke, what happens on connected browsers and why are all acknowledged edits preserved? Connected browsers see a subtle "Reconnecting..." indicator while users keep typing smoothly into their local document copy (buffered in memory and IndexedDB). Within the 10 s etcd shard lease window, a surviving Session Server acquires the shard, loads the latest object-store snapshot plus <= 500 tail rows from doc_ops (rebuilding both the exact head_rev text and {client_id -> (last_seq, assigned_rev)}), and accepts reconnecting tabs. Clients send their last_seen_rev and any unacknowledged (client_id, client_seq) batch: if the crashed server had already committed that batch to quorum storage before dying, the new owner spots client_seq in the loaded log and immediately sends ack(assigned_rev); if not, it transforms and appends it cleanly. Zero acknowledged edits are ever lost because the crashed server never sent ack until after the 3-way quorum op-log write succeeded.
  • How would you adapt the architecture when a single hot document has hundreds of concurrent writers alongside tens of thousands of read-only spectators? Transforming 300 active editors (~900 ops/s) still fits easily on one Session Server CPU, but network fan-out explodes (900 ops/s x 10,000 sockets = 9,000,000 outbound messages/s). First, cap active read-write editors (e.g., 100–200 slots, downgrading idle tabs and extra arrivals to read-only viewers) and have the Session Server coalesce outbound editor updates and viewport-filtered cursors into 50–100 ms micro-batches (<= 10–20 pushes/s per editor). Second, move all read-only viewers completely off the Session Server onto a horizontally scaled Stateless Fan-Out Relay tier: the Session Server publishes one coalesced delta batch every 250–500 ms to a pub/sub topic for that hot document, and dozens of relay nodes broadcast it to 50,000+ viewers while serving newly arriving viewers a CDN-cached snapshot.
  • How do you support rolling a document back to an earlier revision while keeping the entire edit timeline intact? Never delete or truncate rows in doc_ops! Instead, reconstruct the historical document text and formatting at target revision R (by loading the nearest snapshot <= R and replaying forward to R), compute the span diff from the current head_rev state to R's state, and package that diff as a brand-new forward operation based on base_rev = head_rev tagged with metadata restored_from_rev = R. Submitting that operation through the normal Session Server OT pipeline assigns it head_rev + 1 (transforming cleanly against any concurrent keystrokes happening right then!), preserves revisions R + 1 .. head_rev intact in the audit timeline, and makes "undoing a mistaken restore" trivial—just restore head_rev the exact same way.

Follow-up questions

Similar questions

More Otter.Ai interview questions

All 12 Otter.Ai questions →