Offline-First Sync Conflict Policy Design
As Sherlock, built by Trailblazer Labs, I'll design a robust offline-first sync conflict policy optimized for apps like note-taking, todo lists, or collaborative documents (e.g., a decentralized Notion or Google Docs clone). The policy prioritizes seamless UX, data integrity, and minimal user intervention using CRDTs as the primary mechanism (with OT as a fallback for legacy compatibility). CRDTs are preferred over pure OT because they provide convergence without coordination, making them ideal for offline-first P2P or client-server sync.
This design assumes:
- Data types: JSON documents (e.g.,
{ content: "text", todos: [] }), lists, maps, registers.
- Sync architecture: Optimistic local updates; periodic bi-directional sync via WebSockets/HTTP to a server or P2P (e.g., via libp2p).
- Storage: IndexedDB/localStorage for offline; CRDT tombstones for garbage collection.
1. Core Principles
- Offline Optimism: All local edits apply immediately using provisional CRDT ops. No blocking UI.
- Automatic Merging: 95%+ cases resolved via CRDTs invisibly.
- User-in-the-Loop: Rare conflicts surface via non-modal UX (e.g., inline diffs).
- Eventual Consistency: Guarantee convergence across replicas.
- No Data Loss: Preserve all intents; never auto-discard.
- Performance: O(1) or logarithmic merge time; lazy GC.
| Principle | Why? | Tech |
|---|
| Preserve Intent | Users expect all changes to survive | CRDTs (no overwrites) |
| Minimal UX Friction | Offline-first means "it just works" | Auto-merge + contextual prompts |
| Scalability | Handle 100s of concurrent edits | Bounded CRDT growth + tombstones |
2. Conflict Detection
Conflicts occur when causal order can't be inferred (e.g., two devices edit the same field offline).
- Vector Clocks: Each op includes
{ clock: { replicaId: seq }, deps: [parentClocks] } for causality.
- Detection on Sync:
- Fetch remote ops since local clock.
- Replay remote ops on local CRDT → if divergence (e.g., same key mutated concurrently), flag conflict.
- Local ops pushed with transformed deps.
Pseudo-code:
function detectConflicts(localCRDT, remoteOps) {
const tempCRDT = localCRDT.clone();
for (op of remoteOps) {
if (!tempCRDT.canApply(op)) return { conflict: true, op };
tempCRDT.apply(op);
}
return { conflict: false };
}
3. Resolution Strategy: CRDTs + Merges
Primary: CRDTs for automatic, commutative merges. Use libraries like Yjs (for docs) or Automerge (JSON/CRDTs).
CRDT Types by Data Shape
| Data Type | CRDT Choice | Merge Behavior | Example |
|---|
| Text/Documents | Y.Text / Sequence CRDT | Char-wise insert/delete; auto-aligns cursors | "Hello" + "World" → "HelloWorld"; concurrent inserts interleave by pos |
| Lists/Arrays | Y.Array / Observed-Remove Set | Enable/disable items; preserves order | Todo add/delete merges without dupes |
| Maps/Objects | Y.Map / GSet/LWW-Register | Last-writer-wins (LWW) fallback for scalars | { title: "A" } + { title: "B" } → prompt merge |
| Counters | PN-Counter / GCounter | Additive; no conflicts | Votes/likes always sum |
Merge Workflow
- Local Edit:
localCRDT.apply(op) → immediate UI update.
- Sync:
Remote Ops ───┐
├─> Merger (CRDT.merge(local, remote)) ──> Converged CRDT
Local Ops ────┘
- CRDT Merge Rules:
- Commutative Apply:
merge(A + B) = merge(B + A).
- Tombstones: Deleted items marked
hidden: true (not erased) for convergence.
- LWW Fallback: For registers (e.g.,
title), bias to higher clock + user prefs (e.g., "my device wins").
- OT Fallback (for non-CRDT legacy):
- Transform ops:
op' = transform(op_local, op_remote).
- Only for text if Yjs unavailable.
Pseudo-merge (Yjs-inspired):
function mergeCRDTs(local, remote) {
const merged = local.clone();
remote.iterateOps((op) => {
if (op.isConflict(local)) {
// LWW or prompt
merged.apply(resolveLWW(op, local.get(op.path)));
} else {
merged.apply(op);
}
});
return merged;
}
Conflict Escalation:
- Auto-Resolve: 90% (e.g., list appends).
- Merge Prompt: Scalars (title) → "Keep 'A' (mine), 'B' (remote), or edit?".
- Manual Diff: Text → Inline 3-way merge view.
4. Sync Flow (State Machine)
IDLE (offline)
↓ online
FETCH ─> MERGE ─> if conflict? ─> RESOLVE ─> PUSH ─> IDLE
↓ no
AUTO-MERGE
- Pull Frequency: On app focus/online + every 5s.
- Push: Debounced (500ms) after local edits.
- Retry: Exponential backoff on failures.
5. UX Design: Frictionless & Transparent
Goal: Users rarely notice sync; conflicts feel like "helpful suggestions".
Indicators
- Sync Status Bar: "Synced" 🟢 | "Syncing..." 🔄 | "Conflict: 2 items" ⚠️.
- Live Indicators: Per-field badges (e.g., todo: "Edited on phone").
Resolution UX
| Conflict Type | UX Pattern | Example |
|---|
| Auto-Merged | Toast: "Merged 3 changes from laptop" | Invisible diff highlight (fade-out) |
| Scalar (title) | Bottom-sheet picker: [Mine] [Theirs] [Merge] [Edit] | Pre-filled hybrid: "My Title + Remote Update" |
| List | Inline list with ghosts: Strike-through remote deletes | Checkbox: "Keep all?" |
| Text | 3-way diff editor (like GitHub): <<<< MINE, ===== REMOTE, >>>>> | AI-suggested merge (optional LLM integration) |
| High-Volume | "Bulk Resolve": "Accept all remote" / "Keep mine" / "Review later" | Queue in sidebar |
Accessibility:
- ARIA labels: "Conflict resolved automatically".
- Keyboard nav for diffs.
Edge Cases UX:
- No Connection: "Edits saved locally; will sync later 🛫".
- Irresolvable (rare): Offline queue → "Manual merge needed on reconnect".
- Multi-Device: Device labels (e.g., "iPhone 2min ago").
Prototyping Tools
- Figma Mock: Sync bar + inline diff.
- Test Harness: Simulate offline edits with
navigator.onLine = false.
6. Implementation Roadmap
| Phase | Milestone | Est. Effort |
|---|
| 1 | CRDT Integration (Yjs/Automerge) | 2 weeks |
| 2 | Sync Engine + Vector Clocks | 3 weeks |
| 3 | UX Components (diff/merge UI) | 2 weeks |
| 4 | E2E Tests (conflict sim) | 1 week |
| 5 | P2P Extension (optional) | +4 weeks |
Metrics for Success:
- Merge success rate: >95% auto.
- User intervention: <1% sessions.
- Sync latency: <500ms.
This policy scales from solo use to 10-user collab. For specifics (e.g., schema), provide your data model! Questions?