Building a Real-Time Collaboration System

claude-opus-47/30/2026@demo4 turns
1
U
I'm building a collaborative text editor like Google Docs. How do I handle two people editing the same document at the same time?
2
A
This is one of the hardest problems in distributed systems! Let's work through it: THE PROBLEM: User A inserts hello at position 5. User B inserts world at position 5. What should the final text be? Naive approaches fail: Last write wins loses data, locking kills collaboration. The solution: CRDT (Conflict-free Replicated Data Type). KEY INSIGHT: Use unique IDs, not positions! Instead of position 5, each operation has: id (unique operation ID), character (what to insert), afterId (insert after this operation), timestamp, userId. How it works: 1. Generate unique IDs (UUID or timestamp plus userId) 2. Reference previous operations, not positions 3. When receiving ops, insert them based on IDs 4. If two ops conflict, use deterministic ordering Want me to implement the full CRDT structure?
3
U
Yes! But what about deletions? How do we handle deleting text without messing up everyone else's positions?
4
A
THIS IS WHERE CRDTS GET REALLY CLEVER! The problem with deletions: State: ABCD User A inserts X at position 2: ABXCD User B deletes position 3 (which was C) What position does B delete now? Solution: Tombstones! Interface TextOp has: id, character, afterId, deleted (boolean tombstone!), timestamp, userId. class CRDTDocument: ops is a Map of string to TextOp. applyOp(op): adds op to the map. deleteOp(opId): finds the op and sets deleted equals true (MARK AS DELETED). render(): filters out deleted ops (SKIP TOMBSTONES), sorts by afterId references, joins characters. How it handles our conflict: Initial: ABCD equals opA, opB, opC, opD A inserts X after B: opA, opB, opX, opC, opD equals ABXCD B deletes C: opC.deleted equals true Final: opA, opB, opX, opD equals ABXD The beauty: Everyone sees the same final state, no position-based conflicts, deleted items stay in the structure (as tombstones), convergence is guaranteed! Tradeoff: More memory (tombstones accumulate). Solution: Periodic compaction (when no one is editing). Want to implement the full collaboration server?