SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

CRDTs

Data types that can be changed on many machines and always merge to the same result.

โฑ 14 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A CRDT (Conflict-free Replicated Data Type) is a data type built so that many machines can change their own copy at the same time, without locking or asking anyone, and the copies always merge to the same result.

  • Each copy accepts writes locally and instantly, even when it is offline or cut off from the others.
  • When copies meet, a merge rule combines them. The rule gives the same answer in any order and any number of times.
  • This gives strong eventual consistency: copies that have seen the same updates are always identical.

02Concept: What is it?

Say three replicas of a "likes" counter each receive some clicks while the network between them is broken. Later they reconnect. A plain number cannot tell which copy is right: if each copy says 5, 7 and 6, taking the newest or the biggest gives a wrong total, and some likes are lost.

A CRDT solves this by choosing a shape of data and a merge function that cannot conflict. The merge must be:

  • Commutative: merging A with B gives the same result as B with A (order does not matter).
  • Associative: merging in groups gives the same result (grouping does not matter).
  • Idempotent: merging the same thing twice changes nothing (duplicates are harmless).

With these three rules, it does not matter if messages arrive late, out of order, or twice. Every replica ends in the same state once it has seen all updates.

Replicas change alone, then merge
๐Ÿ“ฑReplica A+2 locally
โ†”merge any time
๐Ÿ’ปReplica B+3 locally
โ†”merge any time
๐Ÿ–ฅ๏ธReplica C+1 locally
โœ…All three show 6same state, no conflict
No locks, no leader. The merge rule makes the copies agree.
๐Ÿง Conflicts are designed away
A normal database detects a conflict and then must pick a winner. A CRDT is shaped so there is nothing to fight about: every change can be combined.

03Real-Life Example

๐ŸตThree Friends Counting Votes by Hand
Three friends each keep their own tally sheet of votes. Each friend only ever writes on their own line: "Ann: 4, Ben: 0, Cy: 0". When two friends meet they compare sheets and, for each line, keep the bigger number. Because counts only go up, the bigger number is always the newer one. Meet in any order, meet twice, meet through a friend: in the end, every sheet reads the same and the total is correct. Nobody asked permission to write, and nobody overwrote anyone else.
Tally sheets
G-Counter CRDT
Each friend's own line
A slot per replica that only that replica increases
Writing only on your own line
Local update with no conflict possible
Keeping the bigger number per line
The merge function (max per slot)
Total = sum of all lines
The counter's value
Meeting in any order, twice
Commutative and idempotent merges
A friend who was away for a week
A replica that was offline and merges on return
Merging two copies, slot by slot
๐Ÿ“„Copy 1[A:3, B:1, C:0]
โ†’โ†“merge (max)
๐Ÿ“„Copy 2[A:2, B:4, C:1]
โ†’โ†“=
๐Ÿ“„Result[A:3, B:4, C:1] = 8

04Why Do We Need It?

โšกFast local writes
Update your own copy right away. No waiting for a lock, a leader or a round trip.
โœˆ๏ธWorks offline
Phones and laptops can keep editing without a network, then merge when they reconnect.
๐ŸงฑPartition friendly
Both sides of a network split can keep accepting writes (an AP choice in CAP), and merge later.
๐ŸŽฏNo lost updates
A good merge keeps every change, unlike last-write-wins which silently throws some away.
๐ŸŒMulti-region writes
Users in different regions write to a nearby copy, with low latency everywhere.
๐Ÿ”ŒNo central coordinator
No leader or lock service means no single point of failure.
If writes can happen in many places at once and you cannot wait for agreement, pick data whose merge never conflicts.

05Where Do We Use It?

๐Ÿ“Collaborative editing
Shared documents and notes where many people type together, offline or online.
๐Ÿ‘Counters
Likes, views and inventory-like tallies spread over many data centres.
๐Ÿ›’Sets and carts
Shopping carts and tag lists where items are added and removed on different devices.
๐Ÿ—„๏ธDatabases
Riak, Redis Enterprise (Active-Active) and Azure Cosmos DB offer CRDT-style data types or conflict-free merging.
๐Ÿ’ฌChat and presence
Online status, read markers and message sets that must converge on all devices.
๐Ÿ“ฑLocal-first apps
Apps that store data on your device first and sync to others later.

06Types / Parts / How It Works

Two ways to build a CRDT

