CRDTs: Conflict-Free Replicated Data Types

Learn how conflict-free replicated data types converge after concurrent updates, and where counters, LWW registers, and observed-remove sets fit.

published: reading time: 25 min read author: Geek Workbench updated: November 8, 2026
Quick Summary

CRDTs define merge rules that let replicas converge after receiving the same updates, even when those updates arrive in different orders. Counters, registers, and sets each have different semantics and metadata costs. Convergence does not make reads linearizable or protect business rules, and a last-write-wins register can discard a concurrent value.

Introduction

When replicas accept updates independently, they need a rule for reconciling concurrent changes. A CRDT builds that rule into the data type. Under the data type’s assumptions, replicas that receive the same updates can converge without coordinating each individual write.

graph TD
    subgraph Without CRDT
        N1[Node A] --> W1[Write: x=1]
        N2[Node B] --> W2[Write: x=2]
        M1[Merge] -->|conflict| X[Application chooses a policy]
    end

    subgraph With CRDT
        N3[Node A] --> W3[Write: x=1]
        N4[Node B] --> W4[Write: x=2]
        M2[Merge] --> R[Result depends on data type rules]
    end

Core Concepts

A CRDT is a replicated data type with merge rules designed to make replicas converge after they have received the same updates. For a state-based CRDT, merge is typically a join operation that is associative, commutative, and idempotent. For an operation-based CRDT, concurrent operations must commute, and delivery must meet that CRDT’s assumptions. These are convergence properties; they do not make each read linearizable or preserve every application invariant.

Mathematically, CRDTs come in two flavors:

  • CmRDT (Commutative Replicated Data Types): Operations commute
  • CvRDT (Convergent Replicated Data Types): States converge when merged

The original CRDT paper describes these two approaches and their conditions. Implementations choose one based on how they exchange state or operations; neither makes all concurrent values survive every merge rule. Shapiro et al., Conflict-Free Replicated Data Types.

A small G-Counter merge

Suppose replicas A and B keep one component per replica. A increments twice while disconnected; B increments once:

A before merge: {A: 2, B: 0}  -> value 2
B before merge: {A: 0, B: 1}  -> value 1
Merge by component-wise max: {A: 2, B: 1} -> value 3

If both replicas later merge the same states again, the result stays {A: 2, B: 1}. This merge preserves those independent increments because the component-wise maximum is the G-Counter’s rule; an LWW register has different behavior.

G-Counter: Grow-Only Counter

The simplest CRDT. It only increments. No decrements. This works for things like page view counts where you never need to subtract.

class GCounter:
    """
    Grow-only counter. Each node maintains its own count.
    Merging takes the maximum for each node.
    """
    def __init__(self):
        self.counts = {}  # node_id -> count

    def increment(self, node_id):
        self.counts[node_id] = self.counts.get(node_id, 0) + 1

    def merge(self, other: 'GCounter'):
        for node_id, count in other.counts.items():
            self.counts[node_id] = max(
                self.counts.get(node_id, 0),
                count
            )

    def value(self) -> int:
        return sum(self.counts.values())
graph TD
    N1[Node A: 5] --> M[Merge]
    N2[Node B: 3] --> M
    M --> R[Total: 8]

PN-Counter: Positive-Negative Counter

A PN-Counter extends G-Counter to support both increments and decrements. It maintains two G-Counters: one for increments, one for decrements.

class PNCounter:
    """
    Positive-Negative counter. Supports both increments and decrements.
    Uses two G-Counters internally.
    """
    def __init__(self):
        self.positive = GCounter()  # increments
        self.negative = GCounter()  # decrements

    def increment(self, node_id, amount=1):
        for _ in range(amount):
            self.positive.increment(node_id)

    def decrement(self, node_id, amount=1):
        for _ in range(amount):
            self.negative.increment(node_id)

    def merge(self, other: 'PNCounter'):
        self.positive.merge(other.positive)
        self.negative.merge(other.negative)

    def value(self) -> int:
        return self.positive.value() - self.negative.value()

A use case: a shopping cart where you add and remove items. The PN-Counter tracks the cart size even when concurrent updates happen.

LWW-Register: Last-Write-Wins Register

A register holds a single value. When merging, the write with the latest timestamp wins.

