Implemented a backend-first real-time collaboration system that supports concurrent edits, conflict-free merges, offline sync replay, and low-latency multi-user synchronization.
- CRDT model: RGA-style text CRDT using tombstones for conflict-free insert/delete merge
- LWW registers: Deterministic Last-Writer-Wins merges for note fields and spreadsheet cells
- Versioned operation log: Server-versioned operations for offline replay and delta sync
- Vector clock tracking: Per-actor counters in document state for merge awareness
- Optimistic concurrency: Retry logic for concurrent save races
models/CollaborativeDocument.jsservices/realtimeCollaborationService.jsroutes/realtimeCollaboration.js
server.js
POST /api/realtime-collab/documents- create collaborative documentGET /api/realtime-collab/documents/:id- get snapshot/statePOST /api/realtime-collab/documents/:id/sync- submit offline or realtime opsGET /api/realtime-collab/documents/:id/changes?sinceVersion=N- fetch deltasPOST /api/realtime-collab/documents/:id/presence- update online presence
- Client → Server:
collab:joincollab:operationscollab:leave
- Server → Client:
collab:snapshotcollab:operationscollab:ackcollab:presencecollab:error
- Redis pub/sub channel:
expenseflow:collab - Cross-instance operation fan-out with
serverInstanceIddedupe to avoid local echo duplication
Clients can queue operations while offline and replay them via /sync. The server performs idempotent merges using operation IDs and returns authoritative versions and deltas.
- Concurrent text inserts at same position resolve deterministically by operation ID ordering
- Deletes are tombstone-based and idempotent
- Cell/field updates resolve deterministically by
(lamport, actorId, opId)ordering
- Room-based websocket broadcasting minimizes unnecessary fan-out
- Redis pub/sub enables horizontal scaling across multiple API instances
- Versioned change feed allows efficient incremental sync