State-based and operation-based
State-based (CvRDT)
๐Ÿ“ฆSend the whole state
โ†’โ†“merge()
๐Ÿ–ฅ๏ธReceiver merges
Operation-based (CmRDT)
โœ‰๏ธSend each operation
โ†’โ†“apply()
๐Ÿ–ฅ๏ธReceiver applies
Same goal, different thing sent over the network.
StyleWhat travelsNeeds from the networkCost
State-basedThe full state (or a delta of it)Almost nothing: messages can be lost, repeated or reorderedLarger messages
Operation-basedSmall operations like โ€œ+1โ€ or โ€œadd xโ€Each operation delivered at least once, with causal order (no duplicates, or made idempotent)Small messages, stronger delivery needs

Common CRDT types

TypeWhat it holdsHow conflicts are handled
G-CounterA count that only goes upOne slot per replica, merge takes the max of each slot
PN-CounterA count that can go up and downTwo G-Counters: one for adds, one for subtracts
G-SetA set you can only add toMerge is a union
OR-Set (observed-remove)A set with add and removeEach add gets a unique tag, and remove only deletes the tags it has seen. A concurrent re-add wins.
LWW-RegisterA single valueHighest timestamp wins. Simple, but the loser's write is lost.
Sequence / text CRDTAn ordered list or documentEvery character gets a unique, ordered ID (used by Yjs and Automerge)
VisualizerPlain counter vs G-Counter: who loses likes?Click +1 on two different copies before syncing, then sync in any order. Compare the plain number (newest write wins) with the G-Counter. Reset and try a different sync order.
Plain number (newest write wins)
Phone A
0
written at t=0
Laptop B
0
written at t=0
Server C
0
written at t=0
G-Counter CRDT (one slot per machine, merge = biggest of each slot)
Phone A
0
slots [0, 0, 0]
Laptop B
0
slots [0, 0, 0]
Server C
0
slots [0, 0, 0]

Both rows get the same clicks and the same syncs. The +1 buttons in the two rows do the same thing.

Likes really clicked
0
the true answer
Plain counter says
0
correct
G-Counter says
0
correct
Syncs done
0
Three copies of the same like counter, all at 0. Click +1 on different copies (they cannot talk to each other yet), then press a sync button.

The G-Counter is the simplest CRDT. Each machine only ever adds to its own slot, and merging takes the biggest value per slot. That merge gives the same answer in any order, any number of times (commutative, associative, idempotent), so the copies always converge.

07How to Use It / Steps / Implementation

Using CRDTs in a design

  1. 1
    Ask if conflicts are really possible
    Concurrent writes to the same data in different places? If yes, you need a plan. If one leader takes all writes, you do not need a CRDT.
  2. 2
    Pick the data shape
    Counter, set, map, register or text. Choose the type whose merge matches the meaning you want (for a cart, an OR-Set).
  3. 3
    Choose state-based or operation-based
    State-based tolerates a messy network and is simpler. Operation-based sends less data but needs reliable, causal delivery. Delta-state sits in between.
  4. 4
    Use a tested library
    Do not invent your own merge. Use Yjs, Automerge, Riak data types or the types in your database.
  5. 5
    Sync in the background
    Merge on reconnect, on a timer, or through a gossip protocol. Any order is fine.
  6. 6
    Clean up metadata
    Removed items leave tombstones and old replicas leave slots. Plan garbage collection once every replica has seen them.
  7. 7
    Test with chaos
    Test with replicas going offline, duplicate and reordered messages. The copies must always agree at the end.
๐Ÿ’กPair it with gossip
Because merges are safe to repeat and reorder, CRDTs fit nicely with gossip: machines swap state with random peers, and everything converges without extra coordination.
โš ๏ธNot every rule fits
"Balance must never go below zero" or "only one person gets this seat" need agreement at one moment. A plain CRDT cannot enforce such limits. Use consensus or a transaction for those parts.

08Key Terms to Know

TermMeaning in easy words
CRDTConflict-free Replicated Data Type: data designed so all replicas converge by merging
ReplicaOne copy of the data, on one machine or device
Strong eventual consistencyReplicas that have seen the same updates are always in the same state
CommutativeOrder of merging does not change the result
AssociativeGrouping of merges does not change the result
IdempotentMerging the same data again changes nothing
State-based (CvRDT)Replicas send their full state and merge it
Operation-based (CmRDT)Replicas send operations and apply them
G-Counter / PN-CounterA grow-only counter, and one that can also decrease
OR-SetA set with add and remove, using unique tags to avoid conflicts
TombstoneA marker left behind for a removed item, so a merge knows it was removed

09Pros, Cons and Trade-offs