This is a deliberate conflict policy, not a way to preserve every update. If two users change the same field concurrently, one value is discarded according to the ordering tuple. A wall-clock timestamp records a clock reading, not which change a user intended to win. Clock skew and equal timestamps therefore need an explicit tie-break policy, and even a deterministic tie-break may produce an undesirable business result.

import time
from dataclasses import dataclass

@dataclass
class LWWRegister:
    value: any
    timestamp: float
    node_id: str

class LWWMap:
    """
    Last-Write-Wins map. Each key has a (value, timestamp, node_id) tuple.
    On merge, the entry with highest timestamp wins.
    Ties broken by node_id.
    """
    def __init__(self):
        self.entries = {}  # key -> LWWRegister

    def set(self, key, value, timestamp=None, node_id=None):
        self.entries[key] = LWWRegister(
            value=value,
            timestamp=timestamp or time.time(),
            node_id=node_id
        )

    def get(self, key):
        return self.entries.get(key)

    def merge(self, other: 'LWWMap'):
        for key, reg in other.entries.items():
            if key not in self.entries:
                self.entries[key] = reg
            else:
                # Compare timestamps, then node_id for ties
                ours = self.entries[key]
                if (reg.timestamp > ours.timestamp or
                    (reg.timestamp == ours.timestamp and reg.node_id > ours.node_id)):
                    self.entries[key] = reg
sequenceDiagram
    participant N1 as Node A
    participant N2 as Node B
    participant M as Merge

    N1->>N1: set(x=1, ts=100)
    N2->>N2: set(x=2, ts=101)
    N1->>M: state: x=(1, 100, A)
    N2->>M: state: x=(2, 101, B)
    M->>M: ts=101 > ts=100, keep B
    Note over M: Result: x=2

OR-Set: Observed-Remove Set

An OR-Set lets you add and remove elements. Concurrent adds and removes are handled correctly.

class ORObject:
    """
    Observed-Remove Set entry.
    Each (tag, value) pair can be added and removed.
    """
    def __init__(self, value, tag):
        self.value = value
        self.tag = tag

class ORSet:
    """
    Observed-Remove Set. Elements have unique tags.
    - add(tag, value): Adds element with unique tag
    - remove(tag): Marks element as removed
    - merge(): Union of adds, subtracts removes
    """
    def __init__(self):
        self.adds = {}  # tag -> ORObject
        self.removes = set()  # tags that were removed

    def add(self, value, tag=None):
        tag = tag or str(uuid.uuid4())
        self.adds[tag] = ORObject(value, tag)
        return tag

    def remove(self, tag):
        self.removes.add(tag)

    def contains(self, tag):
        return tag in self.adds and tag not in self.removes

    def merge(self, other: 'ORSet'):
        # Union of adds
        for tag, obj in other.adds.items():
            if tag not in self.removes:
                self.adds[tag] = obj

        # Union of removes
        self.removes.update(other.removes)

    def elements(self):
        return [obj.value for tag, obj in self.adds.items()
                if tag not in self.removes]

OR-Sets are good for collaborative lists, shopping carts, and anywhere items are added and removed concurrently.

Tombstone accumulation is a practical issue with basic OR-Set implementations. When you remove an element, the tag lands in the removes set but never gets cleaned up. Run enough add/remove cycles and the removes set grows without bound. Picture this: add and remove a user 100 times across 5 nodes, and you now have 500 tombstone entries even though the set looks empty to anyone reading it. This is especially painful in memory-constrained environments. RGA and other advanced variants address this differently, using garbage collection or mergeable delete flags instead of permanent tombstones.

RGA: Replicated Growable Array

The RGA is a CRDT for ordered sequences. It handles concurrent inserts at the same position correctly.

class RGANode:
    def __init__(self, value, timestamp, id=None):
        self.value = value
        self.timestamp = timestamp
        self.id = id or str(uuid.uuid4())

class RGA:
    """
    Replicated Growable Array. Uses timestamps and IDs
    for ordering. Concurrent inserts at the same position
    are ordered by ID to ensure determinism.
    """
    def __init__(self):
        self.nodes = []  # Ordered list of RGANodes

    def insert_after(self, after_id, value):
        node = RGANode(value, time.time())
        # Insert at position after after_id
        pos = self._find_position(after_id)
        self.nodes.insert(pos + 1, node)

    def _find_position(self, after_id):
        for i, n in enumerate(self.nodes):
            if n.id == after_id:
                return i
        return -1  # Insert at beginning if not found

    def merge(self, other: 'RGA'):
        # Merge by timestamp+ID ordering
        all_nodes = {n.id: n for n in self.nodes}
        all_nodes.update({n.id: n for n in other.nodes})

        # Re-sort by timestamp, then by ID
        self.nodes = sorted(
            all_nodes.values(),
            key=lambda n: (n.timestamp, n.id)
        )

