Building Real-Time Collaborative Editors with Yjs, Tiptap, and WebSockets

Daniyal
DaniyalSenior Full-Stack Architect
August 16, 202615 min read
Share Technical Insights:
Sponsored · Enterprise Cloud & AI Audit

Cut AWS / GCP & LLM Inference Spend by 40–68% Without Latency Regressions

Get a free 30-minute infrastructure, Kubernetes, or AI pipeline bottleneck audit with a Principal Systems Architect.

Multiplayer collaboration is no longer confined to standalone word processors. Modern enterprise SaaS platforms—from legal contract redlining suites and engineering incident war-rooms to AI-assisted knowledge bases—require sub-50ms concurrent rich-text editing, live cursor presence, and resilient offline reconciliation. Historically, building real-time collaborative editors required complex Operational Transformation (OT) central servers that serialized every keystroke against a master revision log.

LOADING ARCHITECTURE DIAGRAM...
Building Real-Time Collaborative Editors with Yjs, Tiptap, and WebSockets — Architecture Schematic
Figure 1: Building Real-Time Collaborative Editors with Yjs, Tiptap, and WebSockets (Web Development Architecture Overview)

Today, **Conflict-Free Replicated Data Types (CRDTs)** powered by **Yjs** and bound to **Tiptap (ProseMirror)** have fundamentally simplified distributed state convergence. By encoding document nodes as mathematically commutative linked-list items with Lamport logical clocks, Yjs guarantees strong eventual consistency across peers without requiring a central coordination lock—even when mobile or desktop clients edit offline for hours before reconnecting.

At Beyond Ambition, our full-stack web application engineers build collaborative workspaces for teams across New Zealand, Australia, and the United States. Below is our production architecture for scaling Yjs + Tiptap across multi-node WebSocket clusters with binary state compaction and PostgreSQL persistence.

1. CRDTs vs. Operational Transformation (OT): Why Yjs Wins at Scale

In a rich-text editor like ProseMirror, the document is a strict hierarchical tree of block and inline marks, not a flat character array. If User A wraps a paragraph in a `<blockquote />` while User B concurrently splits that same paragraph offline, naive index-based diffs corrupt the document schema:

  • ** YATA Algorithm & Unique Item IDs:** Yjs implements the YATA (Yet Another Transformation Approach) CRDT. Every character insertion and structural node is assigned an immutable tuple identifier `(clientID, clock)` along with pointers to its `originLeft` and `originRight` neighbors at the moment of creation. Concurrent insertions at the exact same position deterministically sort by `clientID`, guaranteeing identical tree convergence on every peer.
  • **Run-Length Binary Encoding:** A naive CRDT stores metadata per character, creating massive memory overhead. Yjs merges adjacent sequential characters typed by the same user into a single compound `Item` struct and serializes state vectors using highly compressed variable-length binary encoding (`lib0`), keeping typical 50-page document snapshots under 120 KB.
  • **Decoupled Awareness Protocol:** Ephemeral state—such as remote cursor coordinates, active text selections, and user avatars—never touches the persistent CRDT document log. Instead, Yjs routes presence over a lightweight, stateless `Awareness` pub/sub channel with automatic heartbeat expiration.

2. Storage & Sync Topology Comparison

Synchronization LayerProtocol / Storage EngineLatency / OverheadFailure Recovery Guarantee
Local Offline Buffer`y-indexeddb` browser store< 2 ms local read/writeZero data loss on tab crash or airplane-mode edits; auto-merges StateVector on reconnect
Edge WebSocket TransportHocuspocus / `y-websocket` binary frames15–40 ms regional RTTDifferential sync step exchanges only missing clock ranges (`encodeStateAsUpdate`)
Cross-Node Pub/Sub BusRedis Streams / NATS binary relay1.2 ms inter-pod fanoutAllows clients on different Kubernetes pods to edit the same `Y.Doc` room concurrently
Durable Database StorePostgreSQL `BYTEA` + Incremental CompactionDebounced 2,000 ms flushMerges incremental update rows into a single compacted `Y.encodeStateAsUpdate` snapshot
Scroll horizontally to view all columns →
Sponsored · Production Engineering Pod

Shipping Next.js 16, Multi-Agent RAG, or High-Concurrency Microservices?

Partner with Beyond Ambition Limited (NZBN 9429053304834) for fixed-milestone delivery and 99.99% SLA guarantees.

3. Production Implementation: Tiptap + Yjs Client & Compaction Server

A critical production mistake with Tiptap and Yjs is leaving ProseMirror's default `History` extension enabled alongside `@tiptap/extension-collaboration`. Doing so causes global undo/redo collisions where pressing `Cmd+Z` reverts a teammate's typing instead of your own local changes. Below is the complete, production-hardened client and server implementation:

CODE
// 1. React Client: Dual IndexedDB + WebSocket Provider with Scoped UndoManager
import { useEffect, useMemo } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Collaboration from "@tiptap/extension-collaboration";
import CollaborationCursor from "@tiptap/extension-collaboration-cursor";
import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
import { IndexeddbPersistence } from "y-indexeddb";