โœ… Pros
  • Writes are local, fast and always available
  • No locks, leader or coordinator needed
  • Works offline and across partitions
  • Merges in any order, with duplicates
  • No silent loss of updates when the type is chosen well
โš ๏ธ Cons
  • Only eventual consistency: copies differ for a while
  • Cannot enforce rules like โ€œnever below zeroโ€
  • Metadata and tombstones can grow large
  • Design of the right type can be tricky
  • Results may surprise users (for example, a re-add beats a remove)

Trade-offs

ChoiceWe gainWe lose
CRDT instead of a leaderAlways-available writes, low latencyNo strict global order or limits
State-basedSimple, robust to bad networksBigger messages
Operation-basedSmall messagesNeeds reliable causal delivery
Last-write-wins registerVery simpleConcurrent writes are dropped silently
OR-SetNo lost adds, sensible removesExtra metadata for tags and tombstones
Text CRDTWorks offline and peer-to-peer, no central serverHeavier than a server-ordered approach like OT

10Common Problems and Mistakes

Common mistakes

  1. Using last-write-wins and calling it a CRDT. It converges, but it throws away concurrent writes.
  2. Writing your own merge. A subtle bug breaks convergence in rare cases. Use a proven library.
  3. Expecting invariants. A counter CRDT cannot stop two people buying the last item.
  4. Ignoring metadata growth. Tombstones and per-replica slots keep growing without cleanup.
  5. Relying on wall-clock time. Machine clocks differ. Use logical clocks or unique IDs.
  6. Surprising merges. Two users edit the same field and the result may not be what either wanted. Show the user what happened.

Things to watch

๐ŸชฆTombstone build-up
Deleted items leave markers. Remove them only after every replica has seen the delete.
๐ŸงฎLarge state
Full-state merges get heavy. Use delta CRDTs to send only changes.
๐Ÿ”€Anomalies
Concurrent add and remove can give a result users did not expect. Pick the semantics on purpose.
๐Ÿ”Trust
A bad replica can send a huge counter value. Merge assumes honest participants.

11Real-World Examples

๐ŸŸRiak
Offers built-in CRDT types such as counters, sets and maps, so apps do not have to resolve conflicts.
๐Ÿ”ดRedis Enterprise Active-Active
Uses CRDT-based types to merge writes made in different regions.
๐ŸงพCollaborative editors
Libraries like Yjs and Automerge use text and list CRDTs for shared editing and local-first apps.
๐ŸŽตSoundCloud and others
Have used CRDT sets and counters for timelines and feeds across data centres.
๐Ÿ’ฌChat and presence systems
Use CRDTs for sets of online users and read states.
๐ŸŒDistributed databases
Several databases use CRDT-like merging for multi-region writes. Check each product's docs for exact behaviour.
๐Ÿ“Note
Which companies use which CRDT type changes over time. Treat these as examples of the idea and check current docs.
Mini case: a shared shopping cart on two devices
๐Ÿ“ฑPhoneadds milk
โ†”merge
๐Ÿ’ปLaptopadds eggs, removes bread
โ†’โ†“=
๐Ÿ›’Cartmilk, eggs
Replica 1 Replica 2 Merged
Phone and laptop both edit offline, then merge with an OR-Set.

12Related Topics to Read Next

Consistency Modelsโ†’

CRDTs give strong eventual consistency, a model between eventual and strong.

Gossip Protocolโ†’

A natural way to spread CRDT state between replicas.

Operational Transformationโ†’

The other main way to merge concurrent edits, used by Google Docs.

Vector Clocksโ†’

Detect which updates are concurrent, and track what a replica has seen.

Network Partitionsโ†’

CRDTs let both sides of a split keep working.

CAP Theoremโ†’

CRDTs make the choice of availability over strict consistency practical.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: data types whose merge function never conflicts, so replicas converge on their own.
  • โœ”Merge rules: commutative, associative, idempotent.
  • โœ”Two styles: state-based (send state) and operation-based (send operations).
  • โœ”Types: G-Counter, PN-Counter, G-Set, OR-Set, LWW-Register, text CRDTs.
  • โœ”Gain: local, always-available writes, offline support, no lock or leader.
  • โœ”Cost: eventual only, metadata and tombstones grow, no global invariants.
  • โœ”Used in: Riak, Redis Active-Active, Yjs, Automerge, local-first apps.
  • โœ”One line: โ€œDesign the data so that every merge order gives the same answer.โ€
โ† Previous
Gossip Protocol
Next โ†’
Operational Transformation