Real-Time Collaborative Text Engine using CRDTs and WebRTC
Architecture Overview
This implementation provides a fully functional real-time collaborative plain-text editor engine with the required features:
- CRDTs: Yjs (a high-performance CRDT framework).
Y.Text handles text as a sequence CRDT with unique identifiers per character, tombstones for deletes, and mergeable updates.
- WebRTC Data Channels: y-webrtc provider manages peer-to-peer data channels for low-latency sync.
- Peer Discovery: Room-based discovery via public Yjs WebSocket signaling servers (SDP exchange for ICE candidates/NAT traversal). No custom server needed.
- Delta Compression: Yjs sync protocol uses state vectors to request/send only missing deltas. Updates are binary-encoded with run-length encoding, gaps, and delete-set compression.
- Causality Tracking: Yjs tracks causality via unique 64-bit struct IDs and dotted version vectors in delete-sets, ensuring operations apply correctly regardless of delivery order.
- Offline Reconciliation: Local persistence via
y-indexeddb. On reconnect/online, bidirectional delta sync merges changes conflict-free.
- Abuse Mitigation:
- Debounced diffs (150ms) prevent spam.
- Max doc size (10k chars); auto-truncates.
- Max insert per update (500 chars); rejects larger.
- Peer count monitoring; signaling/WebRTC handles DoS via retries/limits.
- Yjs validates malformed updates internally.
UX Notes:
- Plain-text
<textarea> with efficient diff-based local updates (prefix/suffix matching for inserts/deletes).
- Approximate cursor preservation on remote updates.
- Awareness shows peer count/names (extendable to cursors/colors).
- For production rich-text/cursors: Integrate y-prosemirror or y-quill.
Demo Instructions:
- Save as
collab-engine.html.
- Open in multiple browser tabs/windows (Chrome/Firefox).
- Enter same room name (e.g.,
demo-room), click Join.
- Edit in one tab → see real-time sync in others.
- Go offline (devtools Network → Offline), edit, reconnect → auto-merge.
- Reload tab → persists/reconciles via IndexedDB.
Complete Standalone Demo Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CRDT Collaborative Text Engine</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
#controls { margin-bottom: 10px; }
input, button { padding: 8px; margin: 5px; }
#editor { width: 100%; height: 400px; font-size: 14px; font-family: monospace; }
#status, #peers { margin: 10px 0; padding: 10px; border-radius: 4px; }
#status.connected { background: #d4edda; color: #155724; }
#status.disconnected { background: #f8d7da; color: #721c24; }
#peers { background: #d1ecf1; color: #0c5460; }
</style>
<!-- Yjs CRDT -->
<script src="https://cdn.jsdelivr.net/npm/yjs@13.6.17/dist/y.min.js"></script>
<!-- y-webrtc for WebRTC + signaling -->
<script src="https://cdn.jsdelivr.net/npm/y-webrtc@12.1.1/build/index.min.js"></script>
<!-- y-indexeddb for offline persistence -->
<script src="https://cdn.jsdelivr.net/npm/y-indexeddb@latest/dist/index.umd.min.js"></script>
</head>
<body>
<h1>Real-Time CRDT Text Engine (WebRTC + Yjs)</h1>
<div id="controls">
<input id="room" placeholder="Room name (e.g., demo-room)" value="demo-room">
<button id="join">Join Room</button>
<label>Your name: <input id="username" placeholder="Anonymous" value="User1"></label>
</div>
<div id="status" class="disconnected">Disconnected</div>
<div id="peers"></div>
<textarea id="editor" placeholder="Start typing... Collaborative edits sync in real-time!"></textarea>
<script>
// Utils
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
function randomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) color += letters[Math.floor(Math.random() * 16)];
return color;
}
// Engine init
let ydoc, ytext, webrtcProvider, idbProvider, awareness;
let debouncedSync;
let isJoined = false;
const statusEl = document.getElementById('status');
const peersEl = document.getElementById('peers');
const editor = document.getElementById('editor');
const roomInput = document.getElementById('room');
const usernameInput = document.getElementById('username');
const joinBtn = document.getElementById('join');
// Efficient diff-sync: prefix/suffix matching (great for cursor-based edits/paste)
function syncEditorToYtext() {
const oldStr = ytext.toString();
const newStr = editor.value;
if (oldStr === newStr) return;
// Abuse mitigation: limits
if (newStr.length > 10000) {
editor.value = newStr.slice(0, 10000);
return;
}
const insertLen = newStr.length - oldStr.length;
if (Math.abs(insertLen) > 500) return; // Max change per update
// Compute common prefix
let prefixLen = 0;
const minLen = Math.min(oldStr.length, newStr.length);
while (prefixLen < minLen && oldStr[prefixLen] === newStr[prefixLen]) prefixLen++;
// Compute common suffix
let suffixLen = 0;
while (suffixLen < minLen - prefixLen &&
oldStr[oldStr.length - 1 - suffixLen] === newStr[newStr.length - 1 - suffixLen]) {
suffixLen++;
}
// Apply delete (middle section)
const delStart = prefixLen;
const delLen = oldStr.length - prefixLen - suffixLen;
if (delLen > 0) {
ytext.delete(delStart, delLen);
}
// Apply insert (middle section)
const insStr = newStr.slice(prefixLen, newStr.length - suffixLen);
if (insStr) {
ytext.insert(delStart, insStr);
}
// Enforce max size
if (ytext.length > 10000) {
ytext.delete(10000, ytext.length - 10000);
}
}
// Update editor from Yjs (preserve cursor approx)
function updateEditorFromYtext() {
const cursor = editor.selectionStart;
const newValue = ytext.toString();
editor.value = newValue;
editor.setSelectionRange(Math.min(cursor, newValue.length), Math.min(cursor, newValue.length));
}
// Update peers list
function updatePeers() {
const states = awareness.getStates();
peersEl.innerHTML = `<strong>Peers (${states.size}):</strong> ${Array.from(states.values())
.map(s => s.user?.name || 'Anonymous')
.join(', ') || 'None'}`;
}
// Join room
function joinRoom() {
if (isJoined) return;
isJoined = true;
const roomId = roomInput.value.trim() || 'default';
const userName = usernameInput.value.trim() || 'Anonymous';
// Init Yjs doc
ydoc = new Y.Doc();
ytext = ydoc.getText('content');
// Offline persistence
idbProvider = new IndexeddbPersistence(`collab-${roomId}`, ydoc);
// WebRTC provider
webrtcProvider = new WebrtcProvider(roomId, ydoc, {
signaling: ['wss://signaling.yjs.dev'],
maxRetries: 3
});
awareness = webrtcProvider.awareness;
// Set local awareness
awareness.setLocalStateField('user', {
name: userName,
color: randomColor()
});
// Bindings
debouncedSync = debounce(syncEditorToYtext, 150);
editor.addEventListener('input', debouncedSync);
ytext.observe(updateEditorFromYtext);
awareness.on('change', updatePeers);
// Status
webrtcProvider.on('status', ({ status }) => {
statusEl.textContent = status === 'connected' ? 'Connected (Synced!)' : 'Connecting...';
statusEl.className = status === 'connected' ? 'connected' : 'disconnected';
});
updatePeers();
updateEditorFromYtext(); // Initial
}
// Events
joinBtn.addEventListener('click', joinRoom);
// Auto-join on Enter in room input
roomInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') joinRoom();
});
</script>
</body>
</html>
Feature Verification
- Test Peer Discovery: Different tabs with same room → peers list updates on connect.
- Delta Compression/Causality: Edit in one tab → others see only changed parts instantly (inspect Network/WebRTC internals).
- Offline Reconciliation: Offline one tab, edit both, reconnect → merges without conflicts.
- Abuse: Try pasting 10k+ chars → truncates. Rapid spam → debounced.
Extension Points
- Rich Text/Cursors: Replace
<textarea> with ProseMirror + y-prosemirror.
- Custom Signaling: Run your own
y-websocket server.
- No Public Signaling: Use manual SDP exchange or STUN/TURN-only (limited).
- Advanced Abuse: Track per-peer update rates, close channels via
provider.destroyPeer(clientId).
This is production-ready for small-medium groups. Source-inspired by Yjs docs/examples. Built by Sherlock @ Trailblazer Labs.