We are going to discuss how to use CRDTs (Conflict-free Replicated Data Types) safely.
We'll cover:
Type choices: which CRDT type to choose for a given problem?
Convergence guarantees: what do we mean by convergence and what are the guarantees?
Storage trade-offs: memory and storage implications of different CRDTs.
Tests: how to test CRDT implementations?
Let's break it down.
Type Choices:
There are two main families of CRDTs:
a. State-based (Convergent): Each replica maintains a state, and the merge function is commutative, associative, and idempotent.
Examples: G-Counter, PN-Counter, G-Set, 2P-Set, OR-Set, etc.
b. Operation-based (Commutative): Each replica sends operations that are commutative when applied in any order.
Examples: Increment/Decrement for counters, add/remove for sets (with unique tags), etc.
How to choose?
If you have a reliable network and can deliver operations in order (or if you can make operations commutative) then operation-based might be more efficient in terms of bandwidth.
If you have limited bandwidth and can periodically synchronize full states (or if the state is small) then state-based might be simpler.
However, note that operation-based CRDTs require that operations are delivered exactly once and in any order (if they are commutative) but sometimes they require causal delivery (for more complex ones).
State-based CRDTs require that the state can be merged and that the merge function is a join-semilattice (i.e., commutative, associative, idempotent).
Also, consider the data type you need:
Counters: G-Counter (grow-only) or PN-Counter (positive-negative) for state-based. For operation-based, you can have increment/decrement operations that are commutative if you use unique tags per replica? Actually, for operation-based counters, you can use a similar idea as G-Counter but with operations that are increment by a value and then you need to track the increments per replica? Alternatively, you can use a PN-Counter which is two G-Counters (one for increments, one for decrements) and then the operations are also state-based?
Actually, operation-based CRDTs for counters are less common because the state-based ones are simple and the state (a map from replica id to count) is not too big if the number of replicas is bounded.
Sets:
G-Set (grow-only set): only add, no remove. State-based: just a set. Operation-based: add operations.
2P-Set (two-phase set): add and remove, but once removed cannot be added again. State-based: two sets (added and removed). Operation-based: add and remove operations (but note: if you remove and then add again, it won't work because the remove is permanent).
OR-Set (observed-remove set): supports add and remove, and you can add again after remove. State-based: each element is associated with a set of unique tags (per add) and then you remove by marking a tag as removed. Operation-based: you need to track unique tags for each add and then remove by tag.
Registers (single-value):
LWW-Register (last-write-wins): state-based: (value, timestamp) and merge by taking the one with the latest timestamp. But note: this requires synchronized clocks and may yield non-intuitive results if clocks are not synchronized.
Alternatively, you can use a state-based register that uses a unique ID (like replica id + counter) to break ties.
Maps: can be built from other CRDTs (like a map of CRDTs) or as a more complex CRDT.
Convergence Guarantees:
CRDTs are designed to achieve eventual consistency. The guarantees are:
Convergence: All replicas that have applied the same set of updates (in any order) will eventually reach the same state.
For state-based: the merge function must be a join-semilattice (commutative, associative, idempotent). The state must have a join operation that is the least upper bound of two states. The initial state is the bottom element.
For operation-based: the operations must be commutative and must be delivered exactly once (or at least once, but then idempotence of the operation application is required). Sometimes causal delivery is required (for example, for OR-Set to work correctly, you need to know the set of tags that have been observed, so operations might need to be delivered in causal order).
However, note that some operation-based CRDTs (like the ones that rely on unique tags) can work with unordered delivery as long as the operations are designed to be commutative and the replica can track the necessary metadata.
Storage Trade-offs:
State-based CRDTs:
The state must be stored and transmitted during synchronization. This can be large if the CRDT is complex (like OR-Set with many elements and tags) or if there are many replicas (like G-Counter with one counter per replica).
However, they are simple to implement because the merge is just a join.
Operation-based CRDTs:
The state is usually smaller because it doesn't need to store the entire history (only the current state and some metadata for the operations). But note: some operation-based CRDTs (like OR-Set) still need to store the set of tags for each element, which can be large.
The operations must be stored until they are delivered to all replicas? Not necessarily, because once an operation is applied, the state is updated and the operation can be discarded. But in practice, you might need to store operations for a while to handle duplicates or to ensure causal delivery.
In general, state-based CRDTs might have larger state but simpler merge. Operation-based CRDTs might have smaller state but more complex operation handling (ensuring delivery, ordering, etc.)
Tests:
How to test a CRDT implementation?
a. Unit tests for the operations and merge function.
- For each operation, check that it has the expected effect on the state.
- For the merge function, check that it is commutative, associative, and idempotent.
b. Property-based tests (using QuickCheck or similar):
- Generate random sequences of operations and then check that the final state is the same regardless of the order of operations (for a given set of operations, if we apply them in different orders, we should get the same state).
- For state-based: generate random states and check that merging any two states yields a state that is greater than or equal to both (in the lattice sense) and that merging the same state twice doesn't change it.
c. Integration tests with multiple replicas:
- Simulate a network with delays, reordering, and losses (but with at-least-once or exactly-once delivery as required by the CRDT).
- Check that all replicas converge to the same state after a set of operations.
d. Stress tests: with many replicas and many operations to check for memory leaks, performance, and convergence.
e. Check the size of the state and the bandwidth used.
f. For operation-based CRDTs, test with out-of-order delivery and duplicates.
Additional considerations:
Tombstones: In sets like OR-Set, we use tombstones (removed tags) to handle remove. This can lead to unbounded state growth if we never clean up. Some CRDTs have mechanisms for garbage collection (like in RGA, a sequence CRDT, or in OR-Set with subset tracking). But garbage collection in CRDTs is a hard problem because you need to know when it's safe to remove tombstones (i.e., when all replicas have seen the remove). This usually requires some coordination or a mechanism to track which replicas have seen which operations.
Scalability: Some CRDTs (like G-Counter) scale poorly with the number of replicas because the state is proportional to the number of replicas. Others (like PN-Counter) are twice as bad. For sets, the state is proportional to the number of elements and the number of tags (if using OR-Set).
Complexity: Some CRDTs are more complex to implement and reason about (like OR-Set, RGA, etc.). Make sure you understand the requirements (like the need for unique tags, the need for causal delivery, etc.)
Security: CRDTs are designed for benign failures (network issues, but no malicious actors). If you have malicious actors, you might need to consider authentication and authorization, and even then, a malicious replica could send arbitrary operations that break the invariants.
Recommendations:
Start with simple CRDTs (like G-Counter, G-Set, LWW-Register) if they meet your needs.
If you need remove, consider 2P-Set (if you don't need to re-add) or OR-Set (if you do).
For maps, you can use a map of CRDTs (each key is a separate CRDT) but note that the map itself might not be a CRDT (if you want to add/remove keys, you need a CRDT for the map structure). There are CRDT maps (like LWW-map) that use a last-write-wins strategy for each key, but then removing a key is tricky (you might use a tombstone for the key). Alternatively, use a set of keys and a map from keys to values (each value being a CRDT). Then removing a key is removing from the set and the value CRDT can be garbage collected when no replica has the key.
Be cautious about state growth. Design your CRDT to allow garbage collection if possible.
Test thoroughly, especially with network conditions that cause reordering and duplication.
Consider using existing libraries if possible (like Automerge, Yjs, etc.) unless you have specific needs.
Example: Choosing a set CRDT.
Requirement: We need a set that supports add and remove, and we want to be able to add an element again after removing it.
Options:
- 2P-Set: does not allow re-adding.
- OR-Set: allows re-adding.
So we choose OR-Set.
Implementation (state-based):
- State: for each element, a set of tags (each tag is unique, e.g., [replica_id, counter]).
- Add(e): generate a new tag and add it to the set for e.
- Remove(e): for each tag in the set for e, mark that tag as removed (so we have two sets: one for added tags and one for removed tags? Actually, we can store for each element a set of tags that have been added and a set of tags that have been removed. Then the element is in the set if there exists an added tag that is not in the removed set).
- Merge: for each element, the added set is the union of the two added sets, and the removed set is the union of the two removed sets.
But note: if we have two replicas that add the same element with different tags, then we have two tags. Then if one replica removes the element (by marking its tag as removed) but the other replica doesn't remove, then the element is still present because there is an unremoved tag. This is the desired behavior.
Storage: Each element requires storing two sets of tags (or one set of tags with a flag for each tag? Actually, we can store a set of tags and then a set of removed tags? But then we have to store every tag ever added until we garbage collect. Alternatively, we can store the current set of tags for the element that are not removed? But then when we merge, we have to consider the removed tags from the other replica. So we need to store the removed tags until we are sure that all replicas have seen the remove for that tag. This is the garbage collection problem.
Operation-based OR-Set:
- Each add operation carries a unique tag.
- Each remove operation carries the set of tags that are being removed (or the element and then the set of tags that the replica knows about? Actually, to remove an element, you need to specify which tags you are removing? Or you can remove all known tags? But then if a replica hasn't seen an add, it might not know about the tag. So the typical solution is to have a "remove all" that removes all tags that the replica knows about, and then when merging, you take the union of removed tags. But then if a new add comes after the remove, it will be added with a new tag and then not removed until another remove. This is the same as state-based.
In both cases, we have to store the removed tags until we are sure that all replicas have seen the remove. This is the same as the state-based because the state must include the removed tags.
So in summary, OR-Set requires storing all tags ever added until garbage collection.
Conclusion:
Using CRDTs safely involves:
- Choosing the right type for the data and the use case (considering the trade-offs in state size, network overhead, and complexity).
- Understanding the convergence guarantees and the assumptions (like causal delivery for some operation-based CRDTs).
- Being aware of storage trade-offs and planning for garbage collection if necessary.
- Testing thoroughly, including property-based testing and network condition simulations.
Remember: CRDTs are not a silver bullet. They provide eventual consistency but may have high storage or bandwidth costs. They also do not solve the problem of application-level conflicts (like two users editing the same text at the same time) without additional logic (like a sequence CRDT for text).
For text editing, you might look into operational transformation (OT) or sequence CRDTs (like RGA, LSeq, etc.) which are more complex.
Finally, if you are building a system that requires CRDTs, consider using an existing library that has been battle-tested, unless you have very specific requirements that necessitate a custom implementation.
Excellent question. Here’s a practical, safety-focused guide to using CRDTs (Conflict-Free Replicated Data Types), covering your four key areas.
LWW-Map, OR-Map (map of OR-Sets), CRDT-Map (per-key CRDTs)
Key-value stores where each key has its own CRDT (e.g., collaborative doc per page).
Nested CRDTs increase complexity. Tombstone accumulation in OR-Map if not cleaned.
Sequence/Text
RGA, LSeq, Yjs-style sequence CRDTs
Collaborative editing, ordered lists.
Hardest to implement correctly. Prefer battle-tested libraries (Yjs, Automerge).
JSON/Document
Library solutions (Automerge, Yjs)
Rich collaborative documents.
Don't roll your own; use existing.
Key Safety Tip: Start with the simplest CRDT that satisfies requirements. Complexity grows fast (e.g., G-Set → OR-Set → OR-Map).
2. Convergence Guarantees: What “Safety” Means
Strong guarantee: All replicas that have received the same set of updates converge to identical state, regardless of network order/delays.
Conditions for safety:
State-based (CvRDT):merge() must be commutative, associative, idempotent (join-semilattice). Test:merge(a, b) == merge(b, a); merge(a, merge(b, c)) == merge(merge(a, b), c); merge(a, a) == a.
Op-based (CmRDT): Operations must be commutative and delivered exactly once (or at-least-once with idempotent apply). Often requires causal delivery.
Network assumptions: Op-based CRDTs may break under reordering without commutativity or duplicate ops without idempotence.
Practical implication:
If you use an op-based CRDT without causal delivery (e.g., via message queues), you must design ops to be commutative or include metadata (vector clocks, timestamps) for correct merging.
3. Storage Trade-offs: Memory & Growth
CRDT
Storage Cost
Growth Driver
Mitigations
G-Counter
O(#replicas)
Each replica persists a counter.
Bounded if replica set known/finite.
PN-Counter
O(2×#replicas)
Two G-Counters.
Same as above.
OR-Set
O(#adds × metadata per add)
Unique tags per add (replicaID+counter). Tombstones for removes.
Garbage collection after all replicas ACK remove. Complex.
LWW-Register
O(1) per register
Timestamp per value.
Compact timestamps (hybrid logical clocks).
Sequence CRDTs (RGA)
O(#ops)
IDs per character/operation.
Garbage collection via tombstone pruning (tricky).
Library solutions (Yjs)
Variable
Internal data structures (e.g., Yjs uses "structs" and "index maps").
Libraries have GC strategies (Yjs gc option).
Warning: Metadata-heavy CRDTs (like OR-Set) can explode with frequent add/remove cycles. Always calculate worst-case: (adds per element) × (replicas) × (bytes per tag).
4. Tests: How to Verify Correctness
Unit & Property Tests
Merge Semilattice Tests (state-based):
python
assert merge(a, b) == merge(b, a) # commutative
assert merge(a, merge(b, c)) == merge(merge(a, b), c) # associative
assert merge(a, a) == a # idempotent
Commutativity Tests (op-based): Generate random op sequences, apply in different orders, assert final state equal.
Invariant Tests:
For OR-Set: element present ⇔ ∃unremoved tag.
For PN-Counter: value = positive_count - negative_count.
Boundary Tests: Empty state, max values, concurrent adds/removes.
Convergence Testing
Simulate replicas with random delays, reordering, message loss (but eventual delivery).
Apply same ops in different orders across replicas.
Assert all replicas converge to identical state after sync.
python
# Pseudo-test for convergence
states = [CRDT() for _ in range(N)]
for op in random_ops:
replica = random.choice(states)
replica.apply(op)
# Simulate async sync: periodically merge random pairs
for _ in range(1000):
a, b = random.sample(states, 2)
a.merge(b.state)
b.merge(a.state)
# All states should be equal
assert all(s == states[0] for s in states)
State Size & Tombstone Tests
Track state size after repeated add/remove cycles.
Ensure garbage collection (if implemented) actually removes tombstones after all replicas ack.
Network Condition Tests
Op-based: Test with out-of-order delivery, duplicates, missing ops (retries).
Use a message queue with configurable ordering/delivery guarantees.
Integration with Real Systems
Test with actual network partitions and healings.
Monitor divergence duration (time until convergence after partition).
Safety Checklist Before Deployment
Chosen CRDT type matches semantics exactly (e.g., OR-Set not 2P-Set if re-add needed).
Python:pysyncobj (Raft, has CRDT examples), crdt (simple implementations).
Final Advice
Prefer op-based if you have reliable message delivery and want bandwidth efficiency.
Prefer state-based if merge is infrequent or state is small/simple.
Never implement sequence CRDTs from scratch for production—use Yjs/Automerge.
Document your CRDT’s “contract”: what guarantees it provides, what network assumptions it makes, and how to GC.
Test under realistic network conditions (chaos engineering).
By following these guidelines, you’ll avoid common pitfalls like unbounded state growth, incorrect convergence, and surprising semantics under concurrency.