Course contentsShow
← Databases & SQL
Lesson 816 of 1,9537. Transaction ManagementFree lesson

Conflict-Free Replicated Data Types

Explore non-locking data structures that enable eventual consistency without traditional transactions.

In this lesson, you will learn how Conflict-Free Replicated Data Types (CRDTs) allow distributed systems to achieve consistency without the need for complex, performance-draining locks.

Moving Beyond Locking

Up until now, we have studied traditional ways to manage distributed state, such as Two-Phase Commit or Saga Patterns. These approaches rely heavily on coordination and locking to prevent conflicts. However, when a system is spread across the globe, waiting for a central coordinator to lock a record creates significant latency.

CRDTs change the game by making data structures "conflict-proof" by design. Instead of preventing concurrent writes, they use mathematical rules to ensure that all replicas eventually converge to the same state, regardless of the order in which updates arrive.

How It Works: The G-Counter

A simple example of a CRDT is the Grow-only Counter (G-Counter). Imagine a database distributed across three nodes. Instead of one global variable that everyone locks before incrementing, each node maintains its own local count.

If Node A increments its local counter, it doesn't need to ask Node B or C for permission. When it’s time to synchronize, the nodes simply share their local counters. Because the operation is strictly "addition," the state of the database is defined as the MAX value seen for each node's contribution:

-- Conceptual representation of merging two G-Counter states
-- Node A: {Node1: 10, Node2: 5, Node3: 2}
-- Node B: {Node1: 10, Node2: 7, Node3: 2}
-- Result: {Node1: 10, Node2: MAX(5, 7), Node3: 2} -> {Node1: 10, Node2: 7, Node3: 2}

By ensuring the operation is commutative (order doesn't matter) and idempotent (doing it twice doesn't change the outcome more than doing it once), the system reaches global consensus automatically.

There is no "locking" involved. No node is ever blocked waiting for a transaction coordinator. You trade the strict serializability of a traditional ACID transaction for eventual consistency, allowing your database to remain highly available and performant even during network partitions.

Key Takeaway: CRDTs enable high-availability systems to achieve convergence without locks by using data structures that are mathematically designed to resolve concurrent updates predictably.