Codeplant IT Solution
Codeplant IT Solution
Custom Software & AI Engineering

Building Real-Time Collaborative Web Applications with CRDTs, Yjs and WebSockets

Category: Web Architecture | Reading Time: 4 min read

How to engineer multiplayer collaborative applications (like Figma or Google Docs) using Conflict-Free Replicated Data Types (CRDTs), Yjs, WebSockets, and offline-first state synchronization.

Building real-time collaborative web applications—where multiple distributed users simultaneously edit documents, canvases, code editors, or spreadsheets—is one of the most notoriously difficult challenges in computer science. When two users in London and Tokyo edit the exact same sentence simultaneously while experiencing 150ms of network latency, how does the system reconcile the edits without losing characters or locking the screen?

Historically, collaborative systems relied on Operational Transformation (OT), the mathematical algorithm that powers Google Docs. However, OT requires a single, centralized server to sequence and transform every keystroke in strict chronological order. It is extraordinarily complex to implement, fails when users work offline for extended periods, and creates a single point of failure.

In 2026, Conflict-Free Replicated Data Types (CRDTs) have superseded OT across modern software architectures. CRDTs are mathematically provable data structures that can be updated independently and concurrently across distributed peers, guaranteeing eventual consistency and identical state without requiring a centralized coordinator. Below is Codeplant's architectural blueprint using Yjs.

1. Core Industry Challenges & Architectural Dilemmas

  • Interleaving Character Duplication: Naive position-based text insertions resulting in scrambled, duplicated words during simultaneous typing.
  • Memory Footprint & Tombstone Bloat: CRDT internal structures storing deleted characters (tombstones) to preserve historical causality, swelling memory over time.
  • Offline Merge Resolution: Cleanly reconciling changes when a user reconnects after 4 hours of offline work on an airplane without overwriting peer edits.
  • Cursor Awareness & Presence: Broadcasting live mouse positions and text selections without saturating WebSocket network bandwidth.

2. Technical Comparison & Architectural Trade-offs

Feature DimensionCentralized LockingOperational Transformation (OT)Conflict-Free Replicated Data Types (CRDTs - Yjs)
Architecture TopologyCentralized database lockStrict central sequencer serverDecentralized peer-to-peer / distributed mesh
Offline Editing SupportImpossible (locks require live server)Extremely complex, prone to merge conflictsNative mathematical eventual consistency
Network ResilienceCrashes on packet dropsRequires re-synchronization pausesImmediate optimistic client updates, asynchronous merge
Algorithm ComplexitySimple (destructive locks)Very High (exponential transformation rules)High mathematical rigor, simple developer API via Yjs
Production ExampleLegacy CMS file locksGoogle Docs (early generation)Figma, Notion, Linear, Jupyter, Codeplant Apps

3. Production Implementation Blueprint & Code Pattern

Below is Codeplant's production implementation setting up a real-time collaborative text editor using Yjs, y-websocket, and IndexedDB local offline persistence:

import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
import { IndexeddbPersistence } from 'y-indexeddb';

// 1. Create a shared Yjs Document
const ydoc = new Y.Doc();
const documentId = 'project-spec-doc-402';

// 2. Bind local IndexedDB for immediate offline loading
const indexdbProvider = new IndexeddbPersistence(documentId, ydoc);
indexdbProvider.on('synced', () => {
  console.log('Local offline document loaded from IndexedDB cache');
});

// 3. Connect to real-time WebSocket sync server
const wsProvider = new WebsocketProvider(
  'wss://collab.codeplantitsolutions.com',
  documentId,
  ydoc
);

// 4. Bind collaborative shared text type
const yText = ydoc.getText('codemirror-content');

// Observe changes from remote collaborators
yText.observe((event) => {
  console.log('Document updated by remote collaborator:', yText.toString());
});

// Update cursor awareness presence
wsProvider.awareness.setLocalStateField('user', {
  name: 'Alex Rivera',
  color: '#00AFA5'
});

4. Production Hardening & High-Concurrency Optimization

  • Document Snapshot Compaction: Periodically compress Yjs document update histories into unified snapshots to purge deleted tombstone overhead.
  • Throttled Presence Broadcasting: Throttle cursor position updates to 30 FPS (33ms) to avoid saturating mobile device WebSockets.
  • Redis Adapter for Multi-Node Scaling: Connect y-websocket server instances via Redis Pub/Sub to allow users connected to different servers to collaborate seamlessly.
  • Binary Protocol Buffers: Transmit CRDT update vectors in compact binary format (Uint8Array) rather than verbose JSON strings.

5. Enterprise Security, Governance & Regulatory Compliance

Multiplayer collaboration channels allow direct bi-directional message streaming. Enforcing strict room-level authorization is critical.

  • WebSocket Handshake JWT Verification: Validate cryptographically signed JWT tokens before permitting connection to any collaborative document room.
  • Document Access Control Lists (ACL): Validate room edit permissions on the WebSocket server before broadcasting peer updates.
  • End-to-End Encryption (E2EE): Optional client-side encryption of Yjs update buffers for confidential corporate whiteboards.

6. Real-World Production Context: Codeplant Real-Time Engineering: Collaborative Platforms

Codeplant IT Solution built real-time collaborative architectural canvas and document editing platforms for engineering design and inspection teams. By implementing Yjs and CRDTs, our applications support dozens of concurrent simultaneous editors with zero data loss, sub-25ms synchronization latency, and seamless offline-to-online transitions.

7. Frequently Asked Technical Questions (FAQ)

Why is Yjs preferred over Automerge for web applications?

Yjs is heavily optimized for JavaScript runtime performance, operating up to 10x faster and using significantly less memory than older CRDT libraries. It also has a mature ecosystem of editor bindings (ProseMirror, Quill, Monaco, CodeMirror).

What happens if a user is offline for days and then reconnects?

Yjs merges the offline updates into the latest document state deterministically. Both the reconnected user and the online users converge on the exact same document state without data corruption.

Can CRDTs be used for structured JSON data, not just text?

Yes. Yjs provides Y.Map and Y.Array primitives to build collaborative tables, kanban boards, design layers, and dynamic object graphs.

Conclusion & Strategic Engineering Takeaways

Multiplayer collaboration is rapidly becoming an expected standard across modern SaaS products. By adopting CRDTs and Yjs, engineering teams can build resilient, offline-first collaborative experiences with mathematical certainty. Consult with Codeplant IT Solution to engineer your collaborative platform.