2P-Set: Add-Only-Then-Remove-Once

A Two-Phase Set (2P-Set) is stricter than an OR-Set: you can add freely, but once something is removed it cannot be re-added. Think feature flags, configuration keys, or any domain where deprecation is permanent.

The two phases are straightforward. During the add phase, elements land in AddSet. During the remove phase, they move to RemoveSet (a tombstone). Merge unions both sets. An element is present only when it is in AddSet and not in RemoveSet.

class TwoPhaseSet:
    """2P-Set: adds go to AddSet, removes go to RemoveSet. Once removed, never returns."""
    def __init__(self):
        self.add_set = set()      # Elements that have been added
        self.remove_set = set()  # Elements that have been removed (tombstones)

    def add(self, value):
        if value not in self.remove_set:
            self.add_set.add(value)

    def remove(self, value):
        self.remove_set.add(value)

    def contains(self, value):
        return value in self.add_set and value not in self.remove_set

    def merge(self, other: 'TwoPhaseSet'):
        self.add_set = self.add_set.union(other.add_set)
        self.remove_set = self.remove_set.union(other.remove_set)

Good fit: versioned config where you deprecate keys and never re-enable them. Roll out a feature flag, then kill it permanently. A 2P-Set handles this correctly even if someone tries to add the flag again concurrently.

Cart merge semantics are application-specific

A cart is not one standard CRDT. The right data type depends on what each operation means:

  • If a device sets a quantity to a value, a last-write-wins register can select one assignment, but it can discard the concurrent assignment.
  • If each action means “add one,” a counter can preserve independent increments, subject to its own replica and delivery assumptions.
  • A remove operation needs a defined relationship to concurrent adds; an observed-remove set or another explicit add/remove policy may fit.

Inventory, checkout limits, and payment authorization still need validation by an authoritative service. A merge rule can converge replicas without guaranteeing that a cart remains purchasable or within a business limit.

JSON-like CRDTs

Libraries that synchronize maps, arrays, or nested documents define their own operation, conflict, and encoding rules. Check the chosen library’s current documentation for concurrent scalar edits, sequence inserts and deletes, synchronization, compaction, and interoperability. A G-Counter or LWW-register example is not enough to infer how a complete document library behaves.

Where CRDTs Can Fit

Collaborative Editing

Collaborative editors may use CRDTs for concurrent edits to shared text or structured documents. A document needs rules for inserts, deletes, and references between fields; a counter CRDT does not solve those problems. Presence indicators and application constraints are separate concerns.

Distributed Databases

Some replicated databases expose data types with CRDT semantics. The exact types, consistency options, and replication guarantees are product-specific; consult the database’s documentation before assuming that a feature is a general CRDT or that it provides a particular availability or consistency guarantee.

Messaging Systems

An offline messaging client may need to reconcile locally queued messages with server state after reconnecting. Message ordering, delivery, and duplicate handling are product-level policies; a CRDT alone does not guarantee that messages arrive once or appear in a user-intended order.

Shopping Carts

An offline-first cart is one possible application, but quantity and removal semantics need care. If two devices independently set a quantity to 3 and 5, a max-based merge yields 5; it does not mean “add both changes.” If each action should count, use an operation model that captures increments. Checkout limits, inventory availability, and payment rules still need authoritative validation because convergence does not enforce them.

Implementing CRDTs in Practice

Most languages have CRDT libraries. For Python:

# Using the crdt library
from crdt import GCounter, PN_Counter, LWW_Register, OR_Map

# Create counters on different nodes
node_a_counter = PN_Counter()
node_b_counter = PN_Counter()

# Each node increments independently
node_a_counter.increment('node_a')
node_b_counter.increment('node_b')

# Merge when nodes communicate
node_a_counter.merge(node_b_counter)

# Result is the sum of all increments
print(node_a_counter.value)

Failure Scenarios to Test

Data Integrity Issues

