Real-Time Multi-User Document Editing Service

Medium · System Design · Software Engineer · Onsite

Prompt

Design the backend and client synchronization protocol for a live multi-author document editor in which teammates type into the same shared workspace at the same moment. Edits made by one participant should appear on collaborators' screens in under 200 ms, local typing must remain lag-free through brief connectivity drops or extended offline sessions (reconciling cleanly once network access returns), and every participant must converge to an identical document state without losing concurrent keystrokes.

Your system must support character- or block-granularity collaborative editing, durable long-term storage, automatic resolution of simultaneous edits, and interactive revision history with the ability to roll a document back to an earlier checkpoint. It should scale horizontally across thousands of concurrently active documents—ranging from quiet two-person notes to busy company-wide pages with hundreds of connected readers and writers.

Scope & Expectations

  • Transport layer and real-time topology: Choose a bidirectional client-server protocol, budget end-to-end propagation below 200 ms, and explain how connection gateways and active document servers scale across thousands of open rooms and high-fan-out documents.
  • Document representation and convergence algorithm: Define how text, blocks, and cursors are modeled, and justify your concurrency strategy (such as Operational Transformation versus Sequence CRDTs) with a concrete trace of simultaneous edits.
  • Durable persistence and revision history: Show how live edits flush safely to long-term storage using operation logs and periodic snapshots, and how users inspect or restore historical versions while collaborators remain connected.
  • Network drops and offline reconciliation: Walk through the handshake used when a disconnected client reconnects with queued local edits so peers converge without duplicate or dropped operations.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Before picking between sync algorithms, pin down three product boundaries: what a document looks like, how long offline editing must work, and whether all traffic flows through our servers.

    Assumptions to state out loud:

    • Document structure: a document is an ordered list of blocks (paragraphs, headings, bullet items, images, tables), where each text block contains a character sequence with inline formatting ranges (bold, italic, links). Synchronization happens at the character level inside blocks and at the block level for structural moves or type changes.
    • Client-through-server topology: browser and mobile clients hold a local editor replica and synchronize through our backend servers, which enforce permissions and durable persistence (pure peer-to-peer WebRTC is out of scope, though our merge model keeps it possible).
    • Offline continuity: keeping local editing instant across transient network drops means keystrokes apply on device in 0 ms and queue in local storage. Because a 3-second Wi-Fi drop and a 3-hour train ride differ only in queue length, we support full offline editing with automatic reconnect merge.
    • Access roles: OWNER, EDITOR, COMMENTER, and VIEWER.

    Functional & non-functional targets:

    1. Real-time convergence: simultaneous edits merge without losing anyone's keystrokes, and any two replicas that have received the same set of edits display the exact same document regardless of message arrival order.
    2. Low latency: remote keystrokes appear on collaborators' screens in under 200 ms within a region; local typing never blocks on the network.
    3. Durability & version history: every acknowledged edit persists to long-term storage, and editors can browse past versions and restore any version safely while others are typing.
    4. Scale: up to 20,000 concurrently open documents at peak—most with 1–5 editors, and occasional "all-hands" hot documents with 100 active editors and 1,000 live viewers.
  2. Back-of-the-envelope numbers and the 200 ms latency budget

    Cluster-wide peak load
      Open documents        20,000 active at peak (~3 open tabs/doc -> 60,000 open WebSocket connections)
      Inbound typing rate   25% of tabs actively typing at ~5 keystrokes/s
                            = 60,000 x 0.25 x 5 = 75,000 ops/s inbound (~80 B encoded/op ≈ 6 MB/s in)
      Outbound fan-out      ~2 other participants/doc on average -> 150,000 msgs/s out (~12 MB/s out)
      Cursor presence       throttled to <= 10/s while moving (~1/s average) -> ~60,000 updates/s
    
    Single hot document (100 editors + 1,000 viewers = 1,100 sockets)
      Inbound typing        25 simultaneous typists x 5 ops/s = 125 ops/s (tiny CPU cost!)
      Naive fan-out         125 ops/s x 1,099 peers = 137,375 socket writes/s from ONE document!
      Batched every 25 ms   <= 40 batches/s x 1,100 sockets = 44,000 socket deliveries/s across gateways
                            (and only 40 batches/s x 6 gateways = 240 msgs/s leaving the room server!)
    
    Persistence & memory
      Batched log flushes   flush dirty docs at most every 500 ms (<= 2 writes/s/doc)
                            ~10,000 docs actively typed -> <= 20,000 log writes/s (down from 75,000/s!)
      Daily op-log volume   ~19,000 ops/s daily avg x 80 B x 86,400 s ≈ 131 GB/day before compression
      Snapshots (10M docs)  10,000,000 docs x ~100 KB compressed snapshot ≈ 1 TB object storage
      Active room RAM       20,000 open docs x ~300 KB in-memory state + buffers ≈ 6 GB across room fleet
    

    Now check the 200 ms end-to-end latency budget step by step:

    [Keypress] --(<=25ms client batch)--> [Send] --(10-40ms WAN)--> [Gateway -> Room: ~1ms apply]
               --(<=25ms fan-out batch)--> [Gateway] --(10-40ms WAN)--> [Browser render: ~16ms]
    Total worst-case in-region = 25 + 40 + 1 + 25 + 40 + 16 = 147 ms  (< 200 ms target!)
    

    Two architectural conclusions jump right out:

    1. A hot document is a fan-out problem, not a sequencing problem. Applying 125 ops/s in memory takes microseconds; pushing updates to 1,100 open sockets requires 25 ms batching and gateway-level fan-out.
    2. Database writes cannot sit on the real-time broadcast path. Waiting for a durable disk/quorum write before broadcasting would eat our safety margin under tail latency, so we must pick a merge model where broadcast-before-persist is 100% crash-safe.
  3. Communication protocol and API

    We compare four real-time transport options:

    Transport Server → client push Overhead per burst Verdict
    WebSockets (persistent two-way TCP connection) Native full-duplex 2–14 B binary frame header Primary choice: lowest latency and framing overhead for chatty typing + cursors
    SSE (Server-Sent Events) + HTTP POST One-way push only Full HTTP headers on every client batch Good proxy compatibility, heavier uplink overhead
    HTTP Long Polling Held request per burst High header + connection churn Fallback when corporate firewalls block WebSockets
    WebRTC Data Channels Peer-to-peer Low after setup Needs NAT traversal + still needs servers for ACLs and storage

    One multiplexed WebSocket per browser tab carries all open documents/sections for that user:

    REST API (HTTPS — CRUD, permissions, and version history)
      POST /v1/docs                                 {title}             -> {doc_id}
      GET  /v1/docs/{doc_id}                                            -> {title, role, snapshot_url}
      PUT  /v1/docs/{doc_id}/acl                    {principal, role}   -> {ok}
      GET  /v1/docs/{doc_id}/versions?cursor=...                        -> [{version_id, created_at, name}]
      GET  /v1/docs/{doc_id}/versions/{version_id}                      -> rendered read-only content
      POST /v1/docs/{doc_id}/versions/{version_id}/restore              -> {ok} (applies forward edit ops)
    
    WebSocket frames (wss://collab.example.com/v1/socket — compact binary encoding)
      Client -> Server:
        hello     {doc_id, client_id, vector}       sent on open & reconnect: "here is what I already have"
        ops       {doc_id, ops: [...]}              local edit batch (flushed every <= 25 ms)
        presence  {doc_id, anchor_id, head_id}      cursor/selection referenced by character IDs (<= 10/s)
    
      Server -> Client:
        sync      {doc_id, ops: [...], vector}      missing ops for client + server's current state vector
        ops       {doc_id, ops: [...]}              peer edits batched every 25 ms (tagged with room HMAC)
        saved     {doc_id, vector}                  confirms durability in log up to this state vector
        presence  {doc_id, cursors: [...]}          coalesced peer cursors every 50 ms
        error     {doc_id, code}                    READ_ONLY | FORBIDDEN | RESYNC | MOVED
    

    Two protocol details prevent subtle bugs:

    • vector is a state vector—a tiny map {client_id: highest_clock_seen} summarizing every edit a replica has applied. Exchanging two state vectors lets client and server compute exact missing diffs without brittle server sequence numbers.
    • Cursors attach to character IDs, not integer string offsets. Integer index 42 shifts the instant someone types at index 0, whereas character ID (19, "client_A") stays anchored to the exact letter under the user's caret.
  4. Data model: CRDT items, metadata tables, log, and snapshots

    We represent document content as a CRDT (Conflict-free Replicated Data Type)—a data structure where concurrent updates from different devices can be applied in any causal order and mathematically converge to the exact same state. Every character is an item carrying an immutable ID (clock, client_id), the ID of the character immediately to its left when typed (its origin), and its character value. When a user deletes a character, we do not splice it out of the array immediately; we keep it in place marked as a tombstone (an invisible deleted marker) so any concurrent edit anchored right next to it still finds its exact spot.

    -- Relational metadata in PostgreSQL (low write rate, strong consistency)
    CREATE TABLE documents (
      doc_id              UUID PRIMARY KEY,
      owner_id            BIGINT NOT NULL,
      title               TEXT NOT NULL,
      latest_snapshot_seq BIGINT NOT NULL DEFAULT 0,   -- highest log batch seq baked into the snapshot
      latest_snapshot_key TEXT,                        -- object-storage path: snapshots/{doc_id}/{seq}.bin
      created_at          TIMESTAMPTZ NOT NULL,
      deleted_at          TIMESTAMPTZ
    );
    
    CREATE TABLE doc_acl (
      doc_id       UUID NOT NULL REFERENCES documents,
      principal_id BIGINT NOT NULL,
      role         TEXT NOT NULL CHECK (role IN ('OWNER', 'EDITOR', 'COMMENTER', 'VIEWER')),
      PRIMARY KEY (doc_id, principal_id)
    );
    
    CREATE TABLE versions (
      doc_id       UUID NOT NULL REFERENCES documents,
      version_id   UUID NOT NULL,
      created_at   TIMESTAMPTZ NOT NULL,
      kind         TEXT NOT NULL,                      -- AUTO | NAMED | BEFORE_MERGE | RESTORE
      name         TEXT,
      state_vector BYTEA NOT NULL,                     -- ~200-500 B compact state vector!
      rendered_key TEXT,                               -- S3 rendered JSON for named & daily versions
      author_ids   BIGINT[] NOT NULL,
      PRIMARY KEY (doc_id, created_at, version_id)
    );
    
    Append-only op log  Wide-column / KV store (Cassandra or DynamoDB)
                        Key: (doc_id, seq) -> Value: {encoded_ops_batch, room_owner, written_at}
                        Write rule: conditional "put if seq does not exist" (fences split-brain rooms!)
                        Cleanup job: deletes batches 30 days AFTER a verified snapshot covers their seq
    
    Object storage (S3) snapshots/{doc_id}/{seq}.bin       -> compact binary CRDT state + tombstones
                        rendered/{doc_id}/{version_id}.json -> plain rendered text outliving compaction
    
    Browser IndexedDB   {doc_id, client_id, local CRDT snapshot, unsaved op queue, last_saved_vector}
                        Guarded by a browser Web Lock so two open tabs NEVER share the same client_id!
    
  5. High-level architecture

       Browser / Mobile Editor (local CRDT replica + IndexedDB + <=25ms op buffer)
             | HTTPS (REST)                                | WebSocket (wss://)
             v                                             v
     +------------------+                     +------------------------------------+
     | Stateless API    |                     | WebSocket Gateways (~6 nodes)      |
     | CRUD, ACLs,      |                     | - 10k-20k sockets/node, 25s ping   |
     | version history  |                     | - routes doc_id -> Room via hash   |
     +------------------+                     | - fans out 1 room batch -> N tabs  |
         |        |                           +------------------------------------+
         |        | restore / named version                | multiplexed internal RPC
         |        +----------------------------+           v
         v                                     |  +--------------------------------+
     +------------------+                      +->| Stateful Room Servers (~8)     |
     | PostgreSQL       |<------------------------| ONE active room per open doc:  |
     | docs, doc_acl,   |  snapshot seq & auto    | 1. check ACL & apply CRDT ops  |
     | versions         |  version pointers       | 2. broadcast in 25ms batches   |
     +------------------+                         | 3. flush op log every 500ms    |
                                                  | 4. write S3 snapshot / 10 min  |
                                                  +--------------------------------+
                                                          |                |
                                                          v                v
                                                +------------------+  +------------------+
                                                | Append-Only Log  |  | Object Storage   |
                                                | (doc_id, seq)    |  | CRDT snapshots & |
                                                | conditional put  |  | rendered history |
                                                +------------------+  +------------------+
      Coordination: Room servers hold 10s leases in etcd; gateways map doc_id -> owner via rendezvous hashing.
    

    Even though CRDT replicas don't require a central sequencer for correctness, routing each open document to one active Room Server is a huge efficiency win: we hold the document's CRDT state in RAM once, check ACLs in one place, coalesce 500 ms log writes sequentially, and relay cursor presence without cross-server pub/sub chatter.

  6. Deep dive 1: OT vs. CRDT, and how RGA resolves concurrent edits

    Interviewers always probe why you picked Operational Transformation (OT) or CRDTs:

    • Operational Transformation (OT) (used in classic Google Docs) sends position-based edits (insert(pos=5, "a")) to a single authoritative server that assigns a strict global order and mathematically transforms late-arriving offsets against earlier concurrent edits.
    • Sequence CRDTs — specifically RGA (Replicated Growable Array) (used in modern local-first editors like Yjs and Automerge) assign every character a unique ID (clock, client_id) using a Lamport clock (an integer counter updated on every event as clock = max(local_clock, seen_clock) + 1) and anchor each insert to its left neighbor's ID (origin).
    Dimension Server-Authoritative OT Sequence CRDT (RGA + Server Relay)
    Offline editing for hours/days Hard: client must rebase queued ops against thousands of server ops on reconnect Built-in: offline edits merge via the exact same apply() function as live edits
    Broadcast before DB write? Unsafe: if server crashes after broadcasting an unpersisted op, clients diverge Safe: ops are idempotent and clients hold unsaved ops to heal the new room
    Memory & storage footprint Lean: state is plain text Higher: ~2–5× plain text in compact run-encoded binary (needs tombstone compaction)

    Because our requirements emphasize seamless typing across connection flickers, offline merges, and < 200 ms broadcast latency without blocking on DB writes, Sequence CRDT (RGA) with a stateful room relay is the cleanest fit.

    How RGA keeps concurrent typing readable without scrambling words: when two users insert right after the same origin, the larger (clock, client_id) goes first (skipping over any already-placed items with larger IDs). Because each subsequent letter a user types points to their own previous letter as origin with an even higher Lamport clock, whole typed words stay grouped together! Trace Ana ("A") typing "abc" and Ben ("B") concurrently typing "xyz" right after "X" (id = (1, "A")):

    Ana's ops: 'a' id=(2,"A") origin=(1,"A") -> 'b' id=(3,"A") origin=(2,"A") -> 'c' id=(4,"A") origin=(3,"A")
    Ben's ops: 'x' id=(2,"B") origin=(1,"A") -> 'y' id=(3,"B") origin=(2,"B") -> 'z' id=(4,"B") origin=(3,"B")
    
    On Ben's screen (already has "Xxyz": [(1,"A"):'X', (2,"B"):'x', (3,"B"):'y', (4,"B"):'z']):
      1. Receive Ana's 'a' (id=(2,"A"), origin='X'):
         Start at index('X') + 1 -> sees 'x' (2,"B") > (2,"A") [skip!]
                                 -> sees 'y' (3,"B") > (2,"A") [skip!]
                                 -> sees 'z' (4,"B") > (2,"A") [skip!] -> lands at index 4: "Xxyza"
      2. Receive 'b' (origin='a') -> lands right after 'a': "Xxyzab"
      3. Receive 'c' (origin='b') -> lands right after 'b': "Xxyzabc"
    
    On Ana's screen (already has "Xabc": [(1,"A"):'X', (2,"A"):'a', (3,"A"):'b', (4,"A"):'c']):
      1. Receive Ben's 'x' (id=(2,"B"), origin='X'):
         Start at index('X') + 1 -> sees 'a' (2,"A") > (2,"B") is FALSE -> lands right at index 1: "Xxabc"
      2. Receive 'y' (origin='x') -> lands at index('x')+1 (before 'a'): "Xxyabc"
      3. Receive 'z' (origin='y') -> lands at index('y')+1 (before 'a'): "Xxyzabc"
    
    Both screens converge to "Xxyzabc" — zero interleaved "xaybzc" gibberish!
    

    Here is a clean, working reference implementation of RGA showing inserts, tombstone deletes, and deduplication:

    class RGADocument:
        """Reference sequence CRDT replica: items stay in document order with tombstones."""
    
        def __init__(self, client_id):
            self.client_id = client_id
            self.clock = 0       # Lamport logical clock: always moves forward
            self.items = []      # Ordered list of {"id", "char", "deleted_by"} dicts
            self.by_id = {}      # Fast lookup: item_id -> item dict
            self.op_log = []     # Causal history of applied ops on this replica
            self.seen = {}       # State vector: {client_id: highest_clock_applied}
    
        def visible_items(self):
            # Keep only characters that have never been marked deleted
            return [item for item in self.items if not item["deleted_by"]]
    
        def text(self):
            return "".join(item["char"] for item in self.visible_items())
    
        def local_insert(self, visible_pos, char):
            visible = self.visible_items()
            # Anchor to the visible character immediately to our left (or None at index 0)
            origin_id = visible[visible_pos - 1]["id"] if visible_pos > 0 else None
            op = {
                "type": "ins",
                "id": (self.clock + 1, self.client_id),
                "origin": origin_id,
                "char": char,
            }
            self.apply(op)
            return op
    
        def local_delete(self, visible_pos):
            target_id = self.visible_items()[visible_pos]["id"]
            op = {
                "type": "del",
                "id": (self.clock + 1, self.client_id),
                "target": target_id,
            }
            self.apply(op)
            return op
    
        def apply(self, op):
            op_clock, author = op["id"]
            # Idempotency check: ignore any op already covered by our state vector
            if op_clock <= self.seen.get(author, 0):
                return
    
            if op["type"] == "ins":
                # Start right after the origin item (or at index 0 if inserted at document start)
                insert_idx = 0
                if op["origin"] is not None:
                    origin_item = self.by_id[op["origin"]]
                    insert_idx = self.items.index(origin_item) + 1
    
                # Tie-break concurrent inserts at the same origin: larger (clock, client_id) goes first.
                # Because descendants of a concurrent item have even higher clocks, this skips whole runs!
                while insert_idx < len(self.items) and self.items[insert_idx]["id"] > op["id"]:
                    insert_idx += 1
    
                new_item = {"id": op["id"], "char": op["char"], "deleted_by": []}
                self.items.insert(insert_idx, new_item)
                self.by_id[op["id"]] = new_item
            else:
                # Tombstone delete: mark the item deleted instead of shifting array positions
                self.by_id[op["target"]]["deleted_by"].append(op["id"])
    
            # Advance Lamport clock and state vector
            self.clock = max(self.clock, op_clock)
            self.seen[author] = op_clock
            self.op_log.append(op)
    

    (Note: this teaching class uses O(n) list scans and one Python dict per character; production CRDT engines like Yjs pack consecutive characters typed left-to-right into single run-length structs inside a B-tree so inserts/deletes run in O(log n) time and use a few bytes per character.)

  7. Deep dive 2: scaling thousands of WebSockets and hot rooms

    Separating stateless WebSocket Gateways from stateful Room Servers prevents room rebalances or deploys from dropping 60,000 client TCP/TLS sessions:

    • Connection capacity & heartbeats: event-loop gateways (epoll/kqueue) hold 10,000–20,000 sockets per node at ~50 KB RAM per socket (~3 GB across 6 gateways in 3 AZs). Gateways send a 25 s WebSocket ping so cloud load balancers (often configured with 60 s idle timeouts) don't silently sever quiet readers, dropping dead mobile sockets after 3 missed pongs.
    • Bounded backpressure for slow phones: each socket gets a 1 MB outbound send buffer. If a user enters an elevator and stalls TCP delivery past 1 MB, the gateway drops the socket cleanly; reconnecting later via a tiny hello state-vector diff is far cheaper than buffering megabytes in gateway RAM.
    • Jittered reconnects: if one gateway crashes, 10,000 clients reconnect using exponential backoff with full jitter (random delay in [0, min(30s, 1s × 2^attempt)]) so surviving gateways and rooms don't get slammed in the same millisecond.
    • Rendezvous hashing for room placement: room servers maintain 10-second leases in etcd. Gateways hash (doc_id, server_id) across live servers (rendezvous hashing) and pick the highest score—meaning when a server joins or leaves, only 1/N of open documents move while (N-1)/N stay warm in RAM.
    • Taming the 1,100-user hot document: the room batches edits every 25 ms (<= 40 batches/s) and sends one copy per gateway (40 × 6 = 240 RPCs/s instead of 137,000), letting gateways fan the bytes out to local sockets while coalescing viewer cursors into "1,000 viewing".
  8. Deep dive 3: snapshots, append-only op log, and version history

    Why broadcast-before-persist (500 ms log batching) is safe:

    1. Authors keep every local op in IndexedDB until a saved {vector} frame confirms it reached the durable log, resending unconfirmed ops automatically on reconnect.
    2. Each room server binds client_id to the authenticated editor session (and tags broadcast batches with a short room HMAC so peers can also resupply unpersisted batches after a room crash without letting viewers forge edits).
    3. Every log batch writes (doc_id, seq) with a conditional if-not-exists fence. If a zombie room server briefly overlaps with a newly elected room server, its seq write fails immediately, forcing it to close the room and send RESYNC.

    Combining snapshots with the append-only op log:

    • Opening a cold document reads 1 latest snapshot (snapshots/{doc_id}/{seq}.bin) + log batches with batch_seq > seq.
    • Rooms write a fresh snapshot every 1,000 batches, every 10 minutes of active editing, and when the last user closes the doc—always uploading the S3 object before advancing documents.latest_snapshot_seq in Postgres so the pointer never dangles.
    • A background job deletes old log batches 30 days after a verified snapshot covers them (never via a blind 30-day DB TTL, which would cause data loss if snapshot uploads broke on a quiet document!).

    Cheap version history & safe forward restores: because tombstones record which op ID deleted them, storing a version only requires saving a ~300-byte state_vector! An item was visible at vector if and only if vector includes its insert and none of its deletes:

    def render_text_at_version(doc, version_vector):
        """Reconstruct exact document text as of `version_vector` using tombstone metadata."""
        visible_chars = []
        for item in doc.items:
            ins_clock, ins_author = item["id"]
            # Skip characters inserted after this historical state vector
            if ins_clock > version_vector.get(ins_author, 0):
                continue
    
            # Check whether any deletion of this character had already happened at version_vector
            was_deleted = any(
                del_clock <= version_vector.get(del_author, 0)
                for del_clock, del_author in item["deleted_by"]
            )
            if not was_deleted:
                visible_chars.append(item["char"])
    
        return "".join(visible_chars)
    

    Named versions and daily checkpoints also save a plain rendered JSON copy to S3 so history older than 90 days survives tombstone compaction. Crucially, restoring a past version never overwrites the server's CRDT state (which would corrupt live collaborators' replicas); instead, the API diffs current text against the target version and submits ordinary forward delete and insert ops through the room!

  9. Deep dive 4: connection flickers and offline-to-online merges

    One tiny 3-step state-vector handshake handles a 1-second Wi-Fi blip, a room server failover, and a 3-day offline airplane trip identically:

    Client (offline edits queued in IndexedDB)                 Room Server
    ------------------------------------------                 -----------
    1. Reconnects -> sends hello {doc_id, client_vector}  --->
                                                          <--- 2. Replies sync {ops_missing_for_client, room_vector}
    3. Applies server ops, then sends                     --->
       ops {ops_missing_for_room} (merges seamlessly!)
    
    def compute_missing_ops(doc, peer_vector):
        """Return all ops in our causal log that `peer_vector` has not yet seen."""
        missing_ops = []
        for op in doc.op_log:
            op_clock, author = op["id"]
            # Preserves causal order so every origin/target arrives before ops depending on it
            if op_clock > peer_vector.get(author, 0):
                missing_ops.append(op)
        return missing_ops
    

    Three offline edge cases to call out proactively:

    • Browser storage eviction: call navigator.storage.persist() when offline edits exist and warn on tab close if denied.
    • Permissions revoked while offline: hello re-validates doc_acl. If an editor was downgraded to VIEWER while on a flight, the room returns FORBIDDEN; the client preserves their local work by offering "Save offline edits as a private copy" and resets the shared view cleanly.
    • Large semantic overlaps (> 500 chars): automatically snapshot a BEFORE_MERGE version and highlight newly merged offline spans in the UI so humans notice if two authors rewrote the same paragraph differently.
  10. Scaling limits, failure modes, and key trade-offs

    • Cross-continent physics: light in fiber travels ~200 km/ms, so an editor 8,000 km from the document's active room server pays ~80 ms round-trip in fiber alone. Place each room in the first active editor's region (migrating if traffic shifts), or run one CRDT room per region syncing room-to-room for global teams!
    • Log-store outage: rooms continue relaying live edits in memory (up to a bounded 50 MB dirty buffer) while pausing saved frames so users see "Changes saved locally" after 30 s without losing typing responsiveness.
    • Silent client-bug detection: every 1,000 ops, the room broadcasts (state_vector, crc32(visible_text)); any client whose matching vector produces a different checksum silently reloads from the latest snapshot and logs a bug report.

    Summary of key trade-offs:

    • Sequence CRDT (RGA) over OT: gives effortless offline merges and safe broadcast-before-persist latency (< 150 ms), in exchange for tombstone/ID metadata requiring run-length encoding and periodic compaction.
    • Single room server per open document behind stateless WebSocket gateways: adds ~1 ms internal hop, but cuts 1,100-viewer hot-doc room fan-out from 137,000/s to 240/s, keeps sockets alive across room moves, and centralizes ACL checks and 500 ms log batching.
    • State-vector versions + forward-op restores: makes automatic 10-minute history snapshots nearly free (~300 B/version) and keeps live collaborators convergent during restores.

Intuition & how it works

Imagine three teammates editing the same essay at the same moment. If their computers send plain numeric positions—"delete character #10"—and someone else types three letters at the top of the page a millisecond earlier, index #10 shifts and deletes the wrong letter! Instead, our design gives every character ever typed a permanent badge (clock, client_id) and links it like a bead on a necklace right after the specific bead that sat to its left when typed—a sequence CRDT (Conflict-free Replicated Data Type), a data structure where concurrent edits can arrive in any order and still converge to the exact same result. When someone deletes a letter, we don't rip the bead off the string right away; we mark it invisible as a tombstone (a retained deleted placeholder) so any concurrent edit that pointed to that bead still lands in the exact right neighborhood.

Naive designs fail on both responsiveness and correctness. Locking a paragraph or forcing every keystroke to wait for a database round-trip makes typing feel sluggish and breaks on flaky train Wi-Fi, while "last-writer-wins" on whole blocks silently overwrites a coworker's sentences. Writing every single keypress synchronously to disk (75,000 writes/s at peak) also multiplies storage load and blows past our 200 ms real-time propagation budget.

Walk through "cat" ('c'=(1,A), 'a'=(2,A), 't'=(3,A)) when Ana (client A) types "s" at the end while Ben (client B) concurrently deletes "c":

  1. Instant local edits (0 ms): Ana inserts 's' anchored after origin = (3,A) ('t'), minting ID (4,A) via her Lamport clock (a logical counter set to max_seen_clock + 1), seeing "cats". Concurrently, Ben marks target (1,A) ('c') deleted with op (4,B), seeing "at".
  2. Fast room broadcast (< 150 ms): Both clients send 25 ms batches over WebSockets (persistent two-way TCP connections) to the document's single Room Server, which applies them in memory and broadcasts them immediately—before its 500 ms batched database flush.
  3. Order-independent convergence: Ana receives del (1,A) and hides 'c', leaving visible beads 'a', 't', 's' ("ats"). Ben receives ins 's' after (3,A); 't' is still (3,A) despite 'c' being a tombstone, so 's' lands right after 't', also showing "ats".
  4. Durable checkpoint (<= 500 ms): Once the room appends the batch to the durable log, it sends a saved state vector ({A: 4, B: 4}, a map of highest clocks per client), allowing both browsers to clear their local unsaved queues.

Key trade-offs

  • Sequence CRDT (RGA) vs. Operational Transformation (OT). OT transforms numeric character offsets on a central sequencing server, keeping stored state as lean plain text, but makes multi-day offline rebasing complex and forbids broadcasting edits before they hit durable storage. A sequence CRDT carries per-character IDs and tombstones, but merges offline sessions, connection flickers, and crash recoveries through one uniform, commutative apply() path.
  • Broadcast-before-persist (25 ms relay) vs. persist-before-broadcast (500 ms flush). Relaying in-memory edits before flushing to disk keeps p99 collaborator latency well under 200 ms and cuts database write rate by ~4× (75k/s → <= 20k/s). That shortcut is only safe because CRDT ops are idempotent and clients retain unsaved edits in browser IndexedDB until a saved state vector confirms durability.
  • One stateful Room Server per document vs. stateless write-anywhere servers. Even though CRDTs can merge across multiple servers, pinning each open document to one room via rendezvous hashing (a consistent-hashing scheme that moves only 1/N of rooms when servers join or leave) keeps one copy in RAM, enforces permissions centrally, and batches storage writes sequentially.
  • Separate WebSocket Gateways vs. direct client-to-room sockets. Placing a stateless gateway tier in front of room servers adds ~1 ms of internal network latency, but lets rooms deploy or rebalance without dropping 60,000 TLS connections and collapses hot-document room fan-out from 137,000 messages/s to 240 gateway batches/s.
  • State-vector version history vs. full-document copies. Recording a historical version as a ~300-byte state vector makes 10-minute auto-versions virtually free while tombstones remain in the snapshot; named and daily versions additionally store rendered S3 JSON so old history survives 90-day tombstone compaction.

Common mistakes

  • Overwriting whole blocks or documents with last-writer-wins, silently throwing away one person's concurrent typing.
  • Blocking local typing on server acknowledgment, turning every high-latency or flaky mobile connection into a frozen cursor.
  • Sending cursor positions or edits as raw integer string indexes without character IDs or base revisions, causing edits and selections to jump onto the wrong words under concurrency.
  • Relying on server sequence numbers while broadcasting before persistence. If a room server crashes before flushing seq = 105, the replacement server reuses 105 for a different edit and clients silently skip updates; client-keyed state vectors avoid this trap completely.
  • Using a blind 30-day TTL on the operation log. Deleting log entries purely by age destroys recent edits if snapshot uploads fail on an idle document; only prune log batches after verifying batch_seq <= latest_snapshot_seq.
  • Implementing "Restore Version" by overwriting the CRDT snapshot in place, which invalidates every connected collaborator's state vector and causes crashes or lost live edits instead of applying clean forward delete/insert operations.
  • Sharing one client_id across two browser tabs, allowing both tabs to mint identical (clock, client_id) pairs for different characters and permanently corrupting the CRDT ordering invariant.

Follow-up questions

  • What bottlenecks emerge when a single document reaches hundreds of pages, and how would you restructure storage and client loading to keep editing fast? A 600-page specification (~1.8M characters) cannot use one object per character or load all pages on initial open. First, store consecutive typed characters in compact run-length encoded blocks indexed by a B-tree (like Yjs/Automerge) so local inserts and deletes run in O(log n) time instead of O(n). Second, shard the document into hierarchical sub-documents (for example, a root outline CRDT pointing to independent ~20-page chapter CRDTs, each keyed (doc_id, section_id) with its own snapshot and log), allowing browsers to lazy-load and subscribe over the same WebSocket only to chapters near the user's viewport alongside virtualized DOM rendering.
  • How would you model and enforce granular document permissions—such as read-only viewers, commenters, and full editors—across live sessions and snapshots? Store principal roles in doc_acl (plus signed expiry tokens for shared links) and enforce them inside the authoritative Room Server on every hello and ops frame—never just in the frontend UI. Viewers receive outbound ops only; commenters can submit ops solely to a separate comments sub-document CRDT (whose thread anchors reference immutable character IDs in the body CRDT so highlights track moving text); and editors can write to both body and comments. When an owner downgrades or revokes access live, Postgres notifies the room immediately to block further writes (returning FORBIDDEN on offline reconnects), and snapshots served to viewers/commenters strip historical tombstone text so deleted secrets like accidentally pasted passwords cannot be inspected in network payloads.
  • In a CRDT-based design, how does tombstone and identifier metadata accumulate over months of heavy editing, and how do you bound memory and payload size? Because every character keeps an ID/origin and deleted text stays as tombstones, uncompacted CRDT state grows with total historical edits rather than visible length—a 10-page doc rewritten 20 times carries 200 pages of items, and minting fresh client_ids on every reload bloats the state vector unless tabs reuse a Web-Lock-guarded client_id in IndexedDB. We bound memory in four layers: (1) run-length compress sequential characters typed by the same author into one struct, (2) strip deleted character strings from tombstones older than the 90-day granular history window while retaining compact ID ranges for merges, (3) split huge documents into lazy-loaded sub-documents, and (4) occasionally epoch-rebase cold, heavily edited documents into a fresh zero-tombstone CRDT snapshot (letting any straggler offline client merge across the epoch boundary via a 3-way text diff against its last saved snapshot).

Follow-up questions

Similar questions

More Vercel interview questions

All 5 Vercel questions →