Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Real-Time Collaborative Document
Editor (CRDTs & WebSockets).

Building an offline-capable collaborative editor requires replacing central Operational Transformation (OT) locks with sequence CRDTs (RGA / Yjs) over sticky-routed WebSocket gateways, backed by an append-only operation log and periodic snapshot compaction.
Start the journey5 stages· Last modified Nov 21, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, sequence CRDTs guarantee strong eventual consistency without a central serialization server, but require tombstone compaction and delta-state encoding so document memory does not grow unboundedly.

TL;DR30-second simplified summary
▾

Core Mechanics: Concurrent offline edits break naive index-based updates (insert(pos=5, 'x')). Sequence CRDTs (such as RGA or Yjs) assign each character a globally unique, causally ordered ID (lamport_ts, client_id) so concurrent inserts merge commutatively in any delivery order.

Visual & Structural Flow: Depicts Client A (Offline Edit) and Client B (Concurrent Edit) each maintaining a local RGA / Yjs Character Tree (a1@A, b1@B), exchanging deltas through a WebSocket Pub/Sub Gateway with Commutative Merge (Zero Locks) and persisting to a Compacted Snapshot Store + Op Log.

Trade-Offs & Production: CRDTs eliminate central OT transform-server bottlenecks and support peer-to-peer/offline merges, at the cost of tombstone metadata overhead—mitigated via run-length block encoding and background GC compaction.

Failure Modes & Application: Hash-route document rooms to stateful WebSocket/Redis-PubSub shards, enforce per-document max op-size limits, and compact op logs every N=1,000 edits.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
CRDTs & Conflict-Free Replicated Data
CRDTs (Conflict-free Replicated Data Types) are replicated data structures whose concurrent updates commute or form a mathematical join-semilattice, guaranteeing every replica converges to the exact same state without coordination or consensus.
WebSocket Real-Time Scaling
WebSockets (RFC 6455) upgrade an HTTP connection into a persistent, full-duplex TCP frame stream; scaling to millions of concurrent connections shifts the bottleneck from request/sec to stateful memory, ephemeral ports, pub/sub fan-out, and reconnect storms.
Consistent Hashing & Virtual Nodes
Consistent hashing assigns data keys to servers in a way that limits how many keys move when servers are added or removed. This helps avoid widespread cache misses and sudden load on databases.
Full walkthrough · 5 stages
01
STAGE 01 · REQUIREMENTS & MATHL5 · APPLIED DESIGN

Clarify Concurrency, Offline Sync & Latency Math.

Why this matters: The problem: size WebSocket connections, delta broadcast fanout, and op-log storage.

Think of Clarify Concurrency, Offline Sync & Latency Math as the intuition layer for Design a Real-Time Collaborative Document Editor (CRDTs & WebSockets): The problem: size WebSocket connections, delta broadcast fanout, and op-log storage.

With 10M DAU and ~500K concurrent active sockets, each typing editor emits ~3–5 keystrokes/sec (~100 bytes per binary CRDT delta). Broadcasting to 100 peers in a room requires <80 ms p99 fanout, while offline editors must buffer thousands of local edits and merge cleanly upon reconnect without losing cursor intent.

Lifecycle & Failure Recovery

Clarify Concurrency, Offline Sync & Latency Math

election timeoutmajority voteshigher term seenFollowerCandidate ElectionElected LeaderMinority Isolated
02
STAGE 02 · OT VS. CRDTL5 · APPLIED DESIGN

Why Operational Transformation (OT) Needs a Central Arbiter.

Why this matters: The failure mode: compare central OT index-shifting against lock-free CRDT convergence.

Classic OT transforms integer offsets (insert(5, 'a')) on a single authoritative server per document.

Supporting multi-hour offline editing or multi-region active-active rooms in OT becomes notoriously bug-prone (TP2 puzzle).

Component Topology

Why Operational Transformation (OT) Needs a Central Arbiter

ClientingressQuorum LeadercomputeReplica 1storageReplica 2controlwrite(token)AppendEntriesquorum sync
Engineering Decision Framework
Problem
How to implement Design a Real-Time Collaborative Document Editor (CRDTs & WebSockets) without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, sequence CRDTs guarantee strong eventual consistency without a central serialization server, but require tombstone compaction and delta-state encoding so document memory does not grow unboundedly.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Real-Time Collaborative Document Editor (CRDTs & WebSockets) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · ENTERPRISE ARCHITECTUREL6 · SCALE & TRADE-OFFS

