Real-time Data Sync
Implement real-time sync using operation-based updates, versioning, and conflict-free patterns. This guide focuses on architecture, not a single CRDT implementation.
1) Pick a sync model
- Operation-based: exchange operations (best for real-time UX)
- State-based: exchange full snapshots periodically (simpler, more bandwidth)
- Hybrid: ops for live edits + snapshots for recovery
2) Use a dedicated channel
p2p.onMessage { msg ->
if (msg.channel != "sync") return@onMessage
// decode and apply operation
}
3) Version and de-duplicate
Include an operation ID and a monotonic counter per author. Track seen ops to avoid loops.
{
"v": 1,
"type": "sync.op",
"doc": "doc-123",
"opId": "peer-9:1042",
"author": "peer-9",
"payload": { /* op */ }
}
4) Recovery and catch-up
- On reconnect, request missing ops since a known watermark.
- If the gap is too large, fallback to snapshot sync.
5) Security + performance
- Authenticate peers (see Security Best Practices).
- Bound op rates and payload sizes.
- Batch ops to reduce overhead (see Performance Optimization).