The following are illustrative scenarios to test, not reports of specific production incidents. A CRDT’s merge properties do not remove implementation bugs or application-level constraints.

Tombstone growth

An OR-Set that retains removal metadata may grow as items are added and removed. Measure metadata growth with the expected workload and confirm that the chosen implementation supports safe compaction. Do not discard tombstones until the replication protocol guarantees that older replicas cannot reintroduce removed items.

Clock skew with an LWW register

Illustrative scenario: two replicas update the same field while one replica’s clock is ahead. The timestamp rule may select the value from the skewed clock, even if that value is not the one the user meant to keep. Test clock skew and equal timestamps, and choose a domain-level conflict policy when “latest timestamp wins” is not acceptable.

Invalid positions in an ordered sequence

Illustrative scenario: an RGA implementation accepts an insertion that refers to a missing predecessor. Define how invalid or delayed references are handled, then test that replicas converge when insertions and deletions arrive in different orders.

Semantic and Application-Level Violations

A CRDT merge can produce a mathematically correct result that still violates application-level invariants the CRDT data model knows nothing about. A PN-Counter tracking increments and decrements across replicas does not know that a banking application requires non-negative balances. A JSON CRDT document merging cleanly does not know that an e-commerce cart has a maximum item limit. These violations show up at the boundary between the CRDT layer and the business logic layer, and they demonstrate that CRDT correctness does not automatically translate to application correctness.

Counter merge versus a business limit

Illustrative scenario: a PN-Counter tracks reservations, but independent replicas each accept decrements based on a stale positive balance. The merged counter can cross a domain limit. If the invariant must never be violated, use a coordination or allocation scheme that enforces it; a counter merge alone cannot reserve scarce capacity.

Large document history

Illustrative scenario: a long-lived collaborative document accumulates history or metadata that increases storage and sync cost. Check the selected library’s compaction and snapshot behavior, and test restore and synchronization before adopting a retention policy.

Concurrent cart edits

Illustrative scenario: two devices change a cart item’s quantity while offline, and one removes it. Define whether the application should sum increments, keep one assigned quantity, or let removal win. Encode that choice in the operation model and test the merge; do not assume one generic cart CRDT supplies the desired business semantics.

Common Pitfalls / Anti-Patterns

CRDTs are powerful but not a silver bullet.

Memory overhead: CRDTs maintain metadata (timestamps, tags, per-node state). A G-Counter with 1000 nodes needs 1000 counters even if most are zero.

Not all data types have CRDT forms: You cannot build a CRDT for a set with strong consistency guarantees on contains(). Some data just does not have a conflict-free representation.

Semantic limitations: LWW-Register loses data by design. If two concurrent writes happen, one value disappears. CRDTs do not solve the problem of data loss; they just make the loss predictable.

# CRDT does not preserve both values
node_a.set('x', 'hello')
node_b.set('x', 'world')
# After merge: only one survives
# Which one depends on timestamps, not intent

Timestamps are unreliable: Clocks skew across machines. Hybrid Logical Clocks (HLC) help, but timestamps are never perfect.

CRDTs vs Operational Transformation

Both solve collaborative editing, but differently.

Aspect CRDT Operational Transformation
Coordination Some designs accept concurrent updates without per-write coordination Depends on the OT protocol and deployment
Complexity Merge rules and metadata vary by data type Transformation rules and ordering model vary
Server dependency Some designs sync peer-to-peer or through relays Many deployments use a central sequencer
Memory Grows with history Can be compact

Neither approach is universally simpler. The choice depends on the operation model, delivery assumptions, metadata costs, and whether a coordinating service fits the product’s consistency needs.

CRDT Type Comparison

CRDT Type Operations Merge Strategy Memory Overhead Use Cases
G-Counter Increment only Max per node O(N) counters Page views, vote counts
PN-Counter Increment, Decrement Max for pos/neg O(2N) counters Replicated counts; not invariant enforcement
LWW-Register Set Latest timestamp wins O(1) User preferences, last-write-wins
OR-Set Add, Remove Union of adds, subtracts removes O(A+R) entries Shopping carts, collaborative lists
RGA Insert, Delete Timestamp+ID ordering O(N) nodes Text editing, ordered sequences

Libraries and implementations

Yjs, Automerge, pycrdt, and riak_dt are examples of CRDT-related projects. Their APIs, supported types, merge semantics, and wire formats differ. Check each project’s own documentation and test the behavior your application needs before choosing one.

