Skip to main content
E-Commerce & High-Scale Logistics

Design Collaborative Document Editing with CRDTs (Google Docs)

Senior / Lead

Complete FAANG-level system design blueprint for Google Docs Collaborative Editor. Covers capacity estimation, high-level architecture.

Production Scale: 20M Active Documents • 500 Concurrent Editors/Doc

Design Collaborative Document Editing with CRDTs (Google Docs): Request Topology

5 Stages · 4 Sizing Benchmarks

Request traversal order for Design Collaborative Document Editing with CRDTs (Google Docs) (E-Commerce & High-Scale Logistics) under target workload 20M Active Documents • 500 Concurrent Editors/Doc:

Stage 1

L7 Consistent-Hash WebSocket Router

Stage 2

Stateful Collaboration Room Server

Stage 3

Client CRDT & Cursor Anchor Engine

Stage 4

Write-Ahead Operation Log (Kafka / Redis Streams)

Functional Requirements

  • •Enable up to 500 concurrent users to edit rich-text documents simultaneously with automatic conflict resolution
  • •Synchronize live remote cursor positions, text selections, and active collaborator presence indicators
  • •Support offline client editing with seamless CRDT state merge on reconnect and named version snapshots

Non-Functional Requirements

  • •Sub-50ms local keystroke echo and <150ms cross-client operation broadcast latency
  • •Strong eventual consistency (convergent document state across all peers regardless of message order)
  • •Bounded document memory growth via periodic CRDT tombstone garbage collection

Capacity & Scale Estimation (Back-of-the-Envelope Math)

Open Live Calculator
Production Scale Target20M Active Documents
Peak Throughput500 Concurrent Editors/Doc
Read-to-Write Ratio10 : 1
Availability Target99.999% SLA (Five 9s)

Estimate Custom QPS & Storage Growth Live

Calculate bandwidth ingress, 80/20 RAM cache sizing, and multi-year storage growth using our interactive developer utility.

Launch Calculator →

System Topology & Core Architectural Components

[Client 1 (Web / WASM)]        [Client 2 (Mobile App)]
         |                                 |
         +-------------> [WSS Edge Gateway] <--------------+
                                 |
                                 v
                     [Document Collaboration Node]
                     (CRDT State Vector / OT Engine)
                                 |
                                 v
                     [Redis Pub/Sub Buffer]
                                 |
                                 v
                     [Snapshot Service & S3 / BadgerDB]

1L7 Consistent-Hash WebSocket Router

Pins all WebSocket connections for a given doc_id to a single authoritative room host to avoid cross-node distributed locking.

2Stateful Collaboration Room Server

Validates document ACLs, sequences incoming CRDT/OT deltas in memory, and fans out compact binary updates to connected collaborators.

3Client CRDT & Cursor Anchor Engine

Assigns globally unique causal IDs to characters and anchors user cursors to character IDs so concurrent edits never corrupt selection offsets.

4Write-Ahead Operation Log (Kafka / Redis Streams)

Appends every accepted edit delta sequentially before broadcast so warm standby hosts can take over instantly on room crash.

5Snapshot Compactor & Object Store (PostgreSQL + S3)

Periodically folds operation logs into compacted document checkpoints, prunes safe tombstones, and serves historical revision diffs.

Architectural Trade-Off Analysis & CAP Constraints

Trade-Off Decision Matrix

Engineering a resilient architecture for Design Collaborative Document Editing with CRDTs (Google Docs) at a scale of 20M Active Documents • 500 Concurrent Editors/Doc requires deliberate trade-offs across data consistency, replication latency, network partition tolerance, and storage economics:

DimensionSelected StrategyAlternative EvaluatedTrade-Off Rationale & Latency Impact
CAP Theorem PostureAP (Strong Eventual Consistency via Conflict-Free Replicated Data Types)CP (Centralized Pessimistic Lock per Paragraph / Document)Collaborative text editing requires instantaneous zero-latency local keystroke typing; CRDT state vectors (Yjs/Automerge) guarantee deterministic convergence across peer network splits without server lock blocking.
Collaboration ModelConflict-free Replicated Data Types (CRDT - Yjs / Loro State Vector)Operational Transformation (OT) with Centralized Sequencing NodeCRDTs guarantee mathematical convergence without requiring round-trip lock acquisition to a single master server, enabling robust offline editing.
Transport LayerMultiplexed WebSockets over TLS with Binary Protocol BuffersHTTP Long Polling / Server-Sent Events with REST POSTReduces framing overhead from 800+ bytes per keystroke to 12 bytes, maintaining sub-15ms typing sync latency between worldwide peers.
Document Snapshot PersistenceLog-Structured Append-Only Delta Log + Asynchronous CompactionFull Document Serialization on Every User MutationSerializing 50-page docs on every keystroke exhausts CPU and disk I/O. Delta logs enable O(1) mutations with background snapshots every 100 ops.
Presence & Cursor TrackingEphemeral In-Memory Pub/Sub (Redis Cluster) with 5-Second TTLPersistent Database Storage with Write-Through CachingCursor coordinates and text selections change 30 times/sec; writing ephemeral state to persistent disks causes storage churn.

