We are designing an offline-first application that must handle synchronization conflicts when multiple devices edit the same data while offline. We have two main approaches: Operational Transformation (OT) and Conflict-Free Replicated Data Types (CRDTs). We also need to consider how to merge changes and the user experience (UX) during and after conflict resolution.
Let's break down the problem:
-
Understanding the Data Model: The type of data we are syncing will influence the choice between OT and CRDTs. For example:
- OT is well-suited for collaborative editing of text (like Google Docs) and requires a central server or a well-defined protocol for resolving operations.
- CRDTs are more general and can handle a variety of data structures (lists, sets, maps, registers) without requiring a central server, but they may have higher metadata overhead.
-
Conflict Resolution Strategies:
- OT: Resolves conflicts by transforming operations so that they can be applied in any order and still converge. Requires that all operations are eventually delivered to all replicas and in the same order (or transformed appropriately). Typically used in a client-server model where the server orders operations.
- CRDTs: Designed to be commutative, associative, and idempotent, so that any order of operations leads to the same state. There are two main types: state-based (send entire state) and operation-based (send operations). They avoid conflicts by design.
-
Merging:
- In OT, merging is done by applying transformed operations. The application must handle the transformation functions for each operation type.
- In CRDTs, merging is automatic because the data structure is designed to handle concurrent updates.
-
User Experience:
- During Offline: The app should allow all changes locally and queue them for sync.
- On Reconnection: The app should sync and resolve conflicts. The user might be aware of conflicts if the resolution is not seamless (e.g., if two people edit the same text and the merge is not what one of them expected). We must decide when to involve the user.
- Post-Conflict: If the automatic resolution is not acceptable (e.g., in cases where the data is critical and the system cannot decide), we may need to present the conflict to the user for manual resolution.
-
Hybrid Approaches: Sometimes a combination of both or other strategies (like last-write-wins with timestamps) might be used for simplicity.
Given the complexity, let's design a policy that can be adapted to the specific use case.
Step 1: Choose the Right Algorithm
We must decide between OT and CRDTs. Consider:
-
OT:
- Pros: Efficient for text (only send operations), well-understood for collaborative editing.
- Cons: Requires a central server to order operations (or a complex decentralized algorithm), transformation functions can be complex to implement for every operation.
-
CRDTs:
- Pros: Decentralized, no single point of failure, eventual consistency without coordination. Easier to implement for certain data types (like sets, maps) because the merge logic is built-in.
- Cons: Metadata overhead (like vector clocks or unique IDs) can be high, and for text, the CRDT algorithms (like RGA, Logoot) can be complex and have performance issues.
If the data is primarily text (like a note-taking app), OT might be more efficient. If the data is more structured (like a to-do list with tasks that have properties) and we want to allow multiple devices to edit different parts without conflict, CRDTs might be better.
Alternatively, we can use a hybrid: use CRDTs for the overall data structure (e.g., a map of documents) and OT for the text inside each document.
Step 2: Define the Data Model and Operations
Let's assume we are building a note-taking app with the following data model:
- Each note has:
id: unique identifier (UUID)
title: string
content: string (rich text or plain)
lastModified: timestamp (for last-write-wins fallback)
version: for optimistic concurrency (optional)
We might also have a list of notes (so a collection of notes).
For the note content (text), we want to support collaborative editing. For the note metadata (title, etc.), we might have simpler conflicts.
Step 3: Conflict Resolution for Different Parts
-
Note Content (text): Use OT for real-time collaboration and offline sync. We can use an existing library (like ShareDB for OT or a CRDT library for text). However, note that OT requires a central server to order operations? Actually, for offline-first, we need to sync between multiple clients. We can have a peer-to-peer or client-server model.
If we use a client-server model, the server can be the central authority for ordering operations. But if we want offline-first and peer-to-peer, we might need a decentralized OT algorithm (which is complex) or use CRDTs for text.
Given the complexity, let's assume we are using a client-server model for simplicity, even in offline-first. The server is available when online, and when offline, clients queue operations. When reconnecting, the client sends its queued operations to the server, which transforms them against other operations that happened in the meantime and broadcasts the transformed operations.
However, if we want true offline-first without a server always available, we might need to use CRDTs for the text as well.
Given the trend and simplicity of CRDTs for decentralized scenarios, let's choose CRDTs for the text content. There are efficient CRDTs for text (like RGA with unique identifiers per character). But note that CRDTs for text can have high metadata (each character might have a unique ID and position identifier). Alternatively, we can use a sequence CRDT that uses a tree of identifiers (like LSeq or Logoot) to reduce overhead.
But for simplicity in this design, let's assume we use a library that provides a text CRDT.
-
Note Metadata (title, etc.): These are single values. We can use a last-write-wins (LWW) strategy based on timestamps, but timestamps can be problematic if clocks are not synchronized. Alternatively, we can use a CRDT register (specifically, a LWW register) that uses a combination of timestamp and node ID to break ties.
For the collection of notes (the list of notes), we can use a CRDT set (or map) so that adding, removing, and updating notes (by ID) can be merged automatically.
Step 4: Sync Protocol
We need a sync protocol that works offline and online.
- When online, the client connects to the server (or peers) and exchanges state/operations.
- When offline, the client records all local changes (operations) and applies them immediately to the local state (which is a CRDT, so it can handle concurrent updates).
- On reconnection, the client sends its local operations (or state, depending on the CRDT type) to the server/peers and receives the remote operations/state. The CRDT merge function will automatically resolve conflicts.
Step 5: User Experience for Conflicts
Since we are using CRDTs, most conflicts are resolved automatically without user intervention. However, there might be cases where the automatic resolution is not what the user expects (e.g., two users editing the same title simultaneously, and the CRDT register might keep one version and discard the other). The user might not be aware that their change was overwritten.
To improve UX:
-
Real-time Collaboration Indicators: When online, show who is editing the same note (like a cursor or presence).
-
Offline Change Indicators: When offline, show that changes are pending sync.
-
Conflict Awareness: If a conflict occurred and the automatic resolution resulted in a loss of data (like a title being overwritten), we might want to notify the user after sync. However, note that with CRDTs, we don't have traditional conflicts because the merge is defined. But from the user's perspective, they might have expected their change to be preserved.
For example, in a LWW register, if two users update the title at the same time (without knowing about each other), the one with the later timestamp wins. The user whose change was lost might be upset.
Solutions:
- Use a more advanced CRDT that can keep both changes? For a single string, that's not possible without making the title a list of characters (which doesn't make sense). So we have to choose one.
- We can keep a history of changes and allow the user to see the previous version and the two conflicting changes, and then choose. But that would be a manual conflict resolution, which goes against the automatic nature of CRDTs.
Alternatively, we can design the data model to avoid single points of failure. For example, instead of a single title, we could have a title that is a list of edits (but that would be overkill). Or we can accept that in some cases, the user's change might be lost and try to minimize that by using a reliable timestamp (like a logical clock) that is more likely to reflect the order of events.
Another idea: use a "multi-value register" that keeps both values? But then how to display? We could show both titles? That might not be desirable.
Given the complexity, it might be acceptable to use LWW and educate users that the last saved change wins. We can also try to use a server timestamp when online, but when offline, we have to use local time. We can use a hybrid: when offline, use a local logical clock (like a counter) and when syncing, the server can assign a timestamp? But that would break the decentralized nature.
Alternatively, we can use a CRDT that uses a vector clock to determine causality and then if two updates are concurrent, we keep both? But for a register, we cannot keep two strings. So we have to choose one.
Given these challenges, maybe for the title we don't use a CRDT but use a more manual conflict resolution? But then we break the consistency.
Let's stick with LWW register for title and note that the user might lose changes. We can mitigate by:
- Making the title less critical (maybe it's not edited as often as the content).
- Providing an edit history (so the user can recover the old title).
Step 6: Implementation Steps
-
Choose a CRDT library that supports:
- Text (for content) with operation-based or state-based sync.
- LWW register (for title and other single-value fields).
- Set or map for the collection of notes.
There are libraries like Automerge (which uses JSON CRDTs and supports text) or Yjs (which is for text and also supports shared types for other data). Yjs is more focused on text but has providers for other data types. Automerge is more general for JSON.
Given our data model (notes with title and content), we can use:
- For the note content: a shared text type (from Yjs) or a string in Automerge (which is a CRDT string).
- For the title: a shared string (in Automerge, it's a string which is a CRDT) but note that Automerge's string is a sequence of characters, so it's like the content. But we don't need character-level merging for the title? Actually, we do if two users edit the title at the same time? But the title is a single string, and if two users change the entire title, we want one to win? With Automerge, if two users set the entire title, it will keep the one that was set last (based on the internal logical clock). But if they edit the title character by character, then it will merge the characters? That might not be what we want.
Alternatively, we can treat the title as a single operation (set the whole string) and then the CRDT will keep the one with the latest timestamp. But if two users set the entire title, we lose one.
If we want to allow two users to edit the title at the same time and merge their changes (like appending), then we need the title to be a sequence of characters. But that might lead to mixed titles (like "HelloWorld" from "Hello" and "World"). That might be acceptable? Or we can design the title to be edited as a whole, not character by character.
Given the complexity, let's assume the title is edited as a whole (set the entire string). Then we can use a LWW register. But note that Automerge's string is a sequence of characters and if two users set the entire string, it will keep the one that was set last (by logical time). However, if they make partial edits (like inserting at the beginning), then it will merge as a sequence. So we have to decide on the editing model for the title.
To avoid confusion, we can decide that the title is not edited character by character in a collaborative way. Instead, when the user edits the title, we set the entire title. Then, if two users set the entire title, we keep the one that was set last (by the logical clock). This is the same as a LWW register.
So we can use Automerge's string for both title and content, but for title, we will only allow setting the entire string (not character-level edits). But that might be restrictive.
Alternatively, we can use a separate LWW register for the title and a text CRDT for the content. But Automerge doesn't have a separate LWW register type; it has a string that is a CRDT. We can use a string for the title and only allow set operations (not insert/delete). But the user might try to edit in the middle? We can intercept and set the entire string when the user finishes editing (on blur) or we can treat each keystroke as an operation? That would lead to character-level merging for the title, which we might not want.
Step 7: Sync Process
We assume a client-server model for simplicity, but the CRDTs work in a decentralized way too.
-
Local Changes: When offline, the user makes changes. The client applies these changes to the local CRDT state and records the operations (or state changes) in a log for syncing.
-
Reconnection: When online, the client sends its local operations (or the entire state, depending on the CRDT type) to the server. The server merges the incoming state with its own state (using the CRDT merge function) and then sends back the updated state (or the operations that the client missed). The client then applies the merged state.
Alternatively, in a peer-to-peer setup, each client exchanges operations with its peers.
-
Conflict Resolution: Since we use CRDTs, the merge is automatic and deterministic. There is no conflict in the sense of multiple resolutions, but the result might not be what all users expect.
Step 8: UX Considerations
-
Visual Feedback:
- Show a sync status (online, offline, syncing).
- When offline, show that changes are local only (maybe with a different color or icon).
- When syncing, show a progress indicator.
-
Conflict Notification:
- If a change is overwritten (like the title), we can show a toast notification: "Your title change was overwritten by [user] at [time]."
- We can also provide a way to view the history of changes and restore an old version.
-
Undo/Redo: The CRDT might support undo/redo locally, but after sync, the history might become complex. We need to design an undo/redo that works across sync. This is non-trivial with CRDTs because the state is a function of all operations. We might need to store the entire history and then allow undo of any operation (like Automerge does). But that can be heavy.
Alternatively, we can limit undo/redo to local changes that haven't been synced yet? But after sync, the remote changes are interleaved, so undoing a local change might not be possible if it has been transformed by remote changes.
Given the complexity, we might not support undo/redo across sync, or we can support a limited form (like undoing the last operation, but only if it hasn't been overwritten by a remote operation?).
This is a hard problem. We might decide to not support undo/redo for now.
Step 9: Summary of Policy
-
Data Types:
- Note content: text CRDT (character-level, supporting concurrent edits).
- Note title: LWW register (set entire string, last write wins by logical clock).
- Note collection: CRDT set (by note ID) so that adding and removing notes is conflict-free.
-
Sync Protocol:
- Use operation-based sync (send operations) or state-based (send state) depending on the CRDT library and network conditions.
- When online, sync with the server (or peers) periodically or on every change (if real-time collaboration is needed).
- When offline, queue operations and apply them locally.
-
Conflict Resolution:
- For text: automatic merge by the CRDT (characters are interleaved based on unique identifiers and positions).
- For title: last-write-wins by logical clock (a combination of timestamp and node ID). We assume that the logical clock is increasing and unique per node.
- For note collection: set operations are commutative, so adding and removing notes is conflict-free.
-
UX:
- Show sync status and pending changes.
- Notify when a user's change to the title (or other LWW fields) is overwritten.
- Provide an edit history for each note (store every version? or just the last few?).
- Allow manual resolution for critical data? We might not have manual resolution because CRDTs are automatic. But for the title, if the user's change is lost, they can manually set it again.
Alternatively, we can design the title to be a list of proposals (like a set of title suggestions) and then the user can choose one? That would be a different data model.
Given the time, we stick with LWW and notify on overwrite.
Step 10: Implementation Considerations
-
Choose a CRDT library that is well-maintained and fits the data model. For example:
- Automerge: general purpose JSON CRDT, supports text, maps, sets, etc.
- Yjs: focused on text but also has shared types for other data (like map, array, set). It uses a different algorithm (based on YATA) but is also a CRDT.
Both have JavaScript implementations and can be used in the browser and Node.js.
-
We need a backend that can store the CRDT state and distribute updates. For Automerge, we can use a central server that stores the document state and propagates changes. For Yjs, we can use a WebSocket server or a database that supports Yjs (like Y-webrtc or Y-redis).
-
For offline support, we store the CRDT state in IndexedDB (in the browser) and sync when online.
Step 11: Example Flow
- User A and User B are editing the same note offline on their devices.
- User A changes the title to "Title A" and the content to "Hello from A".
- User B changes the title to "Title B" and the content to "Hello from B".
- They both go online and sync with the server.
- The server receives both updates. The CRDT merge for the title will keep the one with the later logical clock (say User B's). The content will be merged by the text CRDT: if they edited the same part of the text, the characters will be interleaved based on their unique IDs. If they edited different parts, both changes are preserved.
- After sync, User A sees that their title change was overwritten (notification: "Your title change was overwritten by User B") and the content might be a mix of both changes (if they overlapped) or both changes preserved (if they were in different places).
Conclusion
This policy uses CRDTs for automatic conflict resolution, which is suitable for offline-first applications. The user experience is improved by providing feedback about sync status and overwritten changes. However, the user must understand that in some cases (like the title) their change might be lost and they might need to reapply it.
We must also consider the performance of CRDTs, especially for large documents. The metadata overhead and the complexity of the merge algorithm might be a concern.
Finally, we should test the policy with real users and adjust based on their feedback.
Offline-First Sync Conflict Policy: OT/CRDTs, Merges, and UX
1. Guiding Principles
- Offline-first: All edits work offline with immediate local feedback.
- Convergence: All replicas eventually reach identical state without manual intervention.
- User intent preservation: Minimize unexpected data loss; make conflicts visible when automatic resolution is ambiguous.
- Performance: Low latency local edits; efficient sync bandwidth.
- Simplicity: Prefer CRDTs for decentralized scenarios; OT only when centralized coordination is acceptable.
2. Algorithm Selection: OT vs CRDTs
| Criteria | OT (Operational Transformation) | CRDTs (Conflict-Free Replicated Data Types) |
|---|
| Architecture | Client-server (central order required) | Decentralized (peer-to-peer or client-server) |
| Conflict handling | Transform ops against concurrent ops | Commutative, associative, idempotent merges |
| Metadata overhead | Low (ops only) | Moderate to high (per-element IDs, vector clocks) |
| Text editing | Proven (Google Docs, Etherpad) | Complex but viable (Yjs, Automerge) |
| Structured data | Custom per operation type | Built-in types (LWW-register, set, map, list) |
| Undo/Redo | Complex across replicas | Simpler with operation history |
| Network model | Requires reliable delivery & ordering | Tolerates arbitrary delays, duplication |
Recommendation:
- Use CRDTs for most offline-first apps (decentralized, simpler consistency).
- Use OT only if:
- You have a reliable central server.
- Text editing is primary and you need character-level merge efficiency.
- You can guarantee operation delivery order.
3. Data Type Strategies
| Data Type | Recommended CRDT | OT Alternative | Merge Behavior |
|---|
| Text/rich text | Sequence CRDT (RGA, LSeq, Yjs Text) | OT for text (e.g., operational | Character/object-level interleaving; concurrent inserts ordered by unique ID. |
| | transformation) | |
| Single value | LWW-Register (Last-Write-Wins) | OT "set" operation | Timestamp + node ID breaks ties. Keep both values? → No, but log conflict. |
| (timestamp + node ID) | | |
| List/array | Sequence CRDT or Observed-Remove Set | OT list ops (insert/delete) | Concurrent inserts preserved; deletes tracked with tags. |
| Set | 2P-Set or OR-Set | OT add/remove | Adds survive unless explicitly removed; no duplicate adds. |
| Map/dictionary | Map CRDT (value per key is CRDT) | OT per-key ops | Per-key independent merges (use LWW-register for values). |
| Counter | PN-Counter (positive/negative) | OT increment/decrement | Sum all increments/decrements. |
4. Merge Policy & Conflict Detection
Automatic Resolution (No User Involvement)
- CRDTs: Always automatic. No "conflict" concept—all operations commute.
- OT: Requires transformation functions; automatic if all ops are delivered.
When to Alert the User
Despite automatic merges, some merges may violate user expectations:
- Non-idempotent user intent: e.g., two users delete the same paragraph but for different reasons → one deletion wins, but user might expect both deletions to be noted.
- Semantic conflicts: e.g., two users set the same field to different values (LWW-register). The user whose value lost may want to know.
- High-value data: Financial amounts, medical records—require audit trail.
- Loss of meaningful work: e.g., User A carefully crafts a title; User B rapidly overwrites it. A should know.
Alert thresholds:
- Field-level: LWW-register where local value ≠ merged value.
- Structural: If more than X% of a document’s elements were replaced/concurrent-modified.
- User-configurable: “Notify me when my changes are overwritten.”
5. User Experience Design
During Offline Edit
- ✅ Immediate local feedback (optimistic UI).
- ✅ Clear indicator of offline status (e.g., grayed-out sync icon).
- ✅ Queue operations in IndexedDB / localStorage with exponential backoff retry.
- ✅ Allow bulk discarding of pending changes before sync (“Revert all local changes”).
On Reconnection & Sync
- Silent merge (no UI) if:
- Changes were to disjoint parts of data (e.g., different fields, non-overlapping text regions).
- Using CRDTs and merge is unambiguous (e.g., set additions).
- Non-blocking notification (toast) if:
- Your change was overwritten in an LWW field.
- Example: “Your title change was overwritten by Alex 2 minutes ago.”
- Conflicting change dialog (rare, high-stakes):
- Show side-by-side diff of your change vs. incoming change.
- Let user choose: keep mine, keep theirs, keep both (if data model allows), or merge manually.
- Example: concurrent edits to a single-line field where both values matter (e.g., “Assigned to: Alice vs. Bob”).
Post-Conflict Navigation
- History viewer: Show a timeline of changes with authors/timestamps.
- Undo support: Limit to local changes before sync? Or full undo (requires full op history stored).
- “Accept Override” button: If your change was overwritten, one-click to reapply your value (creates new operation).
6. Sync Implementation Details
Metadata Requirements
- Per operation:
- Unique operation ID (UUID + site ID + counter).
-Timestamp (physical or logical, e.g., hybrid logical clock).
-Causal context (vector clock or dot map) for dependency tracking.
- Per replica: Site ID (persistent UUID), clock.
Sync Protocol
- Connection → exchange “hello” with current state hash / version vector.
- Gap detection → request missing ops/state.
- Transport:
- Op-based: Send unresolved operations (with dependencies). Better for active editing.
- State-based: Send full state (compressed). Better for infrequent edits or large text.
- Hybrid: State-based for initial sync, op-based thereafter.
- Ack & cleanup: After applying remote ops, send ack; garbage collect acknowledged ops.
Storage Format
- Use binary CRDT encoding (e.g., Automerge’s Uint8Array, Yjs’s update format).
- Store in IndexedDB with versioning.
- Backup/export as JSON for user portability.
7. Edge Cases & Pitfalls
| Scenario | CRDT Solution | OT Solution | UX Recommendation |
|---|
| Network partition & healing | Automatic merge via CRDT semantics | Requires op buffering & transformation | Show “sync completed” with count of merged changes. |
| Malformed ops / tampering | CRDTs reject non-conformant ops (signature check) | OT server can validate & reject | Warn user: “Invalid sync data; contact support.” |
| Clock skew (LWW) | Use hybrid logical clock (HLC) or node ID tiebreak | N/A (OT doesn’t use timestamps) | Log overwrite events; consider “merged” instead of “lost”. |
| Large binary blobs (images) | Treat as immutable blobs with content hash; LWW on metadata | OT not suitable | Sync blobs separately; metadata via CRDT. |
| Schema evolution | CRDTs tolerant (missing fields default to null) | OT requires backward-compatible ops | Migrate old documents on load; warn on incompatible changes. |
8. Monitoring & Debugging
- Log every conflict/override (anonymized) to understand merge patterns.
- Metrics: sync duration, conflict rate, op throughput, storage growth.
- Developer mode: Show CRDT state (dot map, vector clock) for debugging.
- User-facing “Sync History”: Let users see who changed what and when.
9. Recommended Stack
| Component | Recommendation | Why |
|---|
| CRDT Library | Automerge (general JSON) or Yjs (text-focused) | Automerge: flexible, supports rich types. Yjs: faster for text, better WebRTC support. |
| Transport | WebSocket (real-time) + REST (fallback) | WebSocket for ops; REST for state snapshots. |
| Storage | IndexedDB (browser) + SQLite (mobile) | Handle large CRDT states. |
| Sync Server | Optional: stateless relay (for WebSocket) or full server (for auth, storage) | If decentralized: use WebRTC or P2P mesh. If centralized: Node.js + Redis pub/sub. |
| Auth | JWT per device; bind to site ID | Prevent unauthorized state injection. |
10. Summary Policy
- Default to CRDTs for offline-first apps—they simplify consistency.
- Model each field with appropriate CRDT type (LWW for singles, sequence for text, set for tags).
- Auto-merge silently when CRDT merge is unambiguous (disjoint edits).
- Notify on overwrites for LWW fields (user’s change lost).
- Manual resolution only for high-stakes or semantically irreconcilable conflicts (rare).
- Preserve full operation history for undo and audit.
- Test with real offline scenarios: network partitions, clock skew, concurrent edits.
Final UX Principle:
The user should rarely be interrupted by sync conflicts, but never be surprised by silent data loss.
Provide transparency (“I see your change was overwritten”) and control (“undo, accept, or re-apply”) when automatic resolution doesn’t match user intent.