Quick Recap Checklist

  • A CRDT can provide convergence for concurrent updates when its assumptions hold
  • G-Counter: increment-only counting
  • PN-Counter: bidirectional counting
  • LWW-Register: timestamp-based value selection
  • OR-Set: add/remove collections
  • Metadata, delivery assumptions, and coordination needs vary by CRDT type
  • Not all data types have CRDT representations
  • Consider them for replicated data when the merge semantics match the product rules

For more on eventual consistency, see Consistency Models. For conflict resolution patterns, see Consistency Models. For distributed data patterns, see Database Replication.

CRDTs are a powerful tool for building eventually consistent systems without coordination overhead. They are not right for every problem, but when you need multiple nodes to accept writes independently and merge cleanly, CRDTs provide mathematical guarantees that hand-rolled merge logic cannot match.

Interview Questions

1. What is a CRDT and what problem does it solve in distributed systems?

Expected answer points:

  • CRDT stands for Conflict-Free Replicated Data Type
  • Can provide convergence after replicas receive the same updates, under the CRDT’s assumptions
  • Solves the conflict problem when multiple nodes accept writes concurrently and then synchronize
  • Mathematically designed to merge concurrent updates without conflicts
  • No central node required to sequence writes or resolve conflicts
2. Explain the difference between CmRDT and CvRDT.

Expected answer points:

  • CmRDT (Commutative Replicated Data Types): Operations themselves commute, meaning the order of operations does not matter
  • CvRDT (Convergent Replicated Data Types): States converge when merged, regardless of merge order
  • CvRDTs are more commonly used in practice because they are easier to reason about
  • CvRDTs work by having state that merges cleanly; CmRDTs require operation logs to replay
3. How does a G-Counter work and what are its limitations?

Expected answer points:

  • G-Counter is a grow-only counter that only increments, never decrements
  • Each node maintains its own count mapped by node_id
  • Merging takes the maximum value for each node across all replicas
  • The final value is the sum of all per-node counters
  • Limitation: Cannot decrement, only works for monotonic counters like page views
  • Memory overhead is O(N) where N is the number of nodes
4. What is a PN-Counter and how does it achieve bidirectional counting?

Expected answer points:

  • PN-Counter extends G-Counter to support both increments and decrements
  • Internally maintains two G-Counters: one for positive (increments) and one for negative (decrements)
  • Merge operation merges both counters separately using max strategy
  • Final value is positive counter minus negative counter
  • Use cases: shopping cart quantities, bank balances, any counter that needs to go up and down
5. How does Last-Write-Wins (LWW) Register handle concurrent updates?

Expected answer points:

  • LWW-Register holds a single value with an associated timestamp and node_id
  • When merging, the write with the latest timestamp wins
  • Ties are broken by node_id (higher ID wins)
  • Simple to implement but loses data by design when concurrent writes occur
  • Does not preserve both values in conflict - one value disappears permanently
6. Explain the OR-Set (Observed-Remove Set) and how it handles concurrent adds and removes.

Expected answer points:

  • OR-Set allows adding and removing elements with unique tags
  • Each (tag, value) pair can be added and removed independently
  • Maintains two sets: adds (tag -> object mapping) and removes (set of removed tags)
  • Merge is union of adds minus any tags in removes
  • Concurrent adds of same value with different tags are all preserved
  • Concurrent add and remove of same tag results in removal winning
7. What is tombstone accumulation in OR-Set and why is it a problem?

Expected answer points:

  • Tombstones are tags stored in the removes set when elements are deleted
  • These tombstone entries never get cleaned up in basic OR-Set implementations
  • After many add/remove cycles, the removes set grows without bound
  • Example: add/remove a user 100 times across 5 nodes = 500 tombstone entries
  • Especially painful in memory-constrained environments
  • Advanced variants like RGA use garbage collection or mergeable delete flags instead
8. How does RGA (Replicated Growable Array) handle concurrent inserts at the same position?

Expected answer points:

  • RGA is a CRDT for ordered sequences like text or lists
  • Each element has a timestamp and unique ID
  • Insert operations specify a position using the ID of the preceding element
  • Concurrent inserts at the same position are ordered by ID to ensure determinism
  • Merge combines all nodes from both replicas and re-sorts by timestamp then ID
  • Solves the concurrent edit problem in collaborative text editing