Fault Tolerance, High Availability & Failure Mode Analysis

Operating at 20M Active Documents • 500 Concurrent Editors/Doc demands proactive defenses against cascading outages. The blueprint specifies four critical failure modes and remediation protocols tailored to Design Collaborative Document Editing with CRDTs (Google Docs):

1. Client Network Disconnection and Reconnection Storm

Blast Radius: Massive burst of queued offline mutations arriving simultaneously.

Remediation Protocol: Clients exchange vector clocks; server transmits only the missing compact state vector diff rather than full history replays.

2. Collaboration Node Crash While Hosting 200-Editor Doc

Blast Radius: Active WebSocket connections dropped mid-session.

Remediation Protocol: Consistent hashing sticky-routes editors to backup node; editors reconnect instantly with local CRDT states and reconcile missing ops.

3. CRDT Tombstone Memory Bloat

Blast Radius: Continuous deletion of text fragments accumulates tombstones, bloating document RAM.

Remediation Protocol: Periodic GC passes sweep tombstones after confirming all connected clients have acknowledged vector clock thresholds.

4. Split-Brain Network Partition Across Edge Gateways

Blast Radius: Two isolated groups of editors continue typing simultaneously.

Remediation Protocol: CRDT commutativity guarantees that once the partition heals, both state vector histories merge deterministically without data loss.

Production Algorithm Implementation: State Vector Convergence & Delta Synchronization (CRDT)

typescript

High-scale distributed systems rely on atomic synchronization primitives to enforce SLA boundaries. Below is the production implementation for Design Collaborative Document Editing with CRDTs (Google Docs):

export interface CharNode {
  id: string;        // ClientId + SequenceCounter
  char: string;
  originLeft: string | null;
  originRight: string | null;
  deleted: boolean;
}

export class CRDTSequence {
  private items: CharNode[] = [];

  integrate(remoteNode: CharNode): void {
    if (this.items.some(i => i.id === remoteNode.id)) return;

    let insertIdx = 0;
    if (remoteNode.originLeft) {
      const leftIdx = this.items.findIndex(i => i.id === remoteNode.originLeft);
      if (leftIdx !== -1) insertIdx = leftIdx + 1;
    }

    while (insertIdx < this.items.length) {
      const next = this.items[insertIdx];
      if (next.originLeft === remoteNode.originLeft && remoteNode.id < next.id) {
        break;
      }
      insertIdx++;
    }
    this.items.splice(insertIdx, 0, remoteNode);
  }

  getText(): string {
    return this.items.filter(i => !i.deleted).map(i => i.char).join('');
  }
}

Design Collaborative Document Editing with CRDTs (Google Docs): Design Scope & Constraints Summary

This senior / lead blueprint balances 3 core functional workflows against 3 availability and latency constraints tailored for 20M Active Documents • 500 Concurrent Editors/Doc. Review the FAQ trade-offs below to compare partitioning keys, replication topology, and failure isolation specific to E-Commerce & High-Scale Logistics.

Architectural FAQs & Interview Deep Dives

1How do sequence CRDTs compare with Operational Transformation (OT) for conflict-free collaborative editing?

OT keeps document state lightweight by storing plain character arrays and relying on a central sequencing server to transform incoming edit indices against intervening operations. Sequence CRDTs (such as RGA or LSEQ) assign every character a globally unique, causally ordered fractional or Lamport-clock identifier so disconnected clients can merge edits in any arrival order without central coordination.

2How are WebSocket connections routed so 500 concurrent editors on one document avoid cross-server locking?

Layer-7 consistent hashing routes every WebSocket session for a given `doc_id` to a single authoritative stateful room host (paired with a warm standby replica fed via Kafka/Raft). That room sequences concurrent character mutations lock-free in RAM, assigns monotonic revision numbers, and broadcasts compact binary diffs to connected clients over Pub/Sub.

3How do remote cursor positions and text selections stay accurate when multiple users type above the cursor simultaneously?

Client cursors are anchored directly to stable CRDT character IDs—or passed through the same OT index-transformation pipeline as document mutations—so upstream insertions shift downstream cursor offsets automatically. Ephemeral presence updates are throttled (e.g., 50 ms batches) on a separate channel so cursor jitter never contends with durable edit persistence.

4How do you prevent deleted-character tombstones from bloating CRDT document memory over years of revisions?

Deleted nodes remain as tombstones only while active or offline clients might still reference them in concurrent edits. Once causal version vectors confirm all active peers have observed a revision watermark, a background compactor materializes a clean document snapshot to object storage and truncates older operation logs and tombstones.