export function CollaborativeDocumentEditor({ docId, currentUser }: { docId: string; currentUser: { name: string; color: string } }) {
  const ydoc = useMemo(() => new Y.Doc({ gc: true }), [docId]);

  const provider = useMemo(
    () => new WebsocketProvider(process.env.NEXT_PUBLIC_COLLAB_WS_URL!, docId, ydoc, { connect: true }),
    [docId, ydoc]
  );

  useEffect(() => {
    // Persist un-synced offline edits locally in browser IndexedDB
    const idbPersistence = new IndexeddbPersistence(`ba-doc-${docId}`, ydoc);
    return () => {
      idbPersistence.destroy();
      provider.destroy();
      ydoc.destroy();
    };
  }, [docId, provider, ydoc]);

  const editor = useEditor({
    immediatelyRender: false, // Prevents Next.js SSR hydration mismatch
    extensions: [
      StarterKit.configure({
        // CRITICAL: Disable default ProseMirror history; Y.UndoManager tracks per-user local origins
        history: false,
      }),
      Collaboration.configure({
        document: ydoc,
        field: "prosemirror",
      }),
      CollaborationCursor.configure({
        provider,
        user: currentUser,
      }),
    ],
  });

  return <EditorContent editor={editor} className="prose dark:prose-invert max-w-none" />;
}

// 2. Server-Side Binary Update Compaction (Node.js / PostgreSQL)
export async function compactDocumentUpdates(docId: string, pgPool: any): Promise<void> {
  const client = await pgPool.connect();
  try {
    await client.query("BEGIN");
    const { rows } = await client.query(
      "SELECT id, update_blob FROM document_yjs_updates WHERE doc_id = $1 ORDER BY id ASC FOR UPDATE",
      [docId]
    );
    if (rows.length <= 1) {
      await client.query("COMMIT");
      return;
    }
    // Merge N incremental binary frames into a single garbage-collected state vector
    const mergedUpdate = Y.mergeUpdates(rows.map((r: { update_blob: Uint8Array }) => r.update_blob));
    await client.query("DELETE FROM document_yjs_updates WHERE doc_id = $1", [docId]);
    await client.query(
      "INSERT INTO document_yjs_updates (doc_id, update_blob) VALUES ($1, $2)",
      [docId, Buffer.from(mergedUpdate)]
    );
    await client.query("COMMIT");
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

4. Preventing CRDT Tombstone Bloat and Sub-Document Partitioning

Because CRDTs must retain lightweight deletion markers ('tombstones') to resolve out-of-order concurrent edits, documents subjected to hundreds of thousands of edits can accumulate metadata overhead if left uncompacted. To maintain sub-50ms load times in production:

  • **Enable Garbage Collection (`gc: true`):** Keep `gc: true` enabled on the `Y.Doc` instance so deleted item content is immediately purged while retaining only compact 12-byte range structs (`GC` structs). If version history snapshots are required, store immutable periodic snapshots in object storage (S3/R2) rather than disabling garbage collection on the live room.
  • **Incremental Update Compaction:** Instead of re-encoding and overwriting a multi-megabyte blob on every keystroke, append incremental `Y.encodeStateAsUpdate` deltas to an append-only PostgreSQL table and run `Y.mergeUpdates()` asynchronously when a room closes or exceeds 100 delta frames.
  • **Sub-Document Lazy Loading:** For massive enterprise wikis or multi-tab spreadsheets, partition independent sections into Yjs Subdocuments (`new Y.Doc()` nested inside a root `Y.Map`) so the browser only downloads and hydrates the active viewport section.
Architecture Benchmark
FIELD POSTMORTEM

Multiplayer Legal Redlining & Contract Workspace

Production Bottleneck & Failure Mode

A legal-tech SaaS platform suffered frequent document state divergence and 14 MB WebSocket payloads when 25+ attorneys redlined 80-page commercial contracts simultaneously.

Architectural Resolution & Fix

We migrated the editor to Tiptap + Yjs with `lib0` binary WebSocket framing, Redis pub/sub room routing, and background PostgreSQL `Y.mergeUpdates` compaction.

22 msCursor Sync RTT
-89%Snapshot Payload
0 (CRDT)Merge Conflicts

Architectural Takeaway: Pairing Yjs binary differential sync (`encodeStateVector`) with background PostgreSQL update compaction delivers Google Docs-grade responsiveness at a fraction of traditional OT server cost.

Sponsored · Dedicated Senior Engineers

Ready to Turn This Architecture Into Production-Grade Code?

Deploy senior full-stack, mobile, and cloud engineers across the US, UK, AU & NZ timezones within 48 hours.

Share Technical Insights:
Topic Cluster & Architectural References

Production Engineering Capabilities & Case Studies

Schedule Scoping Session

Related Architectural Deep Dives

Accelerate Your Technical Execution

Beyond Ambition delivers custom enterprise AI solutions, premium Next.js web app development, and robust DevOps architecture pipelines. Let’s map your technical requirements and scaling limits in a dedicated scoping session.

Stay at the Cutting Edge

Get bi-weekly technical deep dives on AI architectures delivered directly to your inbox.