9. What are the trade-offs between CRDTs and Operational Transformation (OT)?

Expected answer points:

  • Coordination and server requirements depend on the CRDT or OT protocol and deployment
  • Both approaches have implementation complexity; their metadata and transformation costs differ
  • Choose based on the editing operations, consistency needs, and implementation you can validate
10. What are the fundamental limitations of CRDTs?

Expected answer points:

  • Memory overhead: CRDTs maintain metadata (timestamps, tags, per-node state) - a G-Counter with 1000 nodes needs 1000 counters
  • Not all data types have CRDT forms: cannot build a CRDT for a set with strong consistency contains() guarantees
  • LWW-Register loses data by design: concurrent writes mean one value disappears
  • Timestamps are unreliable: clocks skew across machines; Hybrid Logical Clocks help but are not perfect
  • CRDTs do not solve data loss - they make it predictable but still present
11. What is the 2P-Set (Two-Phase Set) and when would you use it?

Expected answer points:

  • 2P-Set is stricter than OR-Set: you can add freely, but once removed, an element cannot be re-added
  • Two phases: add phase (elements go to AddSet) and remove phase (elements go to RemoveSet/tombstones)
  • Element is present only when in AddSet and not in RemoveSet
  • Good fit: versioned configuration where deprecation is permanent
  • Use cases: feature flags, configuration keys, any domain where items are deprecated forever
12. How do Hybrid Logical Clocks (HLC) improve timestamp reliability in CRDTs?

Expected answer points:

  • Physical clocks (NTP-synced) can skew or jump, making timestamps unreliable
  • HLC combines physical time with logical counters to create causally consistent timestamps
  • HLC guarantees that if event A causally precedes event B, then HLC(A) < HLC(B)
  • Even when physical clocks diverge, the logical component maintains ordering
  • Useful for LWW-Register and other timestamp-based CRDTs to ensure deterministic merges
  • Does not eliminate clock issues entirely but provides bounded guarantee
13. What should you check before relying on a JSON CRDT library?

Expected answer points:

  • Check how the library resolves concurrent scalar writes, inserts, and deletes
  • Confirm its sync protocol, encoding, and interoperability limits
  • Review history compaction, snapshots, and document lifecycle support
  • Test the exact nested edits and conflicts your application permits
  • Keep business invariants outside assumptions about automatic merge
14. Why is a shopping cart not one standard CRDT?

Expected answer points:

  • The merge rule depends on whether an action sets a quantity, increments it, or removes an item
  • A max-based assignment does not sum independent increments
  • Concurrent add/remove behavior must be defined and tested
  • Inventory, checkout limits, and payment rules need authoritative validation
15. Give a suitable generic use case for a CRDT.

Expected answer points:

  • A replicated counter can accept independent increments and merge per-replica components
  • A collaborative document may use sequence or map CRDTs for concurrent edits
  • State the operation semantics, delivery assumptions, and business invariants before choosing a type
16. What is vector clock vs CRDT and when would you use each?

Expected answer points:

  • Vector clocks track causality by maintaining a vector of counters (one per node)
  • Vector clocks detect conflicts but do not resolve them - they just identify concurrent events
  • CRDTs are data structures with built-in merge semantics that resolve conflicts automatically
  • Use vector clocks when you need to detect causality and make application-specific merge decisions
  • Use CRDTs when you want automatic conflict-free merging without application logic
  • Some systems combine both: vector clocks for causality tracking, CRDTs for data
17. Explain delta-based CRDTs and their advantage over state-based CRDTs.

Expected answer points:

  • State-based CRDTs send the entire state on merge, which grows with all history
  • Delta-based CRDTs only send the delta (change) since last synchronization
  • Delta mutation (m) produces delta state d such that state + d = new state
  • Reduces network bandwidth significantly for large CRDTs with long histories
  • Requires maintaining delta logs to compute deltas from full state
  • Commonly used in mobile/offline-first applications where bandwidth is constrained
18. What is the relationship between eventual consistency and CRDTs?

Expected answer points:

  • Eventual consistency guarantees that if no new updates are made, all replicas will eventually converge
  • CRDTs provide strong eventual consistency (SEC): convergence plus the guarantee that any two valid merges produce the same state
  • Some CRDT designs provide strong eventual consistency: replicas that have delivered the same updates converge to the same state
  • That property does not make reads linearizable or make every conflict preserve both values
  • Whether updates can be accepted without coordination depends on the CRDT and its deployment assumptions
