Design a real-time collaborative document editor

    A collaborative editor (Google Docs) lets many people edit the same document at once and converge to an identical state without a central lock. The heart of the problem is concurrency control on text: reconciling edits that happen simultaneously at overlapping positions.

    Real-Time & Messaging, 10 components, about 45 min

    1. Scope

    In scope

    • • Real-time concurrent editing of a shared document
    • • Convergence (everyone sees the same final state)
    • • Presence — see collaborators' cursors/selections
    • • Edit history & document persistence

    Out of scope

    • • Rich rendering / pagination / printing
    • • Comments & suggestions workflow
    • • Offline-first sync with long divergence

    2. Functional requirements

    Must have

    • • Two+ users edit the same doc and changes appear live
    • • Concurrent edits never corrupt the document
    • • All clients converge to the same state
    • • Persist the document durably

    Nice to have

    • • Cursor presence and user colors
    • • Version history / time travel
    • • Access control (view/comment/edit)

    3. Non-functional requirements

    Edit latency< 100 ms local echo, < 200 ms to peers
    ConvergenceGuaranteed (CRDT/OT)
    Availability99.9%
    ConsistencyStrong eventual — converge, never diverge
    DurabilityNo acknowledged edit may be lost

    4. Back-of-envelope estimation

    Assumptions

    • • 50M documents, 5M edited per day
    • • Active doc has ~3 concurrent editors
    • • Each editor produces ~1 op/second while typing
    • • Average op ~100 bytes; doc snapshot ~50 KB

    Derived numbers

    Concurrent sessions (peak)~500K— WebSocket connections
    Op throughput~500K ops/s peak— 500K sessions × ~1 op/s; ~3 ops/s per document
    Op-log/day~hundreds of GB— Before compaction to snapshots
    Snapshot store~2.5 TB— 50M docs × 50 KB

    5. API design

    WS/docs/{id}/connect

    Open a collaboration session; receive op stream + presence

    WSmsg: op

    Send a local op { type, position, content, baseVersion }

    GET/api/docs/{id}

    Load latest snapshot + version

    GET/api/docs/{id}/history

    List versions for time travel

    6. High-level design

    What each box in the reference diagram is responsible for:

    Collab Gateway — Terminates WebSockets, routes a session to the owning Document Service instance.
    Document Service — Per-document authority. Runs the OT/CRDT engine, assigns a total order to ops, broadcasts transformed ops to all collaborators.
    Op Log — Append-only ordered log of operations — the source of truth for replay.
    Presence — Ephemeral Redis state for cursors/selections, with short TTL.
    Snapshot Worker — Periodically compacts the op log into a materialized snapshot.
    Snapshot Store — Durable document state so new joiners don't replay the whole log.
    Metadata DB — Documents, owners, ACLs, version pointers.

    7. Data model

    Op Log: ops(doc_id, seq, user_id, op, ts)— Append-only, ordered by seq per doc
    Snapshot Store: doc_id → { state, version }— Object storage
    Redis: presence:{doc} → {user → cursor}— TTL ~30s

    8. Deep dives

    OT vs CRDT

    Operational Transform (OT) transforms an incoming op against concurrent ops so positions stay correct — it needs a central server to define a canonical order, which fits a per-document authority well (this is what Google Docs uses). CRDTs (e.g. RGA/Yjs) attach unique IDs to characters so ops commute and converge without a central transformer, which is better for P2P/offline. Both converge; OT is leaner on the wire, CRDTs are simpler to reason about under partition.

    Single authority per document

    Pin each active document to one Document Service instance (consistent hashing on doc_id). That instance assigns the total operation order and broadcasts. This avoids distributed consensus on every keystroke. On failover, a new instance rebuilds state from the latest snapshot + op-log tail.

    Snapshots to bound replay

    Replaying millions of ops to open a doc is too slow. A snapshot worker periodically folds the op log into a materialized state and records the version. New collaborators load the snapshot, then receive only ops after that version. The op log can be truncated/cold-stored past the snapshot.

    Presence is cheap and disposable

    Cursor positions change constantly but don't need durability. Keep them in Redis with a short TTL and broadcast over the same WebSocket as ops, on a separate channel so a flood of cursor moves never blocks actual edits.

    9. Bottlenecks

    • A single hot document → one authority instance caps throughput per doc (usually fine)
    • Op-log growth → periodic snapshot + compaction
    • WebSocket fan-out for big docs → presence/op channels separated, conflate cursor updates

    10. Trade-offs

    OT or CRDT

    Choose: Operational transformation with a central server that orders operations per document (the Google Docs model).

    Instead of: CRDTs (Yjs, Automerge): work peer-to-peer and offline without a central order, at the cost of larger metadata and tombstones.

    With a server in the loop anyway, OT keeps documents compact. CRDTs win for offline-first or peer-to-peer.

    Where a document lives at runtime

    Choose: One session server owns each active document (consistent hashing on doc id), holding it in memory.

    Instead of: Stateless servers reading and writing the database per keystroke: far too much write load.

    Single ownership makes ordering trivial and batches persistence.

    Persistence format

    Choose: Append operations to a log and snapshot every N operations; load = latest snapshot + tail.

    Instead of: Store only full documents: no history, no undo across sessions.

    The op log gives version history and recovery; snapshots bound load time.

    11. Failure modes

    Owning session server dies

    Editors disconnect; unpersisted operations at risk.

    Mitigation: Acknowledge an op only after it is appended to the durable log; another server loads snapshot + log and clients resend unacknowledged ops.

    Client offline for an hour, then reconnects

    Large divergent op set to transform.

    Mitigation: Transform against the server history since the client's base version; if too large, rebase by fetching the latest document and re-applying local changes.

    Hot document with 500 editors

    Broadcast fan-out overwhelms one server.

    Mitigation: Batch ops into 50–100 ms frames, cap active editors, and degrade others to view mode with slower updates.

    12. What interviewers probe

    Answer each one yourself before opening it.

    Walk through two users inserting at the same position.Show a strong answer

    Both send insert(5) against version v. The server applies A first, transforms B against A (position becomes 5 + len(A) or stays 5 by a site-id tie-break), broadcasts both, and clients transform pending ops the same way.

    How do cursors and presence work?Show a strong answer

    Ephemeral, not persisted: broadcast cursor positions through the session server, transformed like ops so they stay attached to text.

    How do you implement version history?Show a strong answer

    Snapshots plus the op log; named versions are pointers to log positions; restoring creates a new op that sets content.

    How do permissions change mid-session?Show a strong answer

    The session server checks permission on every op batch and receives revocation events; it downgrades the connection to read-only immediately.

    Sign in to track this guide in your curriculum progress.