RGA/Yjs Delta Sync + Sticky WebSocket Shards + Op-Log Compaction.

Why this matters: The mechanism: route document rooms via consistent hashing and compact tombstones asynchronously.

Think of RGA/Yjs Delta Sync + Sticky WebSocket Shards + Op-Log Compaction as the intuition layer for Design a Real-Time Collaborative Document Editor (CRDTs & WebSockets): The mechanism: route document rooms via consistent hashing and compact tombstones asynchronously.

Consistent-hash doc_id to a WebSocket Room Shard (with Redis Pub/Sub cross-pod fanout for failover). Clients exchange state vectors ({clientId: maxClock}) on reconnect to fetch only missing binary deltas, while a background compactor merges the append-only op log into a single base snapshot and garbage-collects deleted tombstones once all active replicas acknowledge the epoch.

Sync & Persistence Path

CRDT Delta Sync & Snapshot Compaction Pipeline

Local CRDT TreeIndexedDB offlineWS Room ShardHash(doc_id) fanoutAppend Op LogIdempotent deltasSnapshot CompactorPrune tombstones

1.State-Vector Sync: Reconnects exchange compact version vectors to stream only missing deltas.

2.Run-Length Blocks: Yjs merges contiguous typing by one author into 1 block, cutting RAM 10x.

3.Safe Compaction: Squashes op logs into a base snapshot periodically for fast cold loads.

Caption: Sticky document rooms broadcast tiny binary CRDT deltas in <80ms while background compaction bounds op-log and tombstone growth.

def compute_missing_deltas(local_clock: dict[str, int], remote_ops: list[dict]) -> list[dict]:
    """Filter operations unseen by a reconnecting client using its state vector."""
    missing = []
    for op in remote_ops:
        cid = op["client_id"]
        seq = op["seq"]
        if seq > local_clock.get(cid, 0):
            missing.append(op)
    return sorted(missing, key=lambda o: (o["lamport"], o["client_id"]))
04
STAGE 04 · SCALE & MEMORY BOUNDSL6 · SCALE & TRADE-OFFS

Taming Tombstone Bloat & Ephemeral Cursor Presence.

Why this matters: Operational control: keep deleted characters and live cursors from bloating persistent state.

Think of Taming Tombstone Bloat & Ephemeral Cursor Presence as the intuition layer for Design a Real-Time Collaborative Document Editor (CRDTs & WebSockets): Operational control: keep deleted characters and live cursors from bloating persistent state.

Never persist live cursor/selection coordinates in the CRDT op log—broadcast awareness/presence as ephemeral volatile messages over WebSockets with a 30s TTL. For deleted text, compress consecutive deletions into run-length tombstone ranges and run periodic snapshot compaction.

Design Trade-Off

Taming Tombstone Bloat & Ephemeral Cursor Presence

Before · Async Primary / Split-Brain
  • Stale leader overwrites state
  • Clock skew breaks lease order
  • Full-table sync on reboot
After · Quorum + Monotonic Fencing
  • Majority quorum prevents split-brain
  • Fencing tokens reject zombies
  • Merkle/WAL catch-up in O(log N)
05
STAGE 05 · INTERVIEW FOLLOW-UPSL7 · STAFF / PRINCIPAL

Permissions Revocation, Undo/Redo & Large Document Splitting.

Why this matters: Applied problems: enforce access control on reconnect and keep per-user undo local.

Think of Permissions Revocation, Undo/Redo & Large Document Splitting as the intuition layer for Design a Real-Time Collaborative Document Editor (CRDTs & WebSockets): Applied problems: enforce access control on reconnect and keep per-user undo local.

On permission downgrade, immediately close the WebSocket and reject delta writes at the room gateway; implement local per-user undo using inverse operations scoped strictly to client_id so Ctrl+Z never undoes a collaborator's edits.

Request & State Flow

Permissions Revocation, Undo/Redo & Large Document Splitting

ClientLeader / CoordReplica AReplica B1. Propose write with fencingtoken2. AppendEntries(term, index)3. Await majority quorum ack4. Commit & apply to state machine
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why do sequence CRDTs (RGA / Yjs) anchor character insertions to neighbor IDs like (lamport_ts, client_id) instead of integer array indexes?

Recommended Learning Flow