19. How do CRDTs handle network partitions and what are the trade-offs?

Expected answer points:

  • Some CRDT designs can accept updates independently during a partition, subject to their assumptions
  • After replicas receive the same updates, their merge rules can make them converge
  • An LWW register may discard a concurrent value, while other types have different conflict semantics
  • Trade-off: divergent histories accumulate during partition, creating more merge work
  • Memory grows faster during partitions because more concurrent operations accumulate
  • CRDTs do not remove the system's consistency, availability, and partition trade-offs
  • Reads may reflect only the updates a particular replica has received
20. What are garbage collection strategies for CRDT tombstones?

Expected answer points:

  • Tombstones (removal markers) accumulate indefinitely in basic OR-Set and 2P-Set
  • Hybrids approach: periodically compact tombstones using a generation/epoch number
  • G-Counting: maintain per-element add and remove counts, GC when adds = removes for an element
  • Message-stability based: GC tombstones once all known replicas have acknowledged the operation
  • Sliding-window: only keep tombstones within a bounded window of recent operations
  • Absence-based GC: if an element is present in all replicas and no pending operations exist, remove tombstones

Further Reading

Academic Papers

CRDTs have a formal research literature. The paper below describes convergent and commutative replicated data types and their properties.

  • Shapiro et al. (2011) - “A Comprehensive Study of Convergent and Commutative Replicated Data Types” - The foundational paper defining CvRDTs and CmRDTs
  • Bieniusa et al. (2012) - “Brief Announcement: The Case for Fast Update Propagation in CRDTs” - Analyzes merge performance characteristics
  • Bailis et al. (2014) - “Coordination Avoidance in Database Systems” - Relates CRDT concepts to database consistency

Books

Two books show up repeatedly in CRDT discussions. Both cover distributed systems broadly but dedicate good sections to conflict-free data types.

  • “Understanding Distributed Systems” by Roberto Vitillo - Chapter on consistency models covers CRDTs
  • “Designing Data-Intensive Applications” by Martin Kleppmann - Chapter on distributed data includes CRDT comparison

Libraries and Implementations

Specification

There is no universal wire format implied by the CRDT model. Interoperability depends on the specific data types, encoding, and synchronization protocol a library supports; check those projects’ current documentation before planning cross-library exchange.

CRDTs don’t exist in isolation. Hybrid Logical Clocks, Vector Clocks, Operational Transformation, and Event Sourcing all come up when you dig into how CRDTs work and where they fit.

  • Hybrid Logical Clocks (HLC) - for more reliable timestamp ordering
  • Vector Clocks - for causality tracking without automatic merge
  • Operational Transformation (OT) - alternative approach used by Google Docs
  • Event Sourcing - patterns for CRDT state management

Conclusion

CRDTs provide merge rules for replicated data that can converge after replicas receive the same updates. Some designs let replicas accept writes without coordinating each operation, which can help offline-first or collaborative applications. That choice does not guarantee linearizable reads, preserve every concurrent value, or enforce application invariants during a partition.

Choose a data type whose operations match the product semantics: a G-Counter for increment-only counts, a PN-Counter for increments and decrements, an LWW register when selecting one value is acceptable, and a set or sequence CRDT when its add/remove or ordering rules fit. For nested documents, inspect the exact behavior of the library you plan to use.

Before adopting a CRDT, write down the operations, conflict policy, delivery assumptions, metadata lifecycle, and business invariants. Then test duplicate, delayed, reordered, and concurrent updates against the implementation you plan to use.

Category

Related Posts

Asynchronous Replication: Lag, Failover, and Freshness

Learn how asynchronous database replication affects read freshness, failover data loss, lag monitoring, and recovery choices during network partitions.

#distributed-systems #replication #eventual-consistency

Multi-Paxos

Multi-Paxos extends basic Paxos to achieve consensus on sequences of values, enabling practical replicated state machines for distributed systems and databases.

#distributed-systems #consensus #paxos

Paxos Consensus Algorithm

Paxos is a family of consensus algorithms for achieving agreement in distributed systems despite failures, pioneered by Leslie Lamport.

#distributed-systems #consensus #paxos