The Real-time Collaboration Engineer builds systems where multiple users edit shared state simultaneously without conflicts. The hard problem is conflict resolution when two users change the same data at the same time with network latency between them. CRDTs (Conflict-free Replicated Data Types) solve this mathematically: operations can be applied in any order and will always converge to the same result.
Yjs CRDT Integration
// Yjs: the most production-ready CRDT library for JavaScript
// Works with Tiptap, ProseMirror, Monaco, CodeMirror, Quill
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
import { MonacoBinding } from 'y-monaco';
// Create shared document
const ydoc = new Y.Doc();
// Connect to sync server
const provider = new WebsocketProvider(
'wss://sync.example.com', // Your y-websocket server
'document-room-id', // Room = document identifier
ydoc,
{ connect: true }
);
// Awareness: presence indicators (cursor position, user info)
const awareness = provider.awareness;
awareness.setLocalStateField('user', {
name: currentUser.name,
color: userColor,
cursor: null,
});
// Listen for other users' presence
awareness.on('change', () => {
const states = Array.from(awareness.getStates().entries());
const onlineUsers = states
.filter(([clientId]) => clientId !== ydoc.clientID)
.map(([, state]) => state.user);
updatePresenceIndicators(onlineUsers);
});
// Bind to Monaco editor
const monacoBinding = new MonacoBinding(
ydoc.getText('monaco'),
editor.getModel()!,
new Set([editor]),
awareness
);
Y-WebSocket Server
// Minimal y-websocket server (Node.js)
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import * as Y from 'yjs';
import { setupWSConnection } from 'y-websocket/bin/utils';
const server = createServer();
const wss = new WebSocketServer({ server });
// In-memory document store (replace with Redis + persistence in production)
const docs = new Map<string, Y.Doc>();
wss.on('connection', (ws, req) => {
// Room name extracted from URL: /room/document-id
const roomName = req.url?.slice(1) ?? 'default';
if (!docs.has(roomName)) {
docs.set(roomName, new Y.Doc());
}
setupWSConnection(ws, req, {
docName: roomName,
gc: true, // Garbage collect deleted content
});
});
server.listen(1234);
Shared State Patterns
// Yjs data structures for different use cases
const ydoc = new Y.Doc();
// Collaborative text editor
const text = ydoc.getText('content');
text.insert(0, 'Hello, world!');
// Shared JSON object (settings, metadata)
const settings = ydoc.getMap('settings');
settings.set('theme', 'dark');
settings.observe(event => {
console.log('Settings changed:', event.keysChanged);
});
// Ordered list (tasks, slides, sections)
const tasks = ydoc.getArray('tasks');
tasks.push([{ id: '1', title: 'Task 1', done: false }]);
// Persist to backend on change (debounced)
let saveTimeout: NodeJS.Timeout;
ydoc.on('update', (update: Uint8Array) => {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(() => {
const state = Y.encodeStateAsUpdate(ydoc);
saveToDatabase(roomId, state); // Store binary Yjs state
}, 500);
});