Design a Collaborative Text Editor
The Prompt
Design a collaborative document editor where multiple users edit simultaneously with real-time sync, cursor presence, and conflict resolution.
Core Challenges
- Conflict resolution ā what happens when two users edit the same paragraph?
- Latency ā edits must feel instant locally while syncing globally
- Presence ā show who's editing where
- History ā undo/redo must work correctly in a multi-user context
Conflict Resolution Approaches
Operational Transform (OT)
Transform operations against concurrent operations:
User A: insert('X', pos=3)
User B: insert('Y', pos=1)
B's operation shifts A's position:
A transformed: insert('X', pos=4)- Used by Google Docs
- Complex to implement (O(n²) worst case for n concurrent ops)
- Requires a central server for ordering
CRDT (Conflict-free Replicated Data Types)
Data structure that merges automatically without conflicts:
Each character has a unique ID: (userId, counter)
Characters are sorted by fractional indices
Insert: generate a position between neighbors
Delete: mark as tombstone (soft delete)- Used by Figma, Notion
- More bandwidth (metadata per character)
- Works peer-to-peer (no central server required)
Architecture
Local Editor State
ā (immediate)
Local CRDT/OT Engine
ā (debounced)
WebSocket ā Server ā Broadcast to peers
ā
Remote CRDT/OT Engine
ā
Remote Editor StatePresence System
// Broadcast cursor position
ws.send(JSON.stringify({
type: 'presence',
userId: currentUser.id,
cursor: { line: 5, column: 12 },
selection: { start: { line: 5, column: 8 }, end: { line: 5, column: 12 } }
}));Render remote cursors with colored labels:
- Throttle presence updates to ~50ms
- Remove stale cursors after 30s timeout
- Use CSS animations for smooth cursor movement
Trade-offs
| Factor | OT | CRDT |
|---|---|---|
| Complexity | Algorithm complex | Data structure complex |
| Server | Required (ordering) | Optional (P2P possible) |
| Bandwidth | Lower | Higher (metadata) |
| Undo | Natural (reverse ops) | Complex (need additional layer) |
| Proven at scale | Google Docs | Figma, Notion |
The senior insight: you don't implement OT or CRDT in an interview ā you discuss which approach fits the constraints and why.