Skip to content

CRDTs: Conflict-Free Replicated Data Types ​

"Replicas of any CRDT are guaranteed to converge in a self-stabilising manner, despite any number of failures." — Marc Shapiro, Nuno Preguiça, Carlos Baquero and Marek Zawirski, Conflict-free Replicated Data Types, INRIA Research Report RR-7687, 2011 (SSS 2011)

Summary: A CRDT (conflict-free replicated data type) is a data type whose replicas accept writes with no coordination at all, exchange states or operations in any order, and still end up identical, because the merge is designed so that order never matters. This page covers the theory (strong eventual consistency, state-based, operation-based and delta-state CRDTs), the full catalogue with exact merge rules, the text and JSON CRDTs behind collaborative apps, the metadata and garbage-collection bill, and what CRDTs cannot do. Focus: Strong eventual consistency; CvRDT and the join-semilattice (commutative, associative, idempotent merge); CmRDT and causal delivery; delta-state CRDTs; G-Counter, PN-Counter, G-Set, 2P-Set, LWW-Register, MV-Register, LWW-Element-Set, OR-Set with dots (add-wins vs remove-wins), OR-Map; sequence CRDTs (RGA, Logoot, LSEQ, Treedoc, WOOT) and text CRDTs (Yjs/YATA, Automerge, Fugue, Peritext); the JSON CRDT; tombstones, causal stability and garbage collection; interleaving anomalies and intent preservation; CRDTs vs operational transformation; Riak data types, Redis Active-Active (CRDB), Akka Distributed Data, SoundCloud Roshi, AntidoteDB, Figma multiplayer; global invariants, size and Byzantine peers. Learning goal: For any piece of replicated state, say whether a CRDT fits, pick the type and its conflict rule (add-wins or remove-wins, LWW or multi-value), estimate its metadata, implement and test the merge (Go property tests, a Laravel merge-on-write endpoint over PostgreSQL JSONB), and recognise the cases that still need coordination.

This chapter is in the Distributed Systems Primitives group. It owns merge-by-construction. Neighbouring pages own the rest: which consistency model "strong eventual" sits in is in Consistency Models; how multi-leader and leaderless replication create the concurrent writes in the first place, and the menu of conflict-resolution options (LWW, siblings, merge), is in Replication Topologies; version vectors, Lamport clocks and hybrid logical clocks in depth are in Vector Clocks, Lamport Clocks & Distributed Causality; anti-entropy and read repair that move CRDT states around are in Merkle Trees, Read Repair, Anti-Entropy & Tombstones and Gossip Protocols; the CAP trade-off that makes AP data worth merging is in CAP and PACELC.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
What problem CRDTs solve and the trade-offWhy it exists
Wuu and Bernstein, Treedoc, Shapiro 2011, Riak 2.0, Yjs, Automerge, FugueWhere it comes from
Strong eventual consistency, convergenceSEC
State-based (CvRDT), join-semilatticeCvRDT
Operation-based (CmRDT), causal deliveryCmRDT
Delta-state CRDTsDelta-state
G-Counter, PN-CounterCounters
LWW-Register, MV-RegisterRegisters
G-Set, 2P-Set, LWW-Element-SetSimple sets
OR-Set, dots, add-wins vs remove-winsOR-Set
OR-Map and nestingMaps
RGA, Logoot, LSEQ, Treedoc, WOOTSequences
Yjs (YATA), Automerge, Fugue, PeritextText CRDTs
The JSON CRDTJSON CRDT
Tombstones, causal stability, garbage collectionMetadata and GC
Interleaving anomalies, intent preservationIntent
CRDTs vs operational transformation, Google DocsCRDT vs OT
Global invariants, size, Byzantine peersLimitations
Riak, Redis Active-Active, Akka, Roshi, AntidoteDB, FigmaIn production
Merge rules, sizes, knobs, error messagesMechanics
CodeGo, Laravel
Likes, carts, offline apps, editors, stock, metadata blow-upSolving the classic problems
Which CRDT for which dataChoosing
Monolith to multi-regionIn architecture
Run the scenarios yourselfLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The three families.

FamilyWhat travelsWhat the network must doWhat the type must doTypical use
State-based (CvRDT)The whole stateEventually deliver some state; loss, duplicates and reordering are fineMerge is a join: commutative, associative, idempotent; updates only grow the stateRiak data types, gossip between servers
Operation-based (CmRDT)Each operationCausal delivery, exactly onceConcurrent operations commuteYjs updates, Automerge changes, RGA
Delta-state (delta-CRDT)The small delta an update producedAny channel; some types need causal delivery of deltasDeltas are states, joined like statesAkka Distributed Data, Riak's newer types

The catalogue.

TypeStateMergeWhat concurrent conflict doesWatch out
G-CounterOne count per replicaPer-replica maxBoth increments countOnly grows
PN-CounterTwo G-Counters (P, N)Merge bothBoth counted; value = P - NCan go below zero
LWW-RegisterValue + timestampLarger timestamp winsOne write silently lostClock skew picks the winner
MV-RegisterValues + version vectorsKeep non-dominated valuesBoth kept as siblingsReader must resolve
G-SetSetUnionn/a (no remove)Only grows
2P-SetAdd set + remove setUnion bothRemove winsRemoved forever
LWW-Element-SetAdd and remove sets with timestampsUnion; latest timestamp per elementLatest timestamp wins (bias decides ties)Clocks again
OR-Set (add-wins)Elements with unique tags (dots) + causal contextKeep a dot unless the other side saw and dropped itAdd winsMetadata per add
Remove-wins setLike OR-Set, bias reversedKeep a removal unless an add saw itRemove winsRarely what users expect
OR-MapKeys as OR-Set, values are CRDTsMerge keys, merge values recursivelyUpdate wins over concurrent key removalResurrected half-objects
RGA / YATA / FugueElements with unique IDs, anchors, tombstonesInsert by anchor + ID orderBoth inserts kept, deterministic orderTombstones, interleaving

What CRDTs do not give you.

NeedWhy a CRDT cannotWhat to use instead
Balance never below zero, stock never oversoldA global invariant cannot be checked from local stateConsensus, one owner per key, escrow / bounded counter
Unique username, last seatTwo replicas can both grant itLinearizable compare-and-set (Consistency Models)
"Exactly what the user meant" in textConvergence is not intentText CRDTs designed for intent (Fugue, Peritext) and UX
Protection from a malicious replicaThe classic model assumes non-Byzantine replicasSigned, hash-linked operations (BFT CRDTs), or a trusted server
Small, bounded metadata foreverTags, tombstones and vectors growCausal-stability GC, compaction, snapshots
State-based (CvRDT)Delta-state (delta-CRDT)Operation-based (CmRDT)ship the whole stateship only what the update changedship the operationreplica A{eu:3, us:2}replica Bmerge = joinreplica Ainc(eu)replica Bjoin deltadelta {eu:4}full statereplica Ainsert(x, after id)replica Bapply effectcausal broadcast:exactly once, after dependenciesChannel: any. Loss, duplicates,reordering are fine (idempotent).Needs: commutative, associative,idempotent merge (semilattice).Cost: message = full state.Riak, Akka Distributed Data.Channel: any (unreliable OK).Deltas are states: join them.Some types need causal deliveryof deltas (Akka ORSet).Cost: small messages, buffered.Akka GCounter, ORSet deltas.Needs: concurrent ops commute;delivery is the hard part.Cost: smallest messages.RGA, Yjs updates, Automerge changes.All three give strong eventual consistency: replicas that received the same updates are equal.

The picture is the whole theory in one line each: state-based CRDTs ship states over a sloppy network and rely on an idempotent join; delta-state CRDTs ship the small part of the state that changed; operation-based CRDTs ship tiny operations but need a delivery layer that is causal and exactly-once.

Why it exists ​

The moment two replicas accept writes without asking each other first (two regions, a phone and a laptop, two users in the same document), they will diverge. Something must bring them back together. The classic answers are to prevent divergence (one leader, consensus: you pay a round trip and lose availability during a partition) or to repair it after the fact (last-writer-wins, application merge code, siblings shown to the user: you pay in lost updates or in bugs). Shapiro et al. put it bluntly: published eventual-consistency approaches "are ad-hoc and error-prone". A CRDT is the third answer: design the data type so that merging is a mathematical operation that cannot conflict.

Coordinate before writing (single leader, consensus)Merge after writing (CRDT)
Every write pays a round trip to the leader or a quorumWrites are local: microseconds, works offline
Minority side of a partition cannot writeEvery replica can always read and write
Any invariant can be enforced (uniqueness, balance)Only invariants that hold locally survive
Simple data model (any value, any update)Data must be modelled as CRDT types; semantics chosen per type
Metadata: a log positionMetadata: version vectors, dots, tombstones, per replica
Failure mode: unavailability, timeoutsFailure mode: surprising merge results ("why is this item back?")

The analogy we reuse on this page: the family shopping list in several notebooks. Each family member carries their own notebook copy of the shopping list and edits it whenever they like, even underground with no signal. When two of them meet, they compare notebooks and copy across what is missing. A G-Counter is "each person keeps their own tally of eggs bought; the total is the sum of everyone's latest tally". Last-writer-wins is "whoever's notebook has the later timestamp wins the whole line", which is how Dad's "milk" disappears because Mum's watch is fast. An OR-Set is "every item you write gets your initials and a number; crossing out an item only crosses out the numbered entries you could see", so if Mum crosses out milk while Dad, elsewhere, writes milk again, Dad's new entry survives. A tombstone is the crossed-out line you cannot erase yet, because someone who has not seen the crossing-out might still write "add bread after the milk line".

Three common misunderstandings, up front ​

  1. "CRDT means no conflicts." It means no unresolved conflicts: every concurrent conflict has a pre-decided, deterministic outcome (add wins, both values kept, larger ID first). Whether that outcome is what users wanted is a product decision you still have to make.
  2. "CRDTs give strong consistency without coordination." They give strong eventual consistency: replicas that saw the same updates are equal. A read can still be stale, two replicas can still disagree right now, and no invariant that needs global knowledge (balance at least zero) can be enforced.
  3. "State-based and operation-based are different capabilities." Shapiro et al. prove each can emulate the other. The real difference is where the cost goes: big messages on a dumb network, or small messages on a smart (causal, exactly-once) network.

Where it comes from ​

  • 1976 to 1984, the ancestors. Johnson and Thomas (RFC 677, The Maintenance of Duplicate Databases, 1976) used last-writer-wins to arbitrate concurrent updates to a replicated database: the LWW-Register (the 2011 paper credits them: "Johnson and Thomas invented the LWW-Register"). Wuu and Bernstein (PODC 1984) built a replicated dictionary from two add-only sets plus a vector-clock-based garbage collector; Shapiro et al. call the construct U-Set.
  • 1989, operational transformation. Ellis and Gibbs (SIGMOD 1989) introduced OT for group editors; the Fugue paper notes that the OT algorithm Jupiter later became the basis of Google Docs' real-time collaboration, which Google itself described in a 2010 blog series.
  • 2006 to 2011, sequence CRDTs. WOOT (Oster et al. 2006), Treedoc (Preguiça, Marquès, Shapiro, Leția, ICDCS 2009), Logoot (Weiss, Urso, Molli 2009), RGA (Roh et al., JPDC 2011). The 2011 paper says the CRDT concept "was invented by Shapiro and Preguiça on their work on Treedoc".
  • 2011, the formal theory. Shapiro, Preguiça, Baquero and Zawirski: Conflict-free Replicated Data Types (SSS 2011, INRIA RR-7687) defines strong eventual consistency, CvRDTs and CmRDTs, and proves they are equivalent; A comprehensive study of Convergent and Commutative Replicated Data Types (INRIA RR-7506) catalogues counters, registers, sets, graphs and sequences, and garbage collection.
  • 2013 onwards, in databases. Riak KV ships counters, sets, maps, registers and flags ("inspired by the work of Marc Shapiro, Nuno Preguiça, Carlos Baquero, and Marek Zawirski"); SoundCloud open-sources Roshi, an LWW-element-set over Redis (now archived). LSEQ (Nédelec et al., DocEng 2013) adapts identifier allocation for sequences.
  • 2014 to 2016, smaller messages and richer data. Almeida, Shoker and Baquero's delta-state CRDTs (arXiv 2014, 2016); the YATA paper (2016), implemented with modifications by Yjs; Kleppmann and Beresford's JSON CRDT (2016, IEEE TPDS 2017), the basis of Automerge.
  • Late 2010s, products. Redis Enterprise Active-Active databases (formerly CRDB), Akka Distributed Data, AntidoteDB, and Figma's multiplayer (October 2019 post: "inspired by" CRDTs, while "Figma isn't using true CRDTs though").
  • 2019 to 2023, quality of merges. Kleppmann et al. describe the interleaving anomaly (PaPoC 2019); Ink & Switch's Peritext (CSCW 2022) handles rich-text formatting; Kleppmann's Making CRDTs Byzantine Fault Tolerant (PaPoC 2022); Weidner and Kleppmann's Fugue (arXiv 2023) defines maximal non-interleaving.
text
     Year   Milestone                                   What practitioners got
1    1976   Johnson & Thomas (RFC 677): LWW             A deterministic, lossy tie-break
2    1984   Wuu & Bernstein: replicated dictionary      Add/remove sets + vector-clock GC
3    1989   Ellis & Gibbs: operational transformation   Real-time group editing via a server
4    2006   WOOT                                        First sequence CRDT for text
5    2009   Treedoc, Logoot                             Dense position identifiers
6    2011   RGA; Shapiro et al. SEC, CvRDT/CmRDT        Theory + catalogue + GC via stability
7    2013+  Riak KV data types, Roshi, LSEQ             CRDTs inside production databases
8    2016   Delta-state CRDTs, YATA/Yjs, JSON CRDT      Small messages, nested JSON documents
9    2019   Figma multiplayer, interleaving anomaly     Server-ordered CRDT ideas; merge quality
10   2022   Peritext, BFT CRDTs                         Rich text; untrusted peers
11   2023   Fugue / FugueMax                            Proven maximal non-interleaving

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what products provide, and how to use it.

Strong eventual consistency and convergence Must-know ​

In plain words: two replicas that have received the same set of updates are already identical, immediately, with no extra "conflict resolution" round, no rollback and no vote.

Common misunderstanding: "Eventual consistency and strong eventual consistency are the same thing." Eventual consistency only promises that replicas converge eventually if writes stop, and allows a system to apply an update, discover a conflict later and roll back. Shapiro et al. call that out: such a system "in general requires a consensus to ensure that all replicas arbitrate conflicts in the same way". SEC removes the rollback: same updates, same state, right now.

Definition: Shapiro et al. 2011, Definition 2.3: an object is strongly eventually consistent if it is eventually consistent (eventual delivery, convergence, termination) and has strong convergence: "Correct replicas that have delivered the same updates have equivalent state". The paper adds that "SEC does not require to solve consensus" and that a SEC object tolerates up to n-1 simultaneous crashes. SEC is a convergence guarantee, not an ordering or recency guarantee: see where it sits in Consistency Models.

text
     Replica A (EU)            Replica B (US)            Notes
1    likes: {eu:0, us:0}       likes: {eu:0, us:0}
2    +1  -> {eu:1}             +1 -> {us:1}              both accept writes, no coordination
3    +1  -> {eu:2}                                       partition: A and B cannot talk
4    read = 2                  read = 1                  stale but legal under SEC
5    ---- partition heals, states exchanged in either direction, maybe twice ----
6    merge -> {eu:2, us:1}     merge -> {eu:2, us:1}     same updates delivered => same state
7    read = 3                  read = 3                  no rollback, no vote

Real scenario: like and view counters in several regions; presence and "online" sets; offline-first notes and to-do apps; collaborative documents; shopping carts that merge across devices; configuration that each node gossips (Akka cluster sharding state).

What provides it:

ProductSEC claim in its docsMechanism
Redis Enterprise Active-Active"strong eventual consistency model"CRDT types + vector clocks, syncer between clusters
Riak KV data types"eventually-convergent data types"State-based merge (riak_dt) behind an operation API
Akka Distributed DataReplicated data types with consistency levels per read/writeState and delta CRDTs, gossip
Automerge, YjsMerges without conflicts, any networkOperation-based list CRDTs, causal metadata
AntidoteDB"CRDTs" and "Highly Available Transactions" on its home pageGeo-replicated CRDT database (research project)

Fix / how to use it: use SEC where the business can live with "stale but never contradictory after sync" and where the merge rule of the type is acceptable to users; add session guarantees for the user's own writes on top (the device always merges its own state first).

State-based CRDTs (CvRDT) and the join-semilattice Must-know ​

In plain words: each replica keeps a state that only ever "grows" in some order, and merging two states means taking the smallest state that contains both. Because that operation does not care about order or repetition, you can gossip whole states around in any way you like.

Common misunderstanding: "Any merge function that looks reasonable will converge." It must satisfy three laws. Last-writer-wins on a value with ties broken randomly is not idempotent across replicas; summing two counter states is not idempotent (merging the same state twice doubles it); "union, then remove what the other side removed" is not associative. Each of those has shipped to production and diverged.

Definition: a join-semilattice is a partial order with a least upper bound (LUB, written as join) for every pair. Shapiro et al.: "It follows that ⊔ is: commutative: x ⊔ y = y ⊔ x; idempotent: x ⊔ x = x; and associative: (x ⊔ y) ⊔ z = x ⊔ (y ⊔ z)." A monotonic semilattice object has (i) states forming a semilattice, (ii) merge = LUB, (iii) updates that never go down the order (s ≤ s • u). Theorem 2.1: assuming eventual delivery and termination, such an object is SEC. That object is a CvRDT (convergent replicated data type).

text
     Law            Why it matters on a real network                Counter-example that breaks it
1    Commutative    A gets B's state first, B gets A's first        "keep the local value on ties"
2    Associative    Gossip in any grouping: (A+B)+C = A+(B+C)       "union adds, then subtract removes"
3    Idempotent     Retries, duplicates, anti-entropy re-sends      "merge = add the two counts"
4    Monotonic      An update never undoes knowledge                "reset the counter to 0 locally"

Real scenario: server-to-server replication where messages are lost or duplicated (Riak, Akka gossip); devices that upload their whole state when they come online (the Laravel endpoint below); anti-entropy that resends whole objects found different by a Merkle tree.

What provides it:

ProductState-based whereMerge transport
Riak KVriak_dt merges replica states (docs: "the convergence logic is state-based behind the scenes")Vnode replication, read repair, active anti-entropy
Akka Distributed DataReplicatedData.merge for every typeGossip, direct replication with WriteMajority/WriteAll
Redis Active-ActiveFull sync between participating clusters when partial sync is impossibleSyncer
Your own serviceDevices upload states; server joinsHTTP, files, anything

Fix / how to use it: prove the three laws with property tests (the Go snippet uses testing/quick for exactly this), keep state monotonic (no "reset" without a CRDT-aware reset), and ship deltas when states are large.

Operation-based CRDTs (CmRDT) and causal delivery Must-know ​

In plain words: instead of shipping the state, each replica ships the operation it performed ("insert x after element 7@ana"), and every replica applies every operation. That works if operations that could happen concurrently give the same result in either order, and if the network delivers each operation exactly once and never before what it depends on.

Common misunderstanding: "Operations commute, so delivery order does not matter." Only concurrent operations commute. Causally related ones do not: "delete element 7@ana" applied before "insert element 7@ana" deletes nothing and leaves the character visible forever. And applying an operation twice usually is not idempotent (increment twice). So CmRDTs push work into the delivery layer.

Definition: an op-based object splits an update into a side-effect-free prepare at the source and an effect applied at every replica. Shapiro et al. assume "a reliable causally-ordered broadcast communication protocol, i.e., one that delivers every message to every recipient exactly once and in an order consistent with happened-before". Theorem 2.2: with causal delivery, if all concurrent updates commute, the object is SEC (a CmRDT, commutative replicated data type). Causal delivery is usually implemented with a version vector per message: deliver an operation from replica j when it is the next one from j and everything j had seen is already delivered here; buffer it otherwise.

text
     Ana                          Network                         Ben
1    insert 'x' (op a1)  ------>  delayed
2    delete 'x' (op a2, after a1) ---------------------------->  arrives first
3                                                                 a2 needs a1: buffer (do not apply)
4                       a1 arrives ----------------------------> apply a1, then a2 from the buffer
5                       a1 arrives again (retry) --------------> already delivered: drop
6    text = ""                                                    text = ""   (converged)

Real scenario: collaborative text (Yjs updates, Automerge changes, the RGA snippet), where shipping the whole document per keystroke is unthinkable; Riak and Redis expose an operation API to clients even when replicas merge states internally; AntidoteDB exposes typed update operations (increment, add, assign, enable) to clients.

What provides it:

SystemOp-based partHow causal, exactly-once delivery is achieved
YjsDocument updates (insertions are "a sequential operation based CRDT")Each item carries (clientID, clock); missing items are fetched by state vector
AutomergeA document "has a history made up of commits", like a git repositoryA transport-agnostic sync protocol exchanges the commits a peer lacks
Akka Distributed Data deltasORSet deltas: "ORSet has support for delta-CRDT and it requires causal delivery of deltas."Delta propagation protocol with sequence numbers
The Go snippetRGAOpCausalInbox: version vector check, buffer, drop duplicates

Fix / how to use it: if you choose op-based, own the delivery layer explicitly: per-origin sequence numbers, a version vector per operation, a buffer for early arrivals, deduplication, and persistent storage of undelivered operations. If you cannot guarantee that, use state-based or delta-state instead.

Delta-state CRDTs Important ​

In plain words: keep the state-based merge (so the network can be sloppy), but after each update send only the small piece of state that changed. The piece is itself a state, so the receiver joins it like any other state.

Common misunderstanding: "A delta is just an operation." An operation is applied; a delta is joined. Delivering a delta twice is harmless (join is idempotent), and two deltas can be joined together before sending. Operations do not have those properties.

Definition: Almeida, Shoker and Baquero define delta mutators that return a delta-state "typically with a much smaller size than the full state", giving "small messages with an incremental nature, as in operation-based CRDTs, disseminated over unreliable communication channels, as in traditional state-based CRDTs". Some types (counters) converge with deltas in any order; types with causal context (OR-Set) need causal delivery of deltas or the occasional full state to stay correct.

text
     G-Counter with 100 replica slots, replica r042 increments once
1    full state: {"p":{"r000":5, ..., "r042":6, ..., "r099":5}}    907 bytes (lab output)
2    delta:      {"p":{"r042":6}}                                    16 bytes
3    receiver:   state = join(state, delta)                          per-slot max
4    duplicate:  state = join(state, delta)                          no change (idempotent)

Real scenario: Akka Distributed Data (enabled by default; akka.cluster.distributed-data.delta-crdt.enabled=off disables it) where "adding element 'c' and 'd' to set {'a', 'b'} would result in sending the delta {'c', 'd'}"; mobile sync where a device uploads only what changed since its last acknowledged state; large OR-Maps where one key changed.

What provides it:

ProductDelta supportCaveat from the docs
Akka Distributed DataGCounter, PNCounter, GSet (no causal delivery needed); ORSet, ORMap, ORMultiMap, PNCounterMap, LWWMap (causal delivery of deltas)"the full state is occasionally also replicated for delta-CRDTs", e.g. when new nodes join
Riak KVClients send operations; replicas merge stateNot exposed as deltas to the client
YjsencodeStateAsUpdate(doc, stateVector) returns only what the remote lacksNeeds one extra round trip for the remote state vector
The Go snippetGCounter.Inc returns the deltaCounters only

Fix / how to use it: for counters and grow-only sets, send deltas freely; for OR-Set-like types, either send deltas over an ordered, exactly-once channel per pair or fall back to full-state sync when in doubt (the Akka model).

Counters: G-Counter and PN-Counter Must-know ​

In plain words: give every replica its own tally. Each replica only ever increases its own tally; when two replicas meet, each slot takes the larger number; the total is the sum. For decrements keep a second set of tallies and subtract.

Common misunderstanding: "A counter is easy: send the increments." Sending "+1" messages over an at-least-once network double-counts on every retry, and sending the current total ("I have 7") loses the other region's increments. The per-replica slot with max-merge is exactly what makes retries and reordering harmless.

Definition: G-Counter state is a vector of non-negative integers indexed by replica; inc at replica i increments entry i; merge is the per-index maximum; value is the sum (Shapiro et al. 4.1, the same structure as a vector clock: "If each process pi is restricted to incrementing its own index inc(i), this is the well-known vector clock"). PN-Counter pairs two G-Counters P and N; value = sum(P) - sum(N); merge merges both.

text
     EU                         US                          Merged (both)
1    P{eu:3}                    P{us:2} N{us:1}
2    value 3                    value 1
3    receive US state           receive EU state
4    P{eu:3,us:2} N{us:1}       P{eu:3,us:2} N{us:1}       value 3 + 2 - 1 = 4
5    receive US state again     (retry)                     P max is unchanged: still 4

Real scenario: likes, views, followers, reactions across regions; quota usage reported by many nodes (eventually exact, never authoritative for enforcement); Riak counters ("Counting the amount of likes on a Facebook post"); Redis Active-Active INCRBY (counters "accumulate the total counter operations", 59-bit range).

What provides it:

ProductCounter typeNotes
Riak KVcounter bucket type, also inside maps"If you require unique, ordered IDs counters should not be used"
Redis Active-ActiveINCR/INCRBY/DECRBY on a string key59-bit counters; plain SET on the same key is LWW
Akka Distributed DataGCounter, PNCounter, PNCounterMapDelta support without causal delivery
AntidoteDBCounter, fat counter (supports reset), integer (with set)Fat counter costs storage linear in operations since reset
AutomergeAutomerge.CounterDocs: safer than changing a number value yourself

Fix / how to use it: one slot per writer (region, server or device), never per user; prune slots of retired replicas only with a coordinated step; never use a PN-Counter as the authority for "stock at least zero" (see Limitations). Go: crdt.PNCounter; Laravel: RegionalLikeCounter stores the slots as rows.

Registers: LWW-Register and MV-Register Must-know ​

In plain words: a register holds one value (a title, a status, an avatar URL). When two replicas set it concurrently, an LWW-Register keeps the write with the larger timestamp and throws the other away; an MV-Register keeps both and lets the reader decide.

Common misunderstanding: "LWW only loses data when clocks are wrong." It loses one of every pair of concurrent writes by design, even with perfect clocks. With imperfect clocks it also loses writes that were not concurrent: a replica whose clock runs 300 ms behind can make an edit after seeing the current value and still lose (the lab shows it). Shapiro et al.: LWW "ensures a total order of operations, at the cost of losing concurrent updates."

Definition: LWW-Register: payload (value, timestamp); assign sets both with a timestamp "consistent with causality"; merge keeps the pair with the larger timestamp, ties broken by replica ID. MV-Register: payload is a set of (value, version vector); assign writes a vector that dominates all vectors seen locally; merge keeps every entry not dominated by an entry on the other side. Concurrency detection needs version vectors; a scalar timestamp "is insufficient" (Shapiro et al. 3.2.2). Clocks and their pitfalls are in Vector Clocks.

text
     Phone (clock -300 ms)                 Laptop (clock correct)
1                                          title = "Q3 plan"  @t=1000
2    sync: sees "Q3 plan" @1000
3    title = "Q3 roadmap" @t=800  (wall)   (phone edited later in real time)
4    sync -> LWW keeps "Q3 plan" (1000 > 800): the newer edit is lost
5    with stamp = max(now, seen+1) = 1001 -> "Q3 roadmap" wins (causally later)
6    truly concurrent edits: MV-Register keeps {"Q3 plan", "Q3 roadmap"} until one write covers both

Real scenario: profile fields edited on two devices (LWW per field is usually acceptable); a document title (MV better: show both); feature-flag state replicated across regions; Figma document properties ("similar to a last-writer-wins register in CRDT literature", with the server defining the order instead of a timestamp); Dynamo's shopping cart, which used multi-value semantics and showed the deleted-item-reappears anomaly.

What provides it:

ProductLWWMulti-value
Redis Active-ActiveStrings and bitfields: "This is the only case with Active-Active databases where OS time is used to resolve a conflict."n/a
Riak KVRegisters inside mapsSiblings on plain keys, tracked with vector clocks or dotted version vectors
Cassandra / ScyllaDBEvery cell, by write timestamp (client or coordinator time)n/a
AntidoteDBLWW-Register: "The timestamps respect causality"MV-Register returns all concurrent values
AutomergeDefault read of a propertygetConflicts() shows the multi-value view
Akka Distributed DataLWWRegister, LWWMap (clock can be customised)n/a

Fix / how to use it: use LWW only where losing one of two concurrent writes is harmless; generate timestamps as max(now, last seen + 1) (a hybrid logical clock does this properly) so causally later writes always win; use an MV-Register where users would be upset to lose an edit, and show the siblings in the UI.

Sets: G-Set, 2P-Set and LWW-Element-Set Important ​

In plain words: a grow-only set (G-Set) only allows adds and merges by union. A two-phase set (2P-Set) adds a second grow-only set of removed elements: once removed, gone forever. An LWW-Element-Set stamps every add and remove with a time and lets the latest stamp per element decide.

Common misunderstanding: "A replicated set is just union." Union cannot remove: a removed element is still present in some other replica's copy and comes back at the next merge (the Dynamo cart anomaly; the before Go snippet reproduces it). Shapiro et al. show that add and remove do not commute, so "a CRDT can only approximate the sequential set"; every set CRDT is a choice of what wins when add and remove are concurrent.

Definition:

TypeStateLookup(e)Concurrent add(e) and remove(e)Re-add after remove
G-SetSet Ae in An/an/a
2P-SetA (adds), R (removes, the "tombstone set")e in A and e not in RRemove winsNever
U-Set2P-Set with unique elements, op-basede added and not removedCannot happen (remove is causally after add)Use a new unique element
LWW-Element-SetA and R of (element, timestamp)Latest add newer than latest removeLater timestamp wins; equal stamps: bias (add or remove)Yes, with a newer timestamp
PN-SetCounter per element, present if > 0count > 0Counts add upAnomalies when the count goes negative
text
     2P-Set                                 LWW-Element-Set (add-biased)
1    A={milk}         R={}                  A={(milk,10)}  R={}
2    remove milk  ->  R={milk}              remove @20 -> R={(milk,20)}
3    add milk     ->  no effect, ever       add @30    -> A={(milk,10),(milk,30)}  present
4    lookup: absent                         a replica with a slow clock adds @15: absent (lost)

Real scenario: G-Set: set of seen message IDs, set of all users who ever joined; 2P-Set: revoked API keys or banned IDs that must never come back; LWW-Element-Set: SoundCloud Roshi stores activity-stream events by external timestamp ("time-series event storage via a LWW-element-set CRDT with limited inline garbage collection", on top of Redis, in Go).

What provides it: Akka GSet (and a documented two-phase set example built from two GSets); AntidoteDB G-Set; Roshi LWW-element-set; Redis Active-Active sorted sets and sets use OR-Set semantics instead.

Fix / how to use it: choose 2P-Set only when "removed forever" is the requirement; choose LWW-Element-Set only when the timestamps are meaningful to the business (event time) rather than wall clocks of random servers; otherwise use an OR-Set.

OR-Set: observed-remove, add-wins vs remove-wins, dots Must-know ​

In plain words: every add gets a unique tag. A remove deletes only the tags it has seen. If someone else concurrently added the same element, their tag was not seen by the remove, so the element stays. That is "add wins", and it is what people usually expect from a shopping cart or a tag list.

Common misunderstanding: "OR-Set needs a tombstone for every removed element forever." The original op-based OR-Set keeps (element, tag) pairs and removes observed pairs; the state-based version naively keeps removed tags. The optimised form (Riak's ORSWOT, Almeida et al.'s add-wins set) keeps a causal context (a version vector of every dot seen) instead: a dot that is in the context but not in the entries is a remembered removal. Metadata is then proportional to elements plus replicas, not to the history of removals.

Definition: Shapiro et al. 3.3.5: "The intuition is to tag each added element uniquely, without exposing the unique tags in the interface. When removing an element, all associated unique tags observed at the source replica are removed, and only those." A dot is a pair (replica, counter): the counter-th event of that replica, which makes a unique tag cheap. State: entries (element to its live dots) plus causal context. Add at replica r: increment ctx[r], the element's dots become {(r, ctx[r])}. Remove: drop the element's dots. Merge: keep a dot if both sides have it, or if one side has it and the other side's context does not contain it; join the contexts. Remove-wins (AntidoteDB's RW-Set: "remove-operations win over concurrent add-operations") reverses the bias: an add overwrites only removes it has seen.

phonelaptopadd(milk)milk: [phone:1]ctx {phone:1}syncremove(milk) (offline)entries: nonectx {phone:1} = remembered removaladd(milk) again (offline)milk: [laptop:1]ctx {phone:1, laptop:1}mergemilk: [laptop:1]ctx {phone:1, laptop:1}milk: [laptop:1]ctx {phone:1, laptop:1}phone:1 is in both contexts and in neither entry list: removed. laptop:1 was never seen by the phone: kept.The remove only deletes the dots it observed, so the concurrent add wins.
text
     Phone                                   Laptop
1    add(milk) -> milk:[phone:1] ctx{phone:1}
2    ---------------- sync ----------------> milk:[phone:1] ctx{phone:1}
3    remove(milk) -> entries {} ctx{phone:1}  add(milk) -> milk:[laptop:1] ctx{phone:1, laptop:1}
4    ---------------- merge both ways -------------------------------------------
5    phone:1: in both contexts, in neither entries -> removed
6    laptop:1: not in phone's context -> kept      result: {milk} on both  (add wins)
7    laptop removes milk after seeing laptop:1 -> merge -> {} on both (observed remove sticks)

Real scenario: shopping carts on phone and laptop; tags or labels on a document; group membership edited from several admin consoles; the set of open sessions per user; Redis Active-Active sets and hashes ("remove can only remove instances it has already seen and in all other cases element add wins"); Riak sets ("Storing items in an e-commerce shopping cart").

What provides it:

ProductSet semanticsNotes
Redis Active-ActiveSets, hashes (fields), sorted sets (members): OR-Set, add/update winsScores in sorted sets merge like counters
Riak KVset bucket type, sets inside mapsRemoves need the causal context fetched with the read
Akka Distributed DataORSet, ORMap, ORMultiMapRemoval: read with ReadMajority first (docs advise it for ORSet removes)
AntidoteDBAW-Set (add-wins) and RW-Set (remove-wins)Both offered; choose per data
The Go and PHP snippetsAdd-wins with dots and causal contextSame JSON shape across both

Fix / how to use it: default to add-wins for user-facing collections; pick remove-wins for safety-oriented sets (permissions, blocklists) where a concurrent re-grant must not silently win; always remove with the context you read (Riak, Akka), never blind.

Maps: OR-Map and nested CRDTs Important ​

In plain words: a map whose keys behave like an OR-Set and whose values are themselves CRDTs (a counter, a register, a set, another map). Updating a field merges into the existing value; removing a key removes what you have seen.

Common misunderstanding: "Removing a key from a map removes the object everywhere." If another replica concurrently updates a field inside that key, the update wins in an add-wins map and the key comes back with only that field: a half-object. Kleppmann and Beresford show this with a to-do item removed on one replica and marked done on another: the item reappears without its title.

Definition: an OR-Map keeps an OR-Set (with dots) of keys and a CRDT per key; merge merges the key sets and then each value type pairwise. Riak's map "is the most versatile of the Riak data types because all other data types can be embedded within them, including maps themselves". AntidoteDB offers three removal semantics: G-Map (no removal), AW-Map (update wins over concurrent remove; "markers for removed elements might never be cleaned up") and RR-Map (remove resets the nested value).

text
     Replica P                                Replica Q
1    todo#7 = {title:"buy milk", done:false}  (same)
2    remove key todo#7                        set todo#7.done = true
3    ---------------- merge ----------------
4    add-wins map: todo#7 = {done:true}       title gone: a "resurrected" half-object
5    remove-resets map: todo#7 reset, then done:true applied -> same shape, still no title
6    application fix: treat "no title" as deleted, or put a deleted flag (LWW) in the object

Real scenario: user profile as a map of registers and counters (Riak's tweet example: counter numberOfRetweets, registers username, tweetContent, flag favorited?); per-product inventory display maps; document metadata in Automerge and Yjs (Y.Map: "The last inserted entry for each key is used").

What provides it: Riak maps; Akka ORMap, LWWMap, PNCounterMap, ORMultiMap; AntidoteDB G-Map, AW-Map, RR-Map; Automerge objects; Yjs Y.Map.

Fix / how to use it: model entities whose existence matters with an explicit deleted register (or a remove-wins flag) instead of key removal; split large maps into several top-level entries (Akka: one ORMap with 1000 elements is less efficient than "10 top level ORMap entries with 100 elements each").

Sequences: RGA, Logoot, LSEQ, Treedoc and WOOT Must-know ​

In plain words: a list or text cannot be merged by index ("insert at position 5"), because position 5 means something different on every replica. Sequence CRDTs give every element a permanent unique ID and express every edit relative to IDs ("insert 'x' right after element 7@ana", "delete element 3@ben"). Two families exist: anchor-based (RGA, WOOT, YATA, Fugue) and dense-position-based (Treedoc, Logoot, LSEQ).

Common misunderstanding: "Deleted characters can simply be removed." A concurrent insert on another replica may still say "after the character you deleted". The deleted element must stay as a tombstone until no such operation can arrive; dense-position schemes avoid tombstones for ordering but pay with growing identifiers.

Definition:

AlgorithmElement identityWhere a new element goesDeletesKnown weakness
WOOT (2006)Unique ID + previous and next neighbours at insert timeBetween its two neighbours, ties by IDTombstones (never collected)Slow; interleaves in some cases (Fugue table)
Treedoc (2009)Path in a binary tree, plus disambiguator for concurrent insertsInfix order of the treeTombstones; rebalancing is a GC that needs agreementTree becomes unbalanced; interleaving
Logoot (2009)Dense position identifier (list of digits + site ID)Sort by identifier; new ID between neighboursRemoved outright (no tombstones)Identifiers grow; character-level interleaving
LSEQ (2013)Like Logoot, adaptive allocation strategy per depthSort by identifierRemoved outrightInterleaving observed in practice
RGA (2011)Lamport timestamp (counter, replica)Right after its anchor, after any elements with a greater ID already thereTombstones"Lesser" interleaving when a user types backwards
YATA / Yjs (2016)(clientID, clock); origin and originRightBetween left and right origin, conflict rule on concurrent itemsDelete set (state-based); content GCBackward interleaving in the multi-replica case (Fugue table)
Fugue / FugueMax (2023)Tree of left/right childrenTree traversal orderTombstonesProven maximal non-interleaving (FugueMax)
RGA: insert after an anchor ID; concurrent inserts at one anchor are ordered by ID, larger firstH1@ana dele2@anal3@anal4@anao5@ana!6@anaboth runs anchor after 5@ana" Alice" 7@ana .. 12@anafirst ID 7@ana" Charlie" 7@ben .. 14@benfirst ID 7@ben (ben > ana wins the tie)Merged order: H(tombstone) e l l o [ Charlie] [ Alice] ! on every replicaRun stays together: 8@ben..14@ben > 7@ana, so they are skipped past as a blockTombstone: a deleted element keeps its ID, because a concurrent insert may still say "after 1@ana".Garbage collection: drop it once the delete is causally stable (every replica has delivered it).Logoot, LSEQ and Treedoc instead give each element a dense position ID; concurrent runs can interleave.

RGA, from Shapiro et al.'s survey: an element's identifier is "a timestamp, assumed unique and ordered consistently with causality", and "two downstream inserts at the same position are ordered in opposite order of their timestamps". The integration rule in the Go snippet is three lines: start right after the anchor; skip every element whose ID is greater than the new one; insert there. Elements inserted later after a skipped element have even greater IDs (Lamport), so whole runs are skipped together.

text
     Ana                                         Ben
1    "Hello!"  ids 1@ana..6@ana                  same (synced)
2    types " Alice" after 5@ana: 7@ana..12@ana   types " Charlie" after 5@ana: 7@ben..14@ben
3    receives Ben's ops (in reverse order: buffered by the causal inbox, applied in order)
4    7@ben > 7@ana (tie on counter, "ben" > "ana") -> Charlie's run goes first
5    "Hello Charlie Alice!"                       "Hello Charlie Alice!"   (lab output)

Real scenario: collaborative code and note editors; ordered to-do lists and kanban columns; playlist ordering; the paragraph list of a document; chat message ordering in offline-first apps.

What provides it:

Library / productSequence algorithm (from its own docs)
Yjs"a modified version" of YATA; "At its heart, Yjs is a list CRDT."
AutomergeList elements have IDs and "operations on the list reference these IDs"; "inserting a run of elements will maintain the insertion order of the replica which generated it"
Redis Active-Active listsConcurrent inserts resolved "arbitrarily but applies the resolution consistently across all Active-Active database instances"
Peritext prototype"uses RGA / Causal Trees as its basis"
FigmaFractional indexing for child order (position "as a fraction between 0 and 1"), server-ordered

Fix / how to use it: do not write your own text CRDT for a product; use Yjs or Automerge, and use the snippet's RGA only to understand and test the idea. If you must order a few items (kanban cards), fractional indexing with a server or an RGA over item IDs is enough.

Text CRDTs in practice: Yjs (YATA), Automerge, Fugue and Peritext Important ​

In plain words: the libraries you would actually ship are sequence CRDTs with heavy engineering on top: runs of characters stored as one item, compact binary encodings, sync protocols, editor bindings, and rules for rich-text formatting.

Common misunderstanding: "Any converging text CRDT gives a good editing experience." Convergence is the floor. Text can still interleave character by character (Intent), formatting can split ("bold" applied by one user lost on text inserted by another), and the document can grow without bound.

Definition and what each one does:

LibraryCore ideaData typesMetadata strategyNotes from its docs
Yjs (JavaScript; ports such as Yrs in Rust)YATA-based list CRDT; maps and text are lists underneathY.Text, Y.Array, Y.Map, XML typesRuns merged into one item; deleted content replaced by a small GC struct; doc.gc = false keeps history"Yjs is network agnostic (p2p!)"; insertions are op-based, deletions "a simpler state based CRDT"
Automerge (Rust core, WebAssembly for JavaScript, C and Swift bindings)JSON CRDT: nested maps, lists, text, countersMap, List, Text, Counter, rich text marks"a compact compression format"; full history kept (like git)"Automerge aims to be PostgreSQL for your local-first app."
Fugue / FugueMax (research, 2023)Tree of left and right children, traversed in orderLists, textTombstones"The problem has gone unnoticed for decades, and it affects both CRDTs and Operational Transformation."
Peritext (Ink & Switch, CSCW 2022)Formatting spans anchored before or after characters, on top of a plain-text CRDTRich text: bold, italic, links, commentsFormat ops kept alongside text opsAutomerge's rich-text marks follow Peritext's merge rules
text
     Peritext essay, base text "The fox jumped."
1    Example 2: Alice bolds the whole sentence; Bob concurrently inserts "brown " before "fox"
2    Peritext rule: a format span covers any text between its anchors, even text it never saw
3    merged: "The brown fox jumped." entirely bold on both replicas
4    Example 3 in Markdown over a plain-text CRDT: Alice "**The fox** jumped.", Bob "The **fox jumped.**"
5    merged characters: "**The **fox** jumped.**": the asterisks interleave and "fox" renders NOT bold
6    Peritext stores spans as separate operations, so both bolds survive: whole sentence bold

Real scenario: note apps and wikis that work offline; local-first design tools; code editors with peer-to-peer pairing; Jupyter-like notebooks; the Apple Notes app, which crdt.tech reports "appears to be built upon CRDTs" based on header files in the operating system (secondary source, not Apple's documentation).

What provides it: Yjs bindings for ProseMirror, Tiptap, Quill, CodeMirror, Monaco and others (listed in the Yjs README); Automerge with automerge-repo for storage and networking; Peritext's prototype in TypeScript.

Fix / how to use it: pick Yjs when you need editor bindings and a mature server ecosystem (y-websocket and similar providers); pick Automerge when the document is application state (JSON) with history; keep a server anyway for persistence, auth and backups (Real-Time Communication covers the WebSocket side).

The JSON CRDT (Kleppmann and Beresford) Important ​

In plain words: a whole JSON document (nested objects, arrays, strings) as one CRDT: objects are maps of CRDTs, arrays are RGA-like lists, primitive values are multi-value registers. Any edit anywhere in the tree merges with any concurrent edit.

Common misunderstanding: "A JSON CRDT preserves my schema." It preserves operations. Kleppmann and Beresford's own example: one replica deletes a to-do item while another marks it done, and the merge resurrects the item without a title. If two replicas assign different types to the same key (a map and a list), both are kept under type-tagged namespaces.

Definition: the 2016 paper (IEEE TPDS 2017) presents "an algorithm and formal semantics for a JSON data structure that automatically resolves concurrent modifications such that no updates are lost, and such that all replicas converge towards the same state". Merging is client-side and does not depend on network ordering guarantees, "making it suitable for deployment on mobile devices with poor network connectivity, in peer-to-peer networks, and in messaging systems with end-to-end encryption". Lists: "Deleted elements are never removed from the linked list structure, but only marked as deleted (they become so-called tombstones)". Ink & Switch's local-first essay states that Automerge "is based on our earlier research on JSON CRDTs".

text
     Replica p                                     Replica q
1    doc = {todo: [{title:"buy milk", done:false}]}
2    delete todo[0]                                todo[0].done = true
3    ---------------------------- merge ----------------------------
4    todo = [{done:true}]  on both: no update lost, but the object lost its title
5    application layer: validate after merge (no title -> hide / treat as deleted)

Real scenario: app state of a local-first app (a kanban board, a trip planner); per-user settings documents; forms filled offline by field workers; game save state across devices.

What provides it: Automerge (JSON-like documents); Yjs Y.Map and Y.Array nesting; Riak maps for a server-side approximation.

Fix / how to use it: keep invariants that matter (an item has a title) in the application: validate after merge, or model existence with a register instead of list deletion; keep documents small enough to load on a phone.

Metadata, tombstones, garbage collection and causal stability Must-know ​

In plain words: CRDTs pay for coordination-freedom in memory: unique tags, per-replica vectors, and deleted elements that cannot be forgotten yet. Garbage collection is possible only for information that no future message can still need, and knowing that requires knowing what every replica has seen.

Common misunderstanding: "Tombstones can be deleted after a timeout, like in Cassandra." A timeout is a guess. If a replica that was offline longer than the timeout comes back with an operation that references the tombstone, a sequence CRDT cannot place it and a set may resurrect data. Time-based purging is only safe if you also refuse replicas older than the purge horizon (Cassandra's gc_grace_seconds plus repair is exactly that bargain, see Merkle Trees & Tombstones).

Definition: Shapiro et al.'s comprehensive study: CRDTs "tend to become inefficient over time, as tombstones accumulate and internal data structures become unbalanced". An update f is causally stable at a replica when every update concurrent with f has been delivered there: "Once f is stable, i.e., all operations concurrent with f have been delivered, r(f) serves no useful purpose." With causal delivery and known membership, a replica keeps the last version vector received from every other replica; the entry-wise minimum is the stability frontier, and anything below it can be collected (Wuu and Bernstein's algorithm). Liveness needs every replica to report: "it is live only if no process is crashed", which is acceptable "since the liveness of garbage collection does not impact the correctness of the main algorithm."

text
     Replica     delivered vector               min over all = stable frontier
1    ana         {ana:13, ben:8}
2    ben         {ana:13, ben:8}                {ana:13, ben:8}
3    delete op ana:13 is covered by the frontier -> tombstone can be dropped on both
4    carol joins with {ana:9, ben:8}            frontier drops to {ana:9, ben:8}: GC stalls
5    carol offline for a month                  frontier frozen: tombstones pile up (evict carol?)

Real scenario: Redis Active-Active: a deleted key "remains in memory as a tombstone until the garbage collector can safely remove it", and the GC removes it "when all instances in the Active-Active database have observed the deletion operation" (monitor with INFO crdt: crdt_gc_pending, crdt_gc_collected, crdt_gc_gvc_min); Akka Distributed Data: deleted top-level keys stay in gossip ("growing memory usage until an ActorSystem runs out of memory"), so use expiry or a fixed set of keys, and pruning of removed nodes' slots; Yjs cannot drop ordering tombstones but discards deleted content; Figma deletes object data on the server and keeps it in the deleting client's undo buffer.

What provides it:

SystemWhat growsHow it is collected
Redis Active-ActiveTombstones for deleted keys and elements; vector clocks per instanceBackground GC once all instances observed the delete (global minimum vector clock)
Akka Distributed DataDeleted keys; per-node slots in counters and setsExpiry (no tombstone left); pruning of removed nodes with markers (pruning-marker-time-to-live)
Riak KVCausal context per objectServer-side; the client sends back the context it read
YjsItem structs (IDs), delete setContent GC; runs merged; structs kept for ordering
AutomergeFull change historyCompression; history is a feature
The Go snippetRGA tombstonesCollect(stable) once the delete is covered by crdt.Min(...) of all delivered vectors

Fix / how to use it: budget metadata per replica, not per user (devices come and go: cap them, retire them explicitly); compute stability from vectors each replica reports (the Laravel snippet stores every device's last state for that purpose); evict replicas that stay offline beyond a horizon and force them to resync from a snapshot.

Interleaving anomalies, convergence vs intent preservation Important ​

In plain words: all replicas agreeing on the same text is not the same as the text being what the users meant. Two people typing different words at the same spot should get both words, one after the other, not a mixture of their letters.

Common misunderstanding: "If the algorithm is proven convergent, the merged text is fine." Kleppmann, Gomes, Mulligan and Beresford (PaPoC 2019) show several published convergent algorithms where concurrent insertions "may be randomly interleaved on a character-by-character basis, resulting in an unreadable jumble of letters". The authors observed it in Logoot and LSEQ implementations.

Definition: intent preservation (a term from the OT literature) asks that each user's operation has its intended effect in the merged result. The interleaving anomaly: two concurrent runs at the same position end up interleaved. Dense-identifier CRDTs (Logoot, LSEQ, Treedoc) suffer because each user spreads identifiers over the same interval. RGA does not interleave runs typed left to right, but has a "lesser interleaving anomaly" when a user moves the cursor back and types again. Fugue defines maximal non-interleaving and proves FugueMax satisfies it.

text
     Start: "Hello!"     Ana inserts " Alice" and Ben inserts " Charlie" between "Hello" and "!"
1    acceptable:         "Hello Alice Charlie!"  or  "Hello Charlie Alice!"
2    Logoot / LSEQ:      e.g. "Hello Al Cihaarlice!" (illustrative: IDs from one interval interleave)
3    RGA, forward typing: never interleaves (test TestRGADoesNotInterleaveForwardTyping)
4    RGA, backward edit: Ana types " reader", moves back, types " dear"; Ben types " Alice"
5                        " Alice" can land between " dear" and " reader": the lesser anomaly

Real scenario: two people filling the same table cell; offline edits of the same paragraph merged hours later (worse than real time, where users see each other and back off); spreadsheets and to-do lists where items are inserted "at the top" (backward insertion is common there, says the Fugue paper).

What provides it:

AlgorithmForward interleavingBackward interleaving (one replica)Backward (multi-replica)
Logoot, LSEQ, TreedocInterleavesInterleavesInterleaves
RGADoes not (proved)InterleavesInterleaves
YjsDoes not (proof in progress per the paper)Does notInterleaves
Fugue, FugueMaxDoes not (proved)Does not (proved)Does not (proved)

(Summary of the Fugue paper's Table 1.)

Fix / how to use it: prefer libraries whose list algorithm is documented and tested against interleaving; for structured data, avoid character-level merging (merge whole cells, items or paragraphs as registers); show presence (cursors) in real time so humans avoid typing at the same spot.

CRDTs vs operational transformation Important ​

In plain words: OT keeps index-based operations ("insert at 5") and, when it receives a concurrent operation, transforms it against what it already applied ("your insert at 5 becomes insert at 8 because I inserted 3 characters before it"). CRDTs avoid indexes altogether by naming elements with unique IDs.

Common misunderstanding: "OT is obsolete, CRDTs replaced it." Google Docs is built on OT with a central server, and it works. Google's 2010 posts: "Google Docs uses an algorithm called operational transformation to merge edits in real time", with a server that keeps the revision log and clients that transform their pending changes. OT's weakness is decentralised use: Shapiro et al. note that OT algorithms "for a decentralised architecture have been proposed; Oster et al. show that most of them are incorrect".

Definition and comparison:

AspectOperational transformationCRDT
Operation addressesIndexes, transformed against concurrent opsUnique element IDs, no transformation
Typical topologyCentral server orders operations (Jupiter, Google Docs)Any: peer-to-peer, server relay, offline sync
Correctness burdenTransformation functions for every pair of operation typesCommutativity / semilattice per type
Offline for daysPainful: long transformation chainsNatural: merge when back
MetadataSmall document, server logIDs per element, tombstones, vectors
InterleavingAlso affected (Fugue table: several OT algorithms)Depends on algorithm
ProductsGoogle Docs, many editorsYjs, Automerge, Redis Active-Active, Riak
text
     OT with a server (Google Docs style)        CRDT (Yjs style)
1    client sends {insert 'Hello' @0, rev 4}     client sends {item 7@ana after 5@ana}
2    server transforms against revs 5, 6         any peer applies directly (IDs, not indexes)
3    server appends rev 7, broadcasts            no central order required
4    other clients transform their pending ops   other clients integrate by ID rule

Real scenario: a SaaS editor with an always-online server (OT or a CRDT both fine; OT is proven at Google scale); an offline-first notes app (CRDT); a design tool with a server of record (Figma: CRDT-inspired, server-ordered, "we can simplify our system by removing this extra overhead").

What provides it: OT: Google Docs, ShareDB-style servers; CRDT: Yjs, Automerge; hybrid: Figma (server is "the central authority").

Fix / how to use it: if a server is always in the loop and you only need real-time collaboration, a server-ordered approach (OT or Figma-style LWW per property) is simpler; if devices must edit offline or peer-to-peer, use a CRDT library.

Limitations: global invariants, size, Byzantine peers Must-know ​

In plain words: a CRDT can only promise things each replica can check alone. "There must never be more than 100 tickets sold" needs to know what other replicas did, so no CRDT can guarantee it without talking to them.

Common misunderstanding: "Just refuse the decrement when the local value is 0." Shapiro et al. answer precisely: "it is not sufficient for each replica to refrain from decrementing when its local value is 0: for instance, two replicas at value 1 might still concurrently decrement, and the value converges to −1." The constraint "is a global invariant, which cannot be evaluated based on local information only."

Definition: three hard limits.

LimitWhyWhat to do
Global invariants (non-negative balance, uniqueness, capacity, referential integrity across objects)Need knowledge of concurrent updates elsewhereSynchronise: "Sadly, the remaining alternative is to synchronise" (consensus, single owner per key), or escrow: pre-allocate rights to decrement per replica (bounded counter), refill by coordination
Size and performanceTags, vectors and tombstones grow; Akka: "It is not intended for Big Data" and "The number of top level entries should not exceed 100000"Delta sync, GC by stability, compaction, sharding documents
Byzantine replicasThe 2011 model assumes "non-byzantine processes"; Kleppmann (PaPoC 2022): "most existing CRDT algorithms cannot guarantee consistency in the presence of such faults"Hash-linked, signed operations (Kleppmann's BFT CRDT scheme), or a trusted server that validates
Semantics users dislikeAdd-wins resurrects, LWW loses, merges create half-objectsChoose per field; validate after merge; show conflicts
Security and authorisationAny replica can merge anything it receivesValidate states at the server; authorise per document; never trust client clocks
text
     Escrow for "seats <= 100" across 2 regions (bounded counter idea)
1    coordinator grants EU 60 rights, US 40 rights        (one coordinated step)
2    EU sells 60 locally, no round trip; 61st -> needs more rights
3    EU asks US for 10 of its unused rights               (coordination only at the edge)
4    total sold <= 60 + 40 = 100 holds without per-sale consensus

Real scenario: ticket and seat inventory; wallet balances; unique usernames and slugs; quotas that must hard-stop; foreign keys across objects ("comment refers to a post that a concurrent delete removed").

What provides it: Shapiro et al. name escrow transactions; AntidoteDB's datatypes include counters with richer semantics (fat counter, integer with set); for hard invariants use Distributed Locking, Leader Election or a linearizable database (Distributed SQL, Consensus & 2PC).

Fix / how to use it: split the entity: the invariant-carrying field goes through coordination (or escrow), the rest (likes, tags, notes, presence) is a CRDT. That hybrid is the normal production design.

Where CRDTs run in production Good to know ​

In plain words: you rarely implement CRDTs yourself; databases and libraries ship them, each with a slightly different menu and conflict rule.

Common misunderstanding: "Product X is CRDT-based, so every operation in it is conflict-free." Each product documents per-type semantics, and some types fall back to LWW (Redis Active-Active strings, Riak registers, Akka LWWRegister).

Definition: the table below is what each product's own documentation says.

ProductTypes offeredConflict rulesReplicationSource
Riak KV data typesCounters, sets, maps, registers and flags (in maps), HyperLogLogsSets OR-style with causal context; registers LWW; flags enable/disableOp API to clients, state-based merge (riak_dt)Riak docs "Data Types"
Redis Enterprise Active-Active (formerly CRDB)Strings (LWW), string counters, sets, hashes, sorted sets, lists (and other types listed in the docs)OR-Set "add wins"; counters accumulate; strings "last write wins" by OS time; EXPIRE: longest TTL winsMulti-primary, syncer, vector clocks; optional causal consistencyRedis docs "Active-Active geo-distributed Redis"
Akka Distributed DataGCounter, PNCounter, GSet, ORSet, ORMap, ORMultiMap, LWWMap, PNCounterMap, LWWRegister, FlagPer type; deltas for many typesGossip + WriteLocal/WriteMajority/WriteAll, ReadLocal/ReadMajority/ReadAllAkka docs "Distributed Data"
SoundCloud RoshiLWW-element-set of timestamped eventsTimestamp decidesStateless Go layer over several Redis clusters ("farm")GitHub README (archived)
AntidoteDBLWW and MV registers, counters, flags (EW/DW), sets (G, AW, RW), maps (G, AW, RR)Chosen per typeGeo-replicated, highly available transactionsantidotedb.eu, AntidoteDB docs
Figma multiplayerPer-property LWW, LWW-set-like object existence, fractional indexingServer defines orderClient/server over WebSockets, one process per documentFigma engineering blog (2019)
Yjs, AutomergeText, lists, maps, counters, rich textLibrary-defined, documented merge rulesAny transport (WebSocket, WebRTC, files)Library docs and READMEs
text
     Redis Active-Active, two clusters, set "cart"
1    EU: SADD cart book                    sync -> US: cart = {book}
2    EU: SREM cart book                    US (concurrently): SADD cart book
3    sync both ways
4    US's add was not observed by EU's remove -> cart = {book} on both ("add wins")

Real scenario: an active-active session store or leaderboard across regions on Redis Enterprise; cluster-wide feature state in an Akka application; activity streams at SoundCloud; a multiplayer design canvas; an offline-capable notes app.

What provides it: see the table; for Redis, also INFO crdt for vector clocks and GC statistics.

Fix / how to use it: read the per-type conflict table of the product before modelling; avoid the LWW types for data where concurrent edits are expected.

Mechanics ​

Merge rules side by side ​

TypeUpdate (at replica r)Merge(a, b)Query
G-CounterP[r] += nP[i] = max(a.P[i], b.P[i]) for all isum(P)
PN-CounterP[r] += n or N[r] += nmerge P, merge Nsum(P) - sum(N)
LWW-Register(v, ts) = (new, max(now, ts+1))keep greater (ts, replica)v
MV-Registernew entry with vector = join of seen vectors, [r]++keep entries not dominated by the other sideall values
G-SetA += {e}A ∪ Be ∈ A
2P-Setadd: A += {e}; remove: R += {e} if e presentunion bothe ∈ A and e ∉ R
LWW-Element-SetA += {(e, ts)} / R += {(e, ts)}union bothlatest add newer than latest remove
OR-Set (dots)add: ctx[r]++, E[e] = {(r, ctx[r])}; remove: E[e] = {}keep dot if in both, or in one and unseen by the other's ctx; ctx = joinE[e] ≠ {}
RGAinsert: id = (max counter + 1, r) after anchor; delete: mark tombstoneop-based: apply in causal ordervisible elements in list order

Metadata size arithmetic ​

Back-of-envelope estimates (labelled as such): R = replicas that ever wrote, E = live elements, D = deleted elements not yet collected.

TypeMetadataExampleEstimate
G-/PN-Counter1-2 integers per writing replica5 regions10 integers per counter, under 100 bytes
PN-Counter per deviceSame, but R = devicesLike counter written by 1 million phonesMegabytes per counter: wrong slot choice
OR-Set with causal contextOne dot per element + one vector entry per replica1,000 items, 20 devicesabout 1,000 dots + 20 entries
Naive OR-Set with tombstonesEvery removed tag kept1,000 items churned 100 timesabout 100,000 tags without GC
RGA / Yjs textOne ID per character (Yjs: per run) + tombstones100 KB document, heavy editingOften several times the visible text without GC; Yjs merges runs
MV-RegisterVector per sibling3 devices concurrent3 values + 3 vectors of 3

Lab measurement: a G-Counter with 100 slots is 907 bytes as JSON; its delta after one increment is 16 bytes.

Knobs per product ​

ProductKnobEffect
Riak KVriak-admin bucket-type create maps '{"props":{"datatype":"map"}}' (also set, counter, hll)Declares a bucket type holding a data type
Riak KVCausal context returned on fetch, sent back on updateRequired for correct removes
Redis Active-ActiveCausal consistency option on the databasePreserves operation order across replicas (extra cost)
Redis Active-ActiveINFO crdt fields crdt_clock, crdt_ovc, crdt_gc_pending, crdt_gc_gvc_minVector clocks and GC progress
Akka Distributed DataWriteLocal, WriteMajority(minCap), WriteAll, ReadLocal, ReadMajority(minCap), ReadAllPer-call replication level
Akka Distributed Dataakka.cluster.distributed-data.delta-crdt.enabledDelta propagation on or off
Akka Distributed Dataakka.cluster.distributed-data.notify-subscribers-interval, durable keys, pruning-marker-time-to-liveChange notifications, persistence, pruning
Yjsdoc.gc (default true)Discard deleted content; false keeps it for version snapshots
YjsY.encodeStateAsUpdate(doc, stateVector)Delta sync against a remote state vector
AutomergeAutomerge.Counter, getConflicts(doc, key)Counter type; multi-value view of LWW properties

Errors and signals you will actually see ​

WhereMessage / signalMeaning
Akka Distributed DataReplicator.UpdateTimeoutNot confirmed by the requested consistency level in time; docs: it "does not mean that the update completely failed or was rolled back"
Akka Distributed DataReplicator.DataDeleted, Replicator.DeletedKey was deleted; "A deleted key cannot be reused again"
Akka Distributed DataGetFailure, NotFoundRead could not reach the level / key absent
Riak KVRemove without context"may fail (removing a field that is not present) or succeed and remove more than intended"
Redis Active-Activeexpired_keys larger than DBSIZEExpires are not always removed when a key becomes a tombstone (documented)
Redis Active-Activecounter beyond 59 bitsActive-Active "support 59-bit counters" to avoid overflow in concurrent operations
The Go snippetpanic: rga: anchor not delivered; causal delivery violatedAn insert was applied before its anchor: the delivery layer is broken
The Laravel snippetHTTP 422 {"errors":{"state":["A dot must be covered by the causal context."]}}Client sent a malformed CRDT state
The Laravel snippetHTTP 409 Document has a different CRDT type.Same doc_key used with two types

Go ​

Before ​

Two designs that work with one replica and lose data with two: a like count shipped as a number with last-writer-wins, and a cart synced by set union. The tests document the losses (5 likes become 2; a removed book comes back).

go
// Package before shows the two designs teams usually ship before they meet
// CRDTs. Both work perfectly with one replica and both lose data with two.
package before

import "time"

// LikeCounter replicates the like count as a plain number. Each region
// increments its local copy and ships the whole value to the other region,
// which keeps the copy with the newest wall-clock timestamp (last writer
// wins). Concurrent likes in two regions: one region's likes vanish.
type LikeCounter struct {
	Count int64
	At    time.Time
}

// Like is the local increment.
func (c *LikeCounter) Like(now time.Time) {
	c.Count++
	c.At = now
}

// Receive applies a copy from another region: newest timestamp wins.
func (c *LikeCounter) Receive(o LikeCounter) {
	if o.At.After(c.At) {
		*c = o
	}
}

// Cart replicates a shopping cart as a plain set. Remove deletes the item
// locally; sync is set union. Union cannot tell "removed here" from "never
// seen there", so removed items come back after a sync (the anomaly the
// Dynamo paper reports for Amazon's cart).
type Cart map[string]bool

// Add puts an item in the cart.
func (c Cart) Add(item string) { c[item] = true }

// Remove takes an item out locally.
func (c Cart) Remove(item string) { delete(c, item) }

// Receive merges another device's cart by union.
func (c Cart) Receive(o Cart) {
	for item := range o {
		c[item] = true
	}
}
go
package before

import (
	"testing"
	"time"
)

func TestLWWCounterLosesConcurrentLikes(t *testing.T) {
	t0 := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)
	eu, us := &LikeCounter{}, &LikeCounter{}
	for i := range 3 {
		eu.Like(t0.Add(time.Duration(i) * time.Millisecond))
	}
	for i := range 2 {
		us.Like(t0.Add(time.Duration(10+i) * time.Millisecond))
	}
	eu.Receive(*us)
	us.Receive(*eu)
	if eu.Count != 2 || us.Count != 2 {
		t.Fatalf("expected the documented loss (5 likes become 2), got %d and %d", eu.Count, us.Count)
	}
}

func TestUnionCartResurrectsRemovedItem(t *testing.T) {
	phone, laptop := Cart{}, Cart{}
	phone.Add("book")
	laptop.Receive(phone)
	phone.Remove("book")
	phone.Receive(laptop)
	if !phone["book"] {
		t.Fatal("expected the documented anomaly: the removed book is back")
	}
}

After: counters, registers and version vectors ​

VClock is the version vector used by the MV-Register, the OR-Set's causal context and causal delivery; Min computes the stability frontier.

go
// Package crdt implements the classic conflict-free replicated data types
// from Shapiro et al. (2011): G-Counter, PN-Counter, LWW-Register,
// MV-Register, G-Set, 2P-Set, an add-wins OR-Set with dots, and an RGA
// sequence. Everything is in memory and dependency-free so the merge rules
// stay visible.
package crdt

import (
	"maps"
	"slices"
)

// ReplicaID names a replica (a device, a region, a server).
type ReplicaID string

// Dot is one event: the n-th update made by a replica. Dots are the unique
// tags of an OR-Set and the per-origin sequence numbers of causal delivery.
type Dot struct {
	Replica ReplicaID `json:"r"`
	Counter uint64    `json:"c"`
}

// VClock is a version vector: for each replica, how many of its updates
// this state has seen.
type VClock map[ReplicaID]uint64

// Ordering is the result of comparing two version vectors.
type Ordering int

const (
	Equal Ordering = iota
	Before
	After
	Concurrent
)

func (o Ordering) String() string {
	return [...]string{"equal", "before", "after", "concurrent"}[o]
}

// Copy returns an independent copy.
func (v VClock) Copy() VClock {
	if v == nil {
		return VClock{}
	}
	return maps.Clone(v)
}

// Contains reports whether the dot is covered by this vector.
func (v VClock) Contains(d Dot) bool { return v[d.Replica] >= d.Counter }

// Merge sets v to the entry-wise maximum of v and o (the join).
func (v VClock) Merge(o VClock) {
	for r, n := range o {
		if n > v[r] {
			v[r] = n
		}
	}
}

// Compare tells whether v happened before, after, equal to or concurrently
// with o.
func (v VClock) Compare(o VClock) Ordering {
	less, greater := false, false
	for _, r := range replicas(v, o) {
		switch a, b := v[r], o[r]; {
		case a < b:
			less = true
		case a > b:
			greater = true
		}
	}
	switch {
	case less && greater:
		return Concurrent
	case less:
		return Before
	case greater:
		return After
	}
	return Equal
}

// Min returns the entry-wise minimum of the vectors: the updates every one
// of them has seen. With the clocks of all replicas it is the causal
// stability frontier used for garbage collection.
func Min(clocks ...VClock) VClock {
	out := VClock{}
	if len(clocks) == 0 {
		return out
	}
	for _, r := range replicas(clocks...) {
		m := clocks[0][r]
		for _, c := range clocks[1:] {
			m = min(m, c[r])
		}
		if m > 0 {
			out[r] = m
		}
	}
	return out
}

func replicas(vs ...VClock) []ReplicaID {
	seen := map[ReplicaID]struct{}{}
	for _, v := range vs {
		for r := range v {
			seen[r] = struct{}{}
		}
	}
	return slices.Sorted(maps.Keys(seen))
}

GCounter.Inc returns its delta-state; PNCounter pairs two G-Counters.

go
package crdt

import "maps"

// GCounter is a grow-only counter: one slot per replica, each replica only
// increments its own slot, merge takes the per-slot maximum and the value is
// the sum. Merge is commutative, associative and idempotent, so replicas
// can exchange whole states in any order, any number of times.
type GCounter struct {
	P map[ReplicaID]uint64 `json:"p"`
}

// NewGCounter returns an empty counter.
func NewGCounter() *GCounter { return &GCounter{P: map[ReplicaID]uint64{}} }

// Inc adds n to replica r's slot and returns the delta-state: a counter that
// holds only the changed slot. Shipping the delta instead of the full state
// is the delta-state CRDT optimisation (Almeida et al.); merging a delta is
// as safe as merging a full state.
func (g *GCounter) Inc(r ReplicaID, n uint64) *GCounter {
	g.P[r] += n
	return &GCounter{P: map[ReplicaID]uint64{r: g.P[r]}}
}

// Value is the sum of all slots.
func (g *GCounter) Value() uint64 {
	var sum uint64
	for _, n := range g.P {
		sum += n
	}
	return sum
}

// Merge joins o into g: per-replica maximum.
func (g *GCounter) Merge(o *GCounter) {
	for r, n := range o.P {
		if n > g.P[r] {
			g.P[r] = n
		}
	}
}

// Clone returns an independent copy.
func (g *GCounter) Clone() *GCounter { return &GCounter{P: maps.Clone(g.P)} }

// Equal compares states, treating a missing slot as zero.
func (g *GCounter) Equal(o *GCounter) bool {
	for r, n := range g.P {
		if o.P[r] != n {
			return false
		}
	}
	for r, n := range o.P {
		if g.P[r] != n {
			return false
		}
	}
	return true
}

// PNCounter supports decrements by pairing two G-Counters: P counts
// increments, N counts decrements, value = P - N. It can go below zero:
// "never negative" is a global invariant no CRDT can enforce locally.
type PNCounter struct {
	P *GCounter `json:"p"`
	N *GCounter `json:"n"`
}

// NewPNCounter returns an empty counter.
func NewPNCounter() *PNCounter { return &PNCounter{P: NewGCounter(), N: NewGCounter()} }

// Inc adds n at replica r.
func (c *PNCounter) Inc(r ReplicaID, n uint64) { c.P.Inc(r, n) }

// Dec subtracts n at replica r.
func (c *PNCounter) Dec(r ReplicaID, n uint64) { c.N.Inc(r, n) }

// Value is increments minus decrements.
func (c *PNCounter) Value() int64 { return int64(c.P.Value()) - int64(c.N.Value()) }

// Merge joins both halves.
func (c *PNCounter) Merge(o *PNCounter) {
	c.P.Merge(o.P)
	c.N.Merge(o.N)
}

// Clone returns an independent copy.
func (c *PNCounter) Clone() *PNCounter { return &PNCounter{P: c.P.Clone(), N: c.N.Clone()} }

// Equal compares both halves.
func (c *PNCounter) Equal(o *PNCounter) bool { return c.P.Equal(o.P) && c.N.Equal(o.N) }

LWWRegister.NextStamp implements max(now, seen + 1) so a causally later write always wins even with a slow clock; MVRegister keeps siblings.

go
package crdt

import "slices"

// Stamp orders writes to an LWW-Register: a time, with the replica ID as a
// deterministic tie-breaker so that every replica picks the same winner.
type Stamp struct {
	Time    int64     `json:"t"`
	Replica ReplicaID `json:"r"`
}

// Less is the total order on stamps.
func (s Stamp) Less(o Stamp) bool {
	if s.Time != o.Time {
		return s.Time < o.Time
	}
	return s.Replica < o.Replica
}

// LWWRegister keeps the value with the greatest stamp. Concurrent writes are
// not merged: all but one are silently discarded. With wall-clock stamps a
// replica whose clock runs behind loses even writes made after it saw the
// current value; NextStamp below closes that particular hole.
type LWWRegister[T any] struct {
	Value T     `json:"v"`
	Stamp Stamp `json:"s"`
}

// Set writes v if s is newer than the current stamp.
func (r *LWWRegister[T]) Set(v T, s Stamp) {
	if r.Stamp.Less(s) {
		r.Value, r.Stamp = v, s
	}
}

// NextStamp returns a stamp for a new write at replica id with wall clock
// now that is guaranteed to beat the value this replica has already seen:
// max(now, seen+1). This is the hybrid-logical-clock idea in one line: a
// write that causally follows another always wins over it, even under skew.
// Truly concurrent writes are still decided by time, and one is lost.
func (r *LWWRegister[T]) NextStamp(id ReplicaID, now int64) Stamp {
	return Stamp{Time: max(now, r.Stamp.Time+1), Replica: id}
}

// Merge keeps the newer of the two.
func (r *LWWRegister[T]) Merge(o *LWWRegister[T]) { r.Set(o.Value, o.Stamp) }

// MVRegister (multi-value register) keeps every concurrent write. Each value
// carries the version vector of its write; merge keeps the values that are
// not dominated by a value on the other side. The reader sees siblings and
// a later write that has seen them all replaces them (Dynamo's shopping
// cart, Riak siblings, Automerge's getConflicts).
type MVRegister[T comparable] struct {
	Entries []MVEntry[T] `json:"entries"`
}

// MVEntry is one sibling.
type MVEntry[T comparable] struct {
	Value T      `json:"v"`
	Clock VClock `json:"vv"`
}

// Set replaces every value this replica has seen with v.
func (m *MVRegister[T]) Set(id ReplicaID, v T) {
	clock := VClock{}
	for _, e := range m.Entries {
		clock.Merge(e.Clock)
	}
	clock[id]++
	m.Entries = []MVEntry[T]{{Value: v, Clock: clock}}
}

// Values returns the current siblings (one value unless writes were concurrent).
func (m *MVRegister[T]) Values() []T {
	out := make([]T, 0, len(m.Entries))
	for _, e := range m.Entries {
		out = append(out, e.Value)
	}
	return out
}

// Merge keeps the entries of either side that the other side does not dominate.
func (m *MVRegister[T]) Merge(o *MVRegister[T]) {
	var out []MVEntry[T]
	keep := func(e MVEntry[T], others []MVEntry[T]) {
		for _, x := range others {
			if e.Clock.Compare(x.Clock) == Before {
				return
			}
		}
		for _, x := range out {
			if x.Clock.Compare(e.Clock) == Equal {
				return
			}
		}
		out = append(out, MVEntry[T]{Value: e.Value, Clock: e.Clock.Copy()})
	}
	for _, e := range m.Entries {
		keep(e, o.Entries)
	}
	for _, e := range o.Entries {
		keep(e, m.Entries)
	}
	slices.SortFunc(out, func(a, b MVEntry[T]) int {
		return compareClocks(a.Clock, b.Clock)
	})
	m.Entries = out
}

// compareClocks is an arbitrary but deterministic total order used only to
// keep sibling lists in the same order on every replica.
func compareClocks(a, b VClock) int {
	for _, r := range replicas(a, b) {
		if a[r] != b[r] {
			if a[r] < b[r] {
				return -1
			}
			return 1
		}
	}
	return 0
}

After: sets, with an add-wins OR-Set built on dots ​

go
package crdt

import (
	"maps"
	"slices"
)

// GSet is a grow-only set: add and lookup, merge is union. It is the
// building block of most other set CRDTs.
type GSet map[string]struct{}

// Add inserts e.
func (s GSet) Add(e string) { s[e] = struct{}{} }

// Has reports membership.
func (s GSet) Has(e string) bool { _, ok := s[e]; return ok }

// Merge is set union.
func (s GSet) Merge(o GSet) {
	for e := range o {
		s[e] = struct{}{}
	}
}

// TwoPSet (two-phase set) is a G-Set of adds plus a G-Set of removes (the
// tombstone set). Remove wins over a concurrent add, and an element that
// was removed can never be added back.
type TwoPSet struct {
	Added   GSet `json:"a"`
	Removed GSet `json:"r"`
}

// NewTwoPSet returns an empty set.
func NewTwoPSet() *TwoPSet { return &TwoPSet{Added: GSet{}, Removed: GSet{}} }

// Add inserts e (a no-op forever after e was removed anywhere).
func (s *TwoPSet) Add(e string) { s.Added.Add(e) }

// Remove deletes e if this replica observes it.
func (s *TwoPSet) Remove(e string) {
	if s.Has(e) {
		s.Removed.Add(e)
	}
}

// Has is "added and never removed".
func (s *TwoPSet) Has(e string) bool { return s.Added.Has(e) && !s.Removed.Has(e) }

// Merge unions both halves.
func (s *TwoPSet) Merge(o *TwoPSet) {
	s.Added.Merge(o.Added)
	s.Removed.Merge(o.Removed)
}

// ORSet is an add-wins observed-remove set in the optimised form used by
// Riak (ORSWOT) and the delta-CRDT papers: every add gets a fresh dot, the
// causal context records every dot the replica has seen, and a remove just
// drops the element's dots. A dot that is in the context but not in the
// entries is a remembered removal, so no per-element tombstone is kept.
//
// Concurrent add and remove: the add's dot was not observed by the remove,
// so it survives the merge: add wins.
type ORSet struct {
	Entries map[string][]Dot `json:"entries"`
	Context VClock           `json:"ctx"`
}

// NewORSet returns an empty set.
func NewORSet() *ORSet { return &ORSet{Entries: map[string][]Dot{}, Context: VClock{}} }

// Add inserts e at replica r with a new dot and returns that dot.
func (s *ORSet) Add(r ReplicaID, e string) Dot {
	s.Context[r]++
	d := Dot{Replica: r, Counter: s.Context[r]}
	// The new dot supersedes every dot of e this replica has observed.
	s.Entries[e] = []Dot{d}
	return d
}

// Remove deletes the dots of e this replica has observed; it returns them
// (an op-based implementation would broadcast exactly this list).
func (s *ORSet) Remove(e string) []Dot {
	dots := s.Entries[e]
	delete(s.Entries, e)
	return dots
}

// Has reports membership.
func (s *ORSet) Has(e string) bool { return len(s.Entries[e]) > 0 }

// Elements returns the members in sorted order.
func (s *ORSet) Elements() []string { return slices.Sorted(maps.Keys(s.Entries)) }

// Merge joins o into s. A dot survives if both sides have it, or if one side
// has it and the other side has never seen it. A dot that one side has seen
// (it is in that side's context) but no longer holds was removed there.
func (s *ORSet) Merge(o *ORSet) {
	keys := map[string]struct{}{}
	for e := range s.Entries {
		keys[e] = struct{}{}
	}
	for e := range o.Entries {
		keys[e] = struct{}{}
	}
	out := map[string][]Dot{}
	for e := range keys {
		mine, theirs := s.Entries[e], o.Entries[e]
		var dots []Dot
		for _, d := range mine {
			if slices.Contains(theirs, d) || !o.Context.Contains(d) {
				dots = append(dots, d)
			}
		}
		for _, d := range theirs {
			if !slices.Contains(mine, d) && !s.Context.Contains(d) {
				dots = append(dots, d)
			}
		}
		if len(dots) > 0 {
			slices.SortFunc(dots, compareDots)
			out[e] = dots
		}
	}
	s.Entries = out
	s.Context.Merge(o.Context)
}

// Clone returns an independent copy.
func (s *ORSet) Clone() *ORSet {
	c := &ORSet{Entries: map[string][]Dot{}, Context: s.Context.Copy()}
	for e, dots := range s.Entries {
		c.Entries[e] = slices.Clone(dots)
	}
	return c
}

// Equal compares entries and context.
func (s *ORSet) Equal(o *ORSet) bool {
	if s.Context.Compare(o.Context) != Equal || len(s.Entries) != len(o.Entries) {
		return false
	}
	for e, dots := range s.Entries {
		if !slices.Equal(dots, o.Entries[e]) {
			return false
		}
	}
	return true
}

func compareDots(a, b Dot) int {
	if a.Replica != b.Replica {
		if a.Replica < b.Replica {
			return -1
		}
		return 1
	}
	switch {
	case a.Counter < b.Counter:
		return -1
	case a.Counter > b.Counter:
		return 1
	}
	return 0
}

Example: RGA with causal delivery and tombstone collection ​

CausalInbox is the delivery layer an op-based CRDT needs: buffer early operations, apply in causal order, drop duplicates.

go
package crdt

// Envelope is an operation as it travels between replicas: who made it, its
// per-origin sequence number, and the origin's version vector at that moment.
type Envelope[T any] struct {
	Origin ReplicaID `json:"origin"`
	Clock  VClock    `json:"clock"`
	Op     T         `json:"op"`
}

// Dot returns the operation's unique (origin, sequence) identity.
func (e Envelope[T]) Dot() Dot { return Dot{Replica: e.Origin, Counter: e.Clock[e.Origin]} }

// CausalInbox implements causal delivery on top of a network that may
// duplicate and reorder: an operation is applied only after every operation
// it depends on, and exactly once. Operation-based CRDTs (CmRDTs) need this;
// state-based CRDTs do not.
type CausalInbox[T any] struct {
	Delivered VClock
	pending   []Envelope[T]
}

// NewCausalInbox returns an inbox that has delivered nothing.
func NewCausalInbox[T any]() *CausalInbox[T] { return &CausalInbox[T]{Delivered: VClock{}} }

// Stamp records a local operation and returns the envelope to broadcast.
func (c *CausalInbox[T]) Stamp(self ReplicaID, op T) Envelope[T] {
	c.Delivered[self]++
	return Envelope[T]{Origin: self, Clock: c.Delivered.Copy(), Op: op}
}

// Receive buffers e and applies, in causal order, every buffered operation
// that has become deliverable. Duplicates are dropped. It returns how many
// operations were applied.
func (c *CausalInbox[T]) Receive(e Envelope[T], apply func(T)) int {
	c.pending = append(c.pending, e)
	applied := 0
	for progress := true; progress; {
		progress = false
		rest := c.pending[:0]
		for _, p := range c.pending {
			switch {
			case c.Delivered.Contains(p.Dot()):
				// duplicate: already applied
			case c.ready(p):
				apply(p.Op)
				c.Delivered[p.Origin] = p.Clock[p.Origin]
				applied++
				progress = true
			default:
				rest = append(rest, p)
			}
		}
		c.pending = rest
	}
	return applied
}

// Pending is the number of buffered operations still waiting for a dependency.
func (c *CausalInbox[T]) Pending() int { return len(c.pending) }

// ready: the next operation from its origin, and everything the origin had
// seen from others is already delivered here.
func (c *CausalInbox[T]) ready(e Envelope[T]) bool {
	for r, n := range e.Clock {
		if r == e.Origin {
			if n != c.Delivered[r]+1 {
				return false
			}
		} else if n > c.Delivered[r] {
			return false
		}
	}
	return true
}
go
package crdt

import "strings"

// ID identifies one inserted element: a Lamport timestamp made unique by the
// replica ID. IDs are totally ordered and respect causality.
type ID struct {
	Counter uint64    `json:"n"`
	Replica ReplicaID `json:"r"`
}

// Less is the total order on IDs.
func (a ID) Less(b ID) bool {
	if a.Counter != b.Counter {
		return a.Counter < b.Counter
	}
	return a.Replica < b.Replica
}

// IsZero is true for the head-of-sequence anchor.
func (a ID) IsZero() bool { return a.Counter == 0 && a.Replica == "" }

// RGAOp is an insert ("put Value right after After") or a delete ("hide
// Target"). Both name elements by ID, never by index, so they commute.
type RGAOp struct {
	Insert bool `json:"insert"`
	ID     ID   `json:"id"`
	After  ID   `json:"after"`
	Value  rune `json:"value"`
	Target ID   `json:"target"`
	// DeleteDot is the delete operation's (origin, sequence); filled in by
	// the replica so tombstones can be collected once the delete is stable.
	DeleteDot Dot `json:"delete_dot"`
}

type rgaNode struct {
	id        ID
	value     rune
	deleted   bool
	deleteDot Dot
}

// RGA is the Replicated Growable Array of Roh et al. (2011): a sequence kept
// as a list of elements in a total order. A new element is placed right
// after its anchor, skipping any elements with a greater ID that are already
// there (those were inserted concurrently and win the spot, or are their
// descendants). Deleted elements stay as tombstones, because a concurrent
// insert may still use them as an anchor.
//
// RGA is operation-based: it needs causal delivery (an insert must arrive
// after its anchor), which Replica provides with a CausalInbox.
type RGA struct {
	nodes []rgaNode
	clock uint64
}

// Text returns the visible elements.
func (r *RGA) Text() string {
	var b strings.Builder
	for _, n := range r.nodes {
		if !n.deleted {
			b.WriteRune(n.value)
		}
	}
	return b.String()
}

// Tombstones counts deleted elements still kept.
func (r *RGA) Tombstones() int {
	c := 0
	for _, n := range r.nodes {
		if n.deleted {
			c++
		}
	}
	return c
}

// prepareInsert turns "insert v at visible index pos" into an operation.
func (r *RGA) prepareInsert(self ReplicaID, pos int, v rune) RGAOp {
	var after ID
	if pos > 0 {
		after = r.nodes[r.physical(pos-1)].id
	}
	return RGAOp{Insert: true, ID: ID{Counter: r.clock + 1, Replica: self}, After: after, Value: v}
}

// prepareDelete turns "delete visible index pos" into an operation.
func (r *RGA) prepareDelete(pos int) RGAOp {
	return RGAOp{Target: r.nodes[r.physical(pos)].id}
}

// apply executes an operation; it is the effect-update of the CmRDT and is
// the same code for local and remote operations.
func (r *RGA) apply(op RGAOp) {
	if !op.Insert {
		for i := range r.nodes {
			if r.nodes[i].id == op.Target && !r.nodes[i].deleted {
				r.nodes[i].deleted, r.nodes[i].deleteDot = true, op.DeleteDot
			}
		}
		return
	}
	r.clock = max(r.clock, op.ID.Counter)
	i := 0
	if !op.After.IsZero() {
		i = r.index(op.After) + 1
	}
	for i < len(r.nodes) && op.ID.Less(r.nodes[i].id) {
		i++
	}
	r.nodes = append(r.nodes, rgaNode{})
	copy(r.nodes[i+1:], r.nodes[i:])
	r.nodes[i] = rgaNode{id: op.ID, value: op.Value}
}

// Collect removes tombstones whose delete is causally stable: every replica
// has delivered it, so no operation that could still use the element as an
// anchor can arrive. stable must be computed from clocks this replica has
// received over FIFO channels (or at quiescence, as in the tests).
func (r *RGA) Collect(stable VClock) int {
	kept := r.nodes[:0]
	removed := 0
	for _, n := range r.nodes {
		if n.deleted && stable.Contains(n.deleteDot) {
			removed++
			continue
		}
		kept = append(kept, n)
	}
	r.nodes = kept
	return removed
}

func (r *RGA) index(id ID) int {
	for i, n := range r.nodes {
		if n.id == id {
			return i
		}
	}
	panic("rga: anchor not delivered; causal delivery violated")
}

func (r *RGA) physical(visible int) int {
	for i, n := range r.nodes {
		if !n.deleted {
			if visible == 0 {
				return i
			}
			visible--
		}
	}
	panic("rga: index out of range")
}

// Replica is one copy of a shared text: the RGA plus causal delivery.
type Replica struct {
	ID    ReplicaID
	Doc   RGA
	Inbox *CausalInbox[RGAOp]
}

// NewReplica creates an empty replica.
func NewReplica(id ReplicaID) *Replica {
	return &Replica{ID: id, Inbox: NewCausalInbox[RGAOp]()}
}

// Insert types v at visible position pos and returns the envelope to broadcast.
func (p *Replica) Insert(pos int, v rune) Envelope[RGAOp] {
	op := p.Doc.prepareInsert(p.ID, pos, v)
	env := p.Inbox.Stamp(p.ID, op)
	p.Doc.apply(op)
	return env
}

// Delete removes the visible element at pos and returns the envelope.
func (p *Replica) Delete(pos int) Envelope[RGAOp] {
	op := p.Doc.prepareDelete(pos)
	env := p.Inbox.Stamp(p.ID, op)
	env.Op.DeleteDot = env.Dot()
	p.Doc.apply(env.Op)
	return env
}

// Receive delivers a remote envelope (any order, duplicates allowed).
func (p *Replica) Receive(e Envelope[RGAOp]) int { return p.Inbox.Receive(e, p.Doc.apply) }

// Text returns the visible text.
func (p *Replica) Text() string { return p.Doc.Text() }

Property-based tests ​

The semilattice laws are checked with testing/quick on random counter states; convergence is checked by replaying hundreds of random schedules (random edits, random delivery order, random duplicates) and comparing replicas at the end. Two targeted tests pin down the semantics: add-wins, and no interleaving for words typed left to right.

go
package crdt

import (
	"encoding/json"
	"math/rand/v2"
	"slices"
	"testing"
	"testing/quick"
)

var ids = []ReplicaID{"a", "b", "c"}

// randomCounter builds a PN-Counter from fuzz input.
func randomCounter(ops []uint8) *PNCounter {
	c := NewPNCounter()
	for _, o := range ops {
		r := ids[int(o)%len(ids)]
		if o&0x80 == 0 {
			c.Inc(r, uint64(o%7)+1)
		} else {
			c.Dec(r, uint64(o%3)+1)
		}
	}
	return c
}

func merged(a, b *PNCounter) *PNCounter { x := a.Clone(); x.Merge(b); return x }

// The three laws that make a state-based CRDT (CvRDT) converge.
func TestPNCounterMergeIsASemilatticeJoin(t *testing.T) {
	commutative := func(x, y []uint8) bool {
		a, b := randomCounter(x), randomCounter(y)
		return merged(a, b).Equal(merged(b, a))
	}
	associative := func(x, y, z []uint8) bool {
		a, b, c := randomCounter(x), randomCounter(y), randomCounter(z)
		return merged(merged(a, b), c).Equal(merged(a, merged(b, c)))
	}
	idempotent := func(x []uint8) bool {
		a := randomCounter(x)
		return merged(a, a).Equal(a)
	}
	for name, f := range map[string]any{"commutative": commutative, "associative": associative, "idempotent": idempotent} {
		if err := quick.Check(f, nil); err != nil {
			t.Errorf("%s: %v", name, err)
		}
	}
}

func TestCountersConvergeUnderAnyGossipOrder(t *testing.T) {
	for seed := range uint64(300) {
		rng := rand.New(rand.NewPCG(seed, 1))
		reps := []*PNCounter{NewPNCounter(), NewPNCounter(), NewPNCounter()}
		var want int64
		for range 200 {
			i := rng.IntN(3)
			switch rng.IntN(3) {
			case 0:
				reps[i].Inc(ids[i], 1)
				want++
			case 1:
				reps[i].Dec(ids[i], 1)
				want--
			default: // gossip a full state, possibly a stale or duplicate one
				reps[i].Merge(reps[rng.IntN(3)].Clone())
			}
		}
		for _, a := range reps {
			for _, b := range reps {
				a.Merge(b)
			}
		}
		for i, r := range reps {
			if r.Value() != want {
				t.Fatalf("seed %d replica %d: value %d, want %d", seed, i, r.Value(), want)
			}
		}
	}
}

func TestGCounterDeltaIsSmallAndSafe(t *testing.T) {
	full := NewGCounter()
	for i := range 100 {
		full.Inc(ReplicaID(rune('A'+i%26))+ReplicaID(rune('a'+i/26)), 3)
	}
	remote := full.Clone()
	delta := full.Inc("Aa", 1)
	remote.Merge(delta)
	remote.Merge(delta) // duplicate delivery is harmless
	if !remote.Equal(full) {
		t.Fatal("delta merge did not reach the full state")
	}
	d, _ := json.Marshal(delta)
	f, _ := json.Marshal(full)
	if len(d)*20 > len(f) {
		t.Fatalf("delta %d bytes is not much smaller than full state %d bytes", len(d), len(f))
	}
}

func TestLWWRegisterLosesConcurrentWriteAndClockSkewHurts(t *testing.T) {
	a, b := &LWWRegister[string]{}, &LWWRegister[string]{}
	a.Set("blue", Stamp{Time: 1000, Replica: "a"})
	b.Merge(a)
	// b's clock is 300 ms behind; its user edits after seeing "blue".
	b.Set("green", Stamp{Time: 800, Replica: "b"})
	if b.Value != "blue" {
		t.Fatalf("skewed write should lose, got %q", b.Value)
	}
	// With max(now, seen+1) the causally later write wins.
	b.Set("green", b.NextStamp("b", 800))
	a.Merge(b)
	if a.Value != "green" {
		t.Fatalf("causal stamp should win, got %q", a.Value)
	}
}

func TestMVRegisterKeepsConcurrentValues(t *testing.T) {
	a, b := &MVRegister[string]{}, &MVRegister[string]{}
	a.Set("a", "Draft")
	b.Merge(a)
	a.Set("a", "Final (Ana)")
	b.Set("b", "Final (Ben)")
	a.Merge(b)
	b.Merge(a)
	if got := a.Values(); len(got) != 2 || !slices.Equal(got, b.Values()) {
		t.Fatalf("want two equal sibling lists, got %v and %v", got, b.Values())
	}
	a.Set("a", "Final")
	b.Merge(a)
	if got := b.Values(); !slices.Equal(got, []string{"Final"}) {
		t.Fatalf("a write that saw both siblings should replace them, got %v", got)
	}
}

func TestTwoPSetRemoveWinsAndIsForever(t *testing.T) {
	a, b := NewTwoPSet(), NewTwoPSet()
	a.Add("milk")
	b.Merge(a)
	a.Remove("milk")
	b.Add("milk") // concurrent re-add
	a.Merge(b)
	b.Merge(a)
	if a.Has("milk") || b.Has("milk") {
		t.Fatal("2P-Set: remove must win")
	}
	a.Add("milk")
	if a.Has("milk") {
		t.Fatal("2P-Set: a removed element cannot come back")
	}
}

func TestORSetAddWins(t *testing.T) {
	a, b := NewORSet(), NewORSet()
	a.Add("a", "milk")
	b.Merge(a)
	a.Remove("milk")   // Ana removes the milk she saw
	b.Add("b", "milk") // Ben adds milk again, concurrently
	a.Merge(b)
	b.Merge(a)
	if !a.Has("milk") || !b.Has("milk") {
		t.Fatal("concurrent add must win over remove")
	}
	b.Remove("milk") // a remove that has observed every add
	a.Merge(b)
	if a.Has("milk") {
		t.Fatal("observed remove must stick")
	}
	a.Add("a", "milk") // unlike 2P-Set, re-adding works
	if !a.Has("milk") {
		t.Fatal("re-add after remove must work")
	}
}

func TestORSetConvergesAndIsASemilattice(t *testing.T) {
	elems := []string{"milk", "eggs", "bread"}
	for seed := range uint64(300) {
		rng := rand.New(rand.NewPCG(seed, 2))
		reps := []*ORSet{NewORSet(), NewORSet(), NewORSet()}
		for range 150 {
			i := rng.IntN(3)
			switch rng.IntN(3) {
			case 0:
				reps[i].Add(ids[i], elems[rng.IntN(3)])
			case 1:
				reps[i].Remove(elems[rng.IntN(3)])
			default:
				reps[i].Merge(reps[rng.IntN(3)].Clone())
			}
		}
		x, y, z := reps[0].Clone(), reps[1].Clone(), reps[2].Clone()
		ab, ba := x.Clone(), y.Clone()
		ab.Merge(y)
		ba.Merge(x)
		if !ab.Equal(ba) {
			t.Fatalf("seed %d: merge not commutative", seed)
		}
		left, right := ab.Clone(), y.Clone()
		left.Merge(z)
		right.Merge(z)
		right2 := x.Clone()
		right2.Merge(right)
		if !left.Equal(right2) {
			t.Fatalf("seed %d: merge not associative", seed)
		}
		again := left.Clone()
		again.Merge(left)
		if !again.Equal(left) {
			t.Fatalf("seed %d: merge not idempotent", seed)
		}
	}
}

func TestCausalInboxBuffersAndDeduplicates(t *testing.T) {
	src := NewCausalInbox[string]()
	e1 := src.Stamp("a", "first")
	e2 := src.Stamp("a", "second")
	dst := NewCausalInbox[string]()
	var got []string
	apply := func(s string) { got = append(got, s) }
	dst.Receive(e2, apply) // arrives early: buffered
	if len(got) != 0 || dst.Pending() != 1 {
		t.Fatalf("e2 must wait for e1, got %v", got)
	}
	dst.Receive(e1, apply)
	dst.Receive(e1, apply) // duplicate
	if !slices.Equal(got, []string{"first", "second"}) {
		t.Fatalf("got %v", got)
	}
}
go
package crdt

import (
	"math/rand/v2"
	"testing"
)

// network delivers envelopes to every other replica in random order, with
// random duplicates; the causal inbox restores what the RGA needs.
type network struct {
	reps  []*Replica
	queue [][]Envelope[RGAOp] // per destination
	rng   *rand.Rand
}

func newNetwork(rng *rand.Rand, n int) *network {
	nw := &network{rng: rng, queue: make([][]Envelope[RGAOp], n)}
	for i := range n {
		nw.reps = append(nw.reps, NewReplica(ReplicaID(rune('a'+i))))
	}
	return nw
}

func (n *network) broadcast(from int, e Envelope[RGAOp]) {
	for to := range n.reps {
		if to != from {
			n.queue[to] = append(n.queue[to], e)
		}
	}
}

func (n *network) deliverOne(to int) {
	q := n.queue[to]
	if len(q) == 0 {
		return
	}
	k := n.rng.IntN(len(q))
	e := q[k]
	if n.rng.IntN(10) != 0 { // 1 in 10 messages is delivered twice
		n.queue[to] = append(q[:k], q[k+1:]...)
	}
	n.reps[to].Receive(e)
}

func (n *network) drain() {
	for to := range n.reps {
		for len(n.queue[to]) > 0 {
			n.deliverOne(to)
		}
	}
}

// Property: whatever the interleaving of local edits and message delivery,
// once every operation is delivered everywhere, all replicas show the same text.
func TestRGAConvergesForRandomOperationOrders(t *testing.T) {
	for seed := range uint64(500) {
		rng := rand.New(rand.NewPCG(seed, 3))
		nw := newNetwork(rng, 3)
		for range 120 {
			i := rng.IntN(3)
			r := nw.reps[i]
			switch n := len([]rune(r.Text())); {
			case rng.IntN(4) == 0:
				nw.deliverOne(i)
			case n > 0 && rng.IntN(3) == 0:
				nw.broadcast(i, r.Delete(rng.IntN(n)))
			default:
				nw.broadcast(i, r.Insert(rng.IntN(n+1), rune('a'+rng.IntN(26))))
			}
		}
		nw.drain()
		want := nw.reps[0].Text()
		for _, r := range nw.reps[1:] {
			if r.Text() != want {
				t.Fatalf("seed %d: %q != %q", seed, r.Text(), want)
			}
			if r.Inbox.Pending() != 0 {
				t.Fatalf("seed %d: undelivered operations", seed)
			}
		}
	}
}

// Two users type a word at the same position at the same time. RGA keeps
// each word together (no character-by-character interleaving) when the
// words are typed left to right.
func TestRGADoesNotInterleaveForwardTyping(t *testing.T) {
	for seed := range uint64(200) {
		rng := rand.New(rand.NewPCG(seed, 4))
		nw := newNetwork(rng, 2)
		base := nw.reps[0]
		for i, c := range "Hello!" {
			nw.broadcast(0, base.Insert(i, c))
		}
		nw.drain()
		for i, c := range " Alice" {
			nw.broadcast(0, nw.reps[0].Insert(5+i, c))
		}
		for i, c := range " Charlie" {
			nw.broadcast(1, nw.reps[1].Insert(5+i, c))
		}
		nw.drain()
		got := nw.reps[0].Text()
		if got != "Hello Alice Charlie!" && got != "Hello Charlie Alice!" {
			t.Fatalf("seed %d: interleaved: %q", seed, got)
		}
		if nw.reps[1].Text() != got {
			t.Fatalf("seed %d: diverged", seed)
		}
	}
}

// Tombstones can be dropped once the delete is causally stable, and the
// replicas still agree and keep converging afterwards.
func TestRGACollectsStableTombstones(t *testing.T) {
	rng := rand.New(rand.NewPCG(9, 9))
	nw := newNetwork(rng, 3)
	for i, c := range "garbage" {
		nw.broadcast(0, nw.reps[0].Insert(i, c))
	}
	nw.drain()
	for range 3 {
		nw.broadcast(1, nw.reps[1].Delete(0))
	}
	nw.drain()
	stable := Min(nw.reps[0].Inbox.Delivered, nw.reps[1].Inbox.Delivered, nw.reps[2].Inbox.Delivered)
	for _, r := range nw.reps {
		if r.Doc.Tombstones() != 3 {
			t.Fatalf("want 3 tombstones, got %d", r.Doc.Tombstones())
		}
		if n := r.Doc.Collect(stable); n != 3 {
			t.Fatalf("collected %d, want 3", n)
		}
	}
	nw.broadcast(2, nw.reps[2].Insert(0, 'X'))
	nw.drain()
	for _, r := range nw.reps {
		if r.Text() != "Xbage" {
			t.Fatalf("got %q", r.Text())
		}
	}
}

The Go angle ​

  • Standard library is enough for the types themselves: maps, slices.Sorted(maps.Keys(...)) for deterministic iteration (Go map order is random, and a merge that depends on iteration order is a convergence bug), encoding/json for the wire format, testing/quick and math/rand/v2 with fixed seeds for reproducible property tests.
  • Determinism is the rule to audit: ties broken by replica ID, sorted dots, no time.Now() inside merge, no map iteration feeding the result order. The tests compare whole states with Equal, not just visible values.
  • Libraries in the ecosystem: there is no dominant Go CRDT library; Yjs has a Rust port (Yrs) with bindings, and Automerge has a Rust core with a C API (rust/automerge-c) that Go can call through cgo. SoundCloud's Roshi (archived) is a Go LWW-element-set over Redis worth reading.
  • Transport: state-based types can ride on anything (HTTP, a Redis key, files); op-based types need durable per-origin sequence numbers, which a Kafka partition per document or a PostgreSQL table with (origin, seq) primary key can provide (Delivery Guarantees).
  • Concurrency inside one process: these types are not goroutine-safe; wrap a replica in a mutex or own it from one goroutine and feed it through a channel.

Laravel ​

Before ​

One integer column written by two regions, and a sync endpoint where the last uploaded document wins.

php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Before: the like count is one integer column, and both regions write it.
 *
 * Correct with a single primary. With two writable regions replicating the
 * row to each other (multi-primary replication that resolves row conflicts
 * by "last update wins"), concurrent likes in EU and US overwrite each other
 * and the count drops. The sync endpoint below has the same flaw for whole
 * documents: the last device to upload wins, and the other device's edits
 * are gone.
 */
class PostLikeController
{
    public function store(Post $post): JsonResponse
    {
        // read-modify-write of a replicated number: the lost-update recipe
        $post->likes = $post->likes + 1;
        $post->save();

        return response()->json(['likes' => $post->likes]);
    }

    public function sync(Request $request, Post $post): JsonResponse
    {
        // the device's copy replaces the server's copy
        $post->document = $request->input('document');
        $post->save();

        return response()->json(['document' => $post->document]);
    }
}

After ​

1. Schema. Merged document states and per-device states in PostgreSQL JSONB, and a PN-Counter stored as rows (one (post, region) slot per writing region). Laravel 13's $table->jsonb() creates the JSONB column; PostgreSQL stores jsonb "in a decomposed binary format" that is faster to process than json.

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // The merged state of each shared document (PostgreSQL JSONB).
        Schema::create('crdt_documents', function (Blueprint $table) {
            $table->id();
            $table->string('doc_key', 120)->unique();
            $table->string('type', 32);
            $table->jsonb('state');
            $table->unsignedBigInteger('merges')->default(0);
            $table->timestamps();
        });

        // The last state each device uploaded: lets the server compute what
        // every device has seen (causal stability) before pruning metadata.
        Schema::create('crdt_device_states', function (Blueprint $table) {
            $table->id();
            $table->string('doc_key', 120);
            $table->string('device_id', 64);
            $table->jsonb('state');
            $table->timestamps();
            $table->unique(['doc_key', 'device_id']);
        });

        // A PN-Counter as rows: one (post, region) slot, written only by its region.
        Schema::create('post_like_counters', function (Blueprint $table) {
            $table->unsignedBigInteger('post_id');
            $table->string('region', 16);
            $table->unsignedBigInteger('p')->default(0);
            $table->unsignedBigInteger('n')->default(0);
            $table->primary(['post_id', 'region']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('post_like_counters');
        Schema::dropIfExists('crdt_device_states');
        Schema::dropIfExists('crdt_documents');
    }
};

2. The CRDTs in PHP, with the same JSON shape as the Go types so a Go service or a JavaScript client can exchange states with the Laravel API.

php
<?php

namespace App\Crdt;

use JsonSerializable;

/**
 * A state-based CRDT: merge must be commutative, associative and idempotent,
 * so the server can merge device states in any order, any number of times.
 */
interface Mergeable extends JsonSerializable
{
    /** Build from a decoded JSON state; throws InvalidArgumentException on bad input. */
    public static function fromArray(array $state): static;

    /** The join of $this and $other, as a new value. */
    public function merge(Mergeable $other): static;

    /** The state as a PHP array, for the Eloquent 'array' cast. */
    public function toArray(): array;

    /** What the application reads. */
    public function value(): mixed;
}
php
<?php

namespace App\Crdt;

use InvalidArgumentException;

/**
 * PN-Counter: one increment slot and one decrement slot per replica
 * (region or device). Merge takes the per-slot maximum; value = sum(P) - sum(N).
 * Same JSON shape as the Go snippet: {"p":{"eu":3},"n":{"us":1}}.
 */
final class PNCounter implements Mergeable
{
    /**
     * @param  array<string, int>  $p
     * @param  array<string, int>  $n
     */
    public function __construct(private array $p = [], private array $n = []) {}

    public static function fromArray(array $state): static
    {
        return new self(self::slots($state['p'] ?? []), self::slots($state['n'] ?? []));
    }

    public function increment(string $replica, int $by = 1): self
    {
        $p = $this->p;
        $p[$replica] = ($p[$replica] ?? 0) + max(0, $by);

        return new self($p, $this->n);
    }

    public function decrement(string $replica, int $by = 1): self
    {
        $n = $this->n;
        $n[$replica] = ($n[$replica] ?? 0) + max(0, $by);

        return new self($this->p, $n);
    }

    public function merge(Mergeable $other): static
    {
        if (! $other instanceof self) {
            throw new InvalidArgumentException('Cannot merge '.$other::class.' into a PN-Counter.');
        }

        return new self(self::max($this->p, $other->p), self::max($this->n, $other->n));
    }

    public function value(): int
    {
        return array_sum($this->p) - array_sum($this->n);
    }

    public function toArray(): array
    {
        return ['p' => $this->p, 'n' => $this->n];
    }

    public function jsonSerialize(): array
    {
        // objects, never [], so Go and JS clients always decode a map
        return ['p' => (object) $this->p, 'n' => (object) $this->n];
    }

    /** @return array<string, int> */
    private static function slots(mixed $slots): array
    {
        if (! is_array($slots)) {
            throw new InvalidArgumentException('Counter slots must be an object.');
        }
        $clean = [];
        foreach ($slots as $replica => $count) {
            if (! is_int($count) || $count < 0 || strlen((string) $replica) > 64) {
                throw new InvalidArgumentException('Counter slot must be replica => non-negative integer.');
            }
            $clean[$replica] = $count;
        }
        ksort($clean);

        return $clean;
    }

    /** @return array<string, int> */
    private static function max(array $a, array $b): array
    {
        foreach ($b as $replica => $count) {
            $a[$replica] = max($a[$replica] ?? 0, $count);
        }
        ksort($a);

        return $a;
    }
}
php
<?php

namespace App\Crdt;

use InvalidArgumentException;

/**
 * Add-wins observed-remove set with dots and a causal context, the same
 * algorithm and JSON shape as the Go snippet:
 * {"entries":{"milk":[{"r":"phone","c":3}]},"ctx":{"phone":3,"laptop":1}}.
 *
 * A dot in ctx but absent from entries is a remembered removal, so the set
 * keeps no per-element tombstones; the context grows with the number of
 * replicas (devices), not with the number of removed elements.
 */
final class ORSet implements Mergeable
{
    /**
     * @param  array<string, list<array{r: string, c: int}>>  $entries
     * @param  array<string, int>  $ctx
     */
    public function __construct(private array $entries = [], private array $ctx = []) {}

    public static function fromArray(array $state): static
    {
        $ctx = [];
        foreach ($state['ctx'] ?? [] as $replica => $counter) {
            if (! is_int($counter) || $counter < 0) {
                throw new InvalidArgumentException('ctx must be replica => non-negative integer.');
            }
            $ctx[$replica] = $counter;
        }
        $entries = [];
        foreach ($state['entries'] ?? [] as $element => $dots) {
            if (! is_array($dots)) {
                throw new InvalidArgumentException('Each element needs a list of dots.');
            }
            foreach ($dots as $dot) {
                if (! is_string($dot['r'] ?? null) || ! is_int($dot['c'] ?? null)) {
                    throw new InvalidArgumentException('A dot is {"r": replica, "c": counter}.');
                }
                if ($dot['c'] > ($ctx[$dot['r']] ?? 0)) {
                    throw new InvalidArgumentException('A dot must be covered by the causal context.');
                }
                $entries[(string) $element][] = ['r' => $dot['r'], 'c' => $dot['c']];
            }
        }

        return new self(self::normalise($entries), $ctx);
    }

    public function add(string $replica, string $element): self
    {
        $ctx = $this->ctx;
        $ctx[$replica] = ($ctx[$replica] ?? 0) + 1;
        $entries = $this->entries;
        $entries[$element] = [['r' => $replica, 'c' => $ctx[$replica]]];

        return new self(self::normalise($entries), $ctx);
    }

    public function remove(string $element): self
    {
        $entries = $this->entries;
        unset($entries[$element]);

        return new self($entries, $this->ctx);
    }

    public function merge(Mergeable $other): static
    {
        if (! $other instanceof self) {
            throw new InvalidArgumentException('Cannot merge '.$other::class.' into an OR-Set.');
        }
        $out = [];
        foreach (array_keys($this->entries + $other->entries) as $element) {
            $mine = $this->entries[$element] ?? [];
            $theirs = $other->entries[$element] ?? [];
            $dots = [];
            foreach ($mine as $dot) {
                if (in_array($dot, $theirs, true) || ! self::covers($other->ctx, $dot)) {
                    $dots[] = $dot;
                }
            }
            foreach ($theirs as $dot) {
                if (! in_array($dot, $mine, true) && ! self::covers($this->ctx, $dot)) {
                    $dots[] = $dot;
                }
            }
            if ($dots !== []) {
                $out[(string) $element] = $dots;
            }
        }
        $ctx = $this->ctx;
        foreach ($other->ctx as $replica => $counter) {
            $ctx[$replica] = max($ctx[$replica] ?? 0, $counter);
        }
        ksort($ctx);

        return new self(self::normalise($out), $ctx);
    }

    /** @return list<string> */
    public function value(): array
    {
        return array_map('strval', array_keys($this->entries));
    }

    public function toArray(): array
    {
        return ['entries' => $this->entries, 'ctx' => $this->ctx];
    }

    public function jsonSerialize(): array
    {
        return ['entries' => (object) $this->entries, 'ctx' => (object) $this->ctx];
    }

    private static function covers(array $ctx, array $dot): bool
    {
        return ($ctx[$dot['r']] ?? 0) >= $dot['c'];
    }

    private static function normalise(array $entries): array
    {
        foreach ($entries as &$dots) {
            usort($dots, fn (array $a, array $b) => [$a['r'], $a['c']] <=> [$b['r'], $b['c']]);
        }
        unset($dots);
        ksort($entries, SORT_STRING);

        return $entries;
    }
}
php
<?php

namespace App\Crdt;

use InvalidArgumentException;

/** Maps the "type" string clients send to a CRDT class. */
final class Crdt
{
    public const TYPES = ['pn-counter', 'or-set'];

    public static function make(string $type, array $state): Mergeable
    {
        return match ($type) {
            'pn-counter' => PNCounter::fromArray($state),
            'or-set' => ORSet::fromArray($state),
            default => throw new InvalidArgumentException("Unknown CRDT type [{$type}]."),
        };
    }

    public static function empty(string $type): Mergeable
    {
        return self::make($type, []);
    }
}

3. Models. The array cast: "The array cast is particularly useful when working with columns that are stored as serialized JSON" (Laravel 13 docs, Eloquent: Mutators & Casting).

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CrdtDocument extends Model
{
    protected $fillable = ['doc_key', 'type', 'state', 'merges'];

    protected function casts(): array
    {
        return [
            'state' => 'array', // JSONB <-> PHP array
            'merges' => 'integer',
        ];
    }
}
php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CrdtDeviceState extends Model
{
    protected $fillable = ['doc_key', 'device_id', 'state'];

    protected function casts(): array
    {
        return ['state' => 'array'];
    }
}

4. Merge on write. The endpoint joins the device's state into the stored state under a row lock and returns the merged state. The merge itself cannot conflict; the read-merge-write in SQL can, which is why lockForUpdate() and DB::transaction(..., 3) are there.

php
<?php

namespace App\Http\Controllers;

use App\Crdt\Crdt;
use App\Crdt\Mergeable;
use App\Models\CrdtDeviceState;
use App\Models\CrdtDocument;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;

/**
 * POST /api/crdt/{docKey}/sync
 * {"device_id": "phone-7f3a", "type": "or-set", "state": {...}}
 *
 * Merge on write: the server joins the device's state into the stored state
 * and returns the merged state, which the device merges back. Because merge
 * is idempotent and commutative, retries, duplicates and out-of-order uploads
 * are all harmless; a device can sync after a week offline.
 */
class CrdtSyncController
{
    public function __invoke(Request $request, string $docKey): JsonResponse
    {
        $data = $request->validate([
            'device_id' => ['required', 'string', 'max:64'],
            'type' => ['required', 'string', Rule::in(Crdt::TYPES)],
            'state' => ['present', 'array'],
        ]);

        try {
            $incoming = Crdt::make($data['type'], $data['state']);
        } catch (InvalidArgumentException $e) {
            throw ValidationException::withMessages(['state' => $e->getMessage()]);
        }

        $merged = DB::transaction(function () use ($docKey, $data, $incoming): Mergeable {
            // Create the row once; concurrent first syncs do not fail.
            DB::table('crdt_documents')->insertOrIgnore([
                'doc_key' => $docKey,
                'type' => $data['type'],
                'state' => json_encode(Crdt::empty($data['type'])),
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            // The merge is conflict-free; the read-merge-write in SQL is not.
            // Without the row lock two concurrent syncs could each merge into
            // the same old state and the second save would drop the first.
            $doc = CrdtDocument::query()->where('doc_key', $docKey)->lockForUpdate()->firstOrFail();
            abort_if($doc->type !== $data['type'], 409, 'Document has a different CRDT type.');

            $merged = Crdt::make($doc->type, $doc->state)->merge($incoming);
            $doc->state = $merged->toArray();
            $doc->merges++;
            $doc->save();

            CrdtDeviceState::query()->updateOrCreate(
                ['doc_key' => $docKey, 'device_id' => $data['device_id']],
                ['state' => $incoming->toArray()],
            );

            return $merged;
        }, 3);

        return response()->json([
            'type' => $data['type'],
            'state' => $merged,
            'value' => $merged->value(),
        ]);
    }
}

5. Likes across regions. Each region increments only its own row with an upsert; rows from other regions are joined with GREATEST, the per-slot maximum, so a replayed or reordered push cannot double-count.

php
<?php

namespace App\Services;

use App\Crdt\PNCounter;
use Illuminate\Support\Facades\DB;

/**
 * Likes as a PN-Counter stored as rows: post_like_counters(post_id, region, p, n).
 *
 * Each region increments only its own row, so local writes never conflict and
 * need no cross-region round trip. Rows from other regions arrive through
 * replication or the merge endpoint and are joined with GREATEST, the
 * per-slot maximum: duplicates and reordering cannot double-count.
 */
final class RegionalLikeCounter
{
    public function __construct(private readonly string $region) {}

    public function like(int $postId): void
    {
        $this->bump($postId, 'p');
    }

    public function unlike(int $postId): void
    {
        $this->bump($postId, 'n');
    }

    public function count(int $postId): int
    {
        return (int) DB::table('post_like_counters')
            ->where('post_id', $postId)
            ->sum(DB::raw('p - n'));
    }

    /** This region's slots for a post, as a PN-Counter to ship to the other regions. */
    public function localState(int $postId): PNCounter
    {
        $row = DB::table('post_like_counters')
            ->where(['post_id' => $postId, 'region' => $this->region])
            ->first();

        return PNCounter::fromArray([
            'p' => [$this->region => (int) ($row->p ?? 0)],
            'n' => [$this->region => (int) ($row->n ?? 0)],
        ]);
    }

    /** Join a remote PN-Counter into the table: per-slot maximum, idempotent. */
    public function mergeRemote(int $postId, PNCounter $remote): void
    {
        $state = $remote->toArray();
        $rows = [];
        foreach (array_unique([...array_keys($state['p']), ...array_keys($state['n'])]) as $region) {
            $rows[] = [
                'post_id' => $postId,
                'region' => (string) $region,
                'p' => $state['p'][$region] ?? 0,
                'n' => $state['n'][$region] ?? 0,
            ];
        }

        DB::table('post_like_counters')->upsert($rows, ['post_id', 'region'], [
            'p' => DB::raw('GREATEST(post_like_counters.p, excluded.p)'),
            'n' => DB::raw('GREATEST(post_like_counters.n, excluded.n)'),
        ]);
    }

    private function bump(int $postId, string $column): void
    {
        DB::table('post_like_counters')->upsert(
            [['post_id' => $postId, 'region' => $this->region, 'p' => $column === 'p' ? 1 : 0, 'n' => $column === 'n' ? 1 : 0]],
            ['post_id', 'region'],
            [$column => DB::raw("post_like_counters.{$column} + 1")],
        );
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Crdt\PNCounter;
use App\Services\RegionalLikeCounter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;

/**
 * After: likes are a PN-Counter. Each region writes its own slot; the total is
 * the sum over regions. "Has this user liked the post?" is a separate,
 * per-user fact (a unique row in the user's home region), not part of the count.
 */
class PostLikeController
{
    public function __construct(private RegionalLikeCounter $likes) {}

    public function store(int $post): JsonResponse
    {
        $this->likes->like($post);

        return response()->json(['likes' => $this->likes->count($post)], 201);
    }

    public function destroy(int $post): JsonResponse
    {
        $this->likes->unlike($post);

        return response()->json(['likes' => $this->likes->count($post)]);
    }

    public function show(int $post): JsonResponse
    {
        return response()->json(['likes' => $this->likes->count($post)]);
    }

    /** Region-to-region: the other region pushes its slots; we join them in. */
    public function mergeRemote(Request $request, int $post): JsonResponse
    {
        $state = $request->validate(['p' => ['present', 'array'], 'n' => ['present', 'array']]);

        try {
            $this->likes->mergeRemote($post, PNCounter::fromArray($state));
        } catch (InvalidArgumentException $e) {
            throw ValidationException::withMessages(['state' => $e->getMessage()]);
        }

        return response()->json([
            'likes' => $this->likes->count($post),
            'local' => $this->likes->localState($post),
        ]);
    }
}
php
<?php

namespace App\Providers;

use App\Services\RegionalLikeCounter;
use Illuminate\Support\ServiceProvider;

class CrdtServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // APP_REGION=eu-west in .env; config/app.php: 'region' => env('APP_REGION', 'local')
        $this->app->singleton(RegionalLikeCounter::class, fn () => new RegionalLikeCounter(config('app.region')));
    }
}
php
<?php

use App\Http\Controllers\CrdtSyncController;
use App\Http\Controllers\PostLikeController;
use Illuminate\Support\Facades\Route;

Route::post('/crdt/{docKey}/sync', CrdtSyncController::class)
    ->where('docKey', '[A-Za-z0-9:_-]{1,120}')
    ->middleware(['auth:sanctum', 'throttle:60,1']);

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/posts/{post}/likes', [PostLikeController::class, 'show'])->whereNumber('post');
    Route::post('/posts/{post}/likes', [PostLikeController::class, 'store'])->whereNumber('post');
    Route::delete('/posts/{post}/likes', [PostLikeController::class, 'destroy'])->whereNumber('post');
});

// Called by the other regions' app servers over a private network with mTLS.
Route::post('/internal/posts/{post}/like-counter', [PostLikeController::class, 'mergeRemote'])
    ->whereNumber('post');

6. The same merges in SQL. Useful when another service writes the table, or to merge in one statement instead of a lock:

sql
-- PN-Counter value for one post, from the per-region rows
SELECT post_id, SUM(p) - SUM(n) AS likes
FROM post_like_counters
WHERE post_id = 42
GROUP BY post_id;

-- Join a remote region's slots (idempotent: replaying it changes nothing)
INSERT INTO post_like_counters (post_id, region, p, n)
VALUES (42, 'us-east', 1200, 31)
ON CONFLICT (post_id, region) DO UPDATE
SET p = GREATEST(post_like_counters.p, EXCLUDED.p),
    n = GREATEST(post_like_counters.n, EXCLUDED.n);

-- G-Counter merge of two JSONB states {"p":{"eu":3,"us":2}}: per-key maximum
CREATE OR REPLACE FUNCTION gcounter_merge(a jsonb, b jsonb) RETURNS jsonb
LANGUAGE sql IMMUTABLE AS $$
  SELECT COALESCE(jsonb_object_agg(k, v), '{}'::jsonb)
  FROM (
    SELECT k, MAX(v::bigint) AS v
    FROM (
      SELECT key AS k, value AS v FROM jsonb_each_text(a)
      UNION ALL
      SELECT key, value FROM jsonb_each_text(b)
    ) s
    GROUP BY k
  ) m
$$;

-- Atomic merge-on-write of a PN-Counter document without an application lock
UPDATE crdt_documents
SET state = jsonb_build_object(
      'p', gcounter_merge(state->'p', '{"phone-7f3a": 4}'::jsonb),
      'n', gcounter_merge(state->'n', '{"phone-7f3a": 1}'::jsonb)),
    merges = merges + 1,
    updated_at = now()
WHERE doc_key = 'post:42:likes' AND type = 'pn-counter';

The Laravel angle ​

  • Casts: 'state' => 'array' decodes JSONB into PHP arrays; PHP turns numeric-string keys into integers and an empty map into [], so the CRDT classes normalise keys and implement JsonSerializable to always emit JSON objects ((object) casts). AsArrayObject is the alternative when you mutate nested offsets in place.
  • Query builder: insertOrIgnore creates the document row without failing on a concurrent first sync; lockForUpdate() serialises read-merge-write per document; upsert() with DB::raw('GREATEST(...)') is the merge for row-shaped counters (PostgreSQL requires the unique index on (post_id, region), which the primary key provides).
  • Transactions: DB::transaction($callback, 3) retries on deadlock; the merge is idempotent, so a retry is safe.
  • Broadcasting: after a merge, broadcast the merged state (or a "document changed" event) with Laravel Reverb so connected devices pull it; the device merges what it receives, so a lost or duplicated event is harmless.
  • Queues: cross-region pushes of counter slots belong in a queued job with retries; idempotent merge makes at-least-once delivery acceptable (Idempotent Consumers).
  • Octane: the RegionalLikeCounter singleton holds only the region name, so it is safe across requests.
  • Yjs and Automerge from Laravel: treat their binary updates as opaque blobs (bytea column), store them in order per document, and let clients merge; PHP does not need to understand the CRDT to be its storage and relay.

Solving the classic problems ​

Likes and view counts across regions ​

SolutionHowAdvantageCost / limitation
Single home region for the counterAll increments go to one regionExact, simpleCross-region latency per like; outage of that region stops likes
UPDATE ... SET likes = likes + 1 in every region with multi-primary replicationReplicate the rowLocal writesRow conflicts resolved LWW: lost likes
PN-Counter with one slot per regionEach region writes its own slot; merge = per-slot maxLocal writes, exact after sync, idempotentValue is eventually exact; no "never negative" guarantee
Sharded counter in one regionN rows summed (Write Buffering & Sharded Counters)Spreads hot-row contentionStill one region

Preferred: PN-Counter per region (RegionalLikeCounter, Go PNCounter), with "did this user like it?" stored separately in the user's home region.

The shopping cart that resurrects removed items ​

SolutionHowAdvantageCost / limitation
Union mergeMerge carts by set unionNever loses an addRemoved items come back (Dynamo anomaly)
2P-SetRemoves are permanentRemoves stickCannot re-add the same item
LWW-Element-SetTimestamp per add/removeRe-add worksClock skew decides
OR-Set (add-wins) with quantities as PN-Counters in an OR-MapDots per add, observed removeMatches user expectations; no clocksMetadata per device; concurrent remove loses to add

Preferred: OR-Map of item to PN-Counter (quantity), keys add-wins. Redis Active-Active hashes and sets give this semantics server-side.

An offline-first notes or to-do app ​

SolutionHowAdvantageCost / limitation
Server wins / last upload winsOverwrite on syncTrivialEdits lost after offline periods
Per-field LWW with HLC timestampsOne register per fieldSmall metadataConcurrent edits to one field lose one
Automerge or Yjs document per list, server stores updatesLibrary CRDT, server is storage and relayEvery edit kept; works peer-to-peerLibrary lock-in; document growth
Device-state merge endpoint (this page's Laravel snippet)Devices upload states, server mergesSimple server, any client languageFull-state uploads; needs GC plan

A collaborative text editor ​

SolutionHowAdvantageCost / limitation
OT with a central serverTransform against concurrent opsProven (Google Docs), small metadataNeeds the server online; complex transforms
Yjs with a WebSocket providerYATA CRDT, editor bindingsMature bindings, offline, p2p possibleTombstone structs remain
Automerge with rich text (Peritext marks)JSON CRDT + PeritextHistory, rich text semanticsLarger history
Lock paragraphs (one editor per block)Coordination per blockNo merge at allUsers wait; not real-time

Stock or balance that must never go negative ​

SolutionHowAdvantageCost / limitation
PN-Counter, refuse decrement locally at 0Local checkFastTwo replicas at 1 both decrement: -1 (Shapiro et al.)
Single owner per SKU or accountRoute writes to the ownerExactOwner's latency and availability
Escrow / bounded counterPre-allocate decrement rights per replicaLocal decrements until rights run outRebalancing rights needs coordination
Consensus (Raft, Spanner, CockroachDB)Linearizable decrementExact everywhereRound trip per write; minority side unavailable

Metadata explosion ​

SolutionHowAdvantageCost / limitation
Causal-stability GCCollect below the min of all replicas' vectorsSafeStalls while any replica is offline
Replica retirementRemove a device's slot after it resyncs or is revokedBounded vectorsNeeds a coordinated step (Akka pruning)
Snapshot and resetFreeze a snapshot, start a new document epochBounded sizeOld replicas must reload
Expiry of whole keysAkka expiry, TTLsNo tombstones at allData disappears by time

Choosing ​

Global invariant on this data?balance >= 0, unique username, last seat, stock >= 0yesCoordinate: consensus, one ownerper key, or escrow of rights.CRDT only for the other fields.noWrites while offline or multi-regionwithout a coordination round trip?noSingle leader is simpler:no merge semantics to designyesPick the CRDT by the data's shapeCountG-/PN-CounterMembershipOR-Set (add/remove-wins)One valueLWW- or MV-RegisterObject / JSONOR-Map, JSON CRDTOrdered textRGA, YATA, Fuguelikes, views, quotascart, tags, memberstitle, status, avatardocuments, settingsnotes, code, PeritextThen budget metadata: tombstones, dots, version vectors per replica; plan garbage collection.
Data / workloadRecommendationExtra techniqueReason
Likes, views, reactions, counters of eventsPN-Counter, one slot per regionSeparate per-user "liked" factIncrements commute; exact after sync
Quota usage (soft limit)PN-Counter + periodic reconciliationAlert on overshootOvershoot of a few is acceptable
Quota or stock (hard limit)Coordination or escrowCRDT for the display copy onlyGlobal invariant
Shopping cart, tags, labels, membersOR-Set / OR-Map (add-wins)Quantities as countersUsers expect a re-add to win
Permissions, blocklistRemove-wins set, or single leaderAudit logA concurrent grant must not win silently
Profile fieldsLWW per field with HLC stampsMV where loss upsets usersConcurrent edits rare and low value
Document title, statusMV-RegisterShow siblingsTwo edits are both meaningful
Text, notes, codeYjs or AutomergePresence, server persistenceSequence CRDTs are hard to get right
Rich textAutomerge (Peritext marks) or Yjs with an editor bindingSchema validation after mergeFormatting intent
Ordered items (kanban)RGA over item IDs or fractional indexing with a serverMove = delete + insert (or a move op)Few items, simple
Event log / timelineLWW-Element-Set by event time (Roshi) or G-SetTime-bucketed keysEvent time is meaningful
Usernames, seats, paymentsNot a CRDT: linearizable storeIdempotency keysUniqueness and money

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One PostgreSQL primary and no replicas: nothing is concurrent across copies, so a CRDT adds metadata for no benefit. The exception is the client: if the monolith has a mobile app that edits offline, the devices are replicas. Example: a Laravel monolith with a notes app; the app stores Yjs updates per note in a bytea column and relays them; the server never merges text itself.

Modular monolith: boundaries without the network ​

Modules share one database, so they can share state transactionally; CRDTs appear at the edges: the "engagement" module keeps PN-Counters that other modules read; the "documents" module owns the CRDT storage and exposes merge(docKey, state) as its only write API. Keep the CRDT library behind that module so the rest of the code sees plain values.

Microservices: CRDT state across service boundaries ​

Services exchange events, not shared tables. A CRDT state is a good event payload because receivers can merge it idempotently in any order, which tolerates at-least-once delivery without an inbox table:

text
     Engagement service (EU)          Kafka topic likes-state (key = post_id)        Feed service (US)
1    like -> slot eu += 1
2    every 1 s: publish {"p":{"eu":120},"n":{"eu":3}}  ->  partition by post_id
3                                                                             consume, merge into local copy
4    consumer crashes, re-reads the last 100 messages                         merge again: no change (idempotent)
5    US likes -> slot us += 1, published the same way -> EU merges
6    both sides: value = sum(p) - sum(n); no saga, no dedup table

What does not survive the boundary: invariants that span services ("do not ship more than paid"); those stay in sagas with compensations (Saga Pattern).

Distributed data: replicas, caches, multi-region ​

This is where CRDTs earn their keep: active-active regions (Redis Enterprise Active-Active, Riak, Akka cluster), caches that accept writes on both sides, and devices as replicas. Replication wiring and the alternative conflict strategies (LWW, siblings, conflict avoidance by home region) are in Replication Topologies; which consistency model the clients then observe is in Consistency Models. Clocks still matter for LWW types: use hybrid logical clocks, never raw wall clocks (Vector Clocks). Repair of diverged replicas uses anti-entropy, and for CRDTs repair is simply "merge the states" (Merkle Trees & Anti-Entropy).

Scaling path: 1x, 10x, 100x ​

LoadWhat changesExample
1xNo CRDTs server-side; maybe a CRDT library on clientsLaravel + PostgreSQL; Yjs updates stored as blobs
10xSecond region active; counters and sets become CRDTs; everything else stays single-leader per keyPN-Counter rows per region, Redis Active-Active for sessions and carts
100xPer-feature consistency: CRDTs for engagement and collaboration, consensus for money and inventory, escrow for soft limits; metadata budgets, GC and replica retirement automatedRedis Active-Active in 3+ regions, Yjs servers sharded by document, CockroachDB or Spanner for payments

Lab: replay the scenarios ​

Single-process Go, no network, no containers. It takes about a second.

go
// Command lab replays the chapter's scenarios in one process: two or three
// replicas, edits made while "offline", then a sync. Output is deterministic.
package main

import (
	"encoding/json"
	"fmt"
	"math/rand/v2"
	"time"

	"academy/crdts/before"
	"academy/crdts/crdt"
)

func main() {
	likes()
	register()
	carts()
	siblings()
	text()
	delta()
}

func likes() {
	fmt.Println("1. likes: EU gets 3 likes, US gets 2, regions offline from each other")
	t0 := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)
	eu, us := &before.LikeCounter{}, &before.LikeCounter{}
	for i := range 3 {
		eu.Like(t0.Add(time.Duration(i) * time.Millisecond))
	}
	for i := range 2 {
		us.Like(t0.Add(time.Duration(10+i) * time.Millisecond))
	}
	eu.Receive(*us)
	us.Receive(*eu)
	fmt.Printf("   before (number + LWW):  eu=%d us=%d\n", eu.Count, us.Count)

	a, b := crdt.NewPNCounter(), crdt.NewPNCounter()
	a.Inc("eu", 3)
	b.Inc("us", 2)
	b.Dec("us", 1) // one unlike
	a.Merge(b)
	b.Merge(a)
	a.Merge(b) // duplicate sync: no effect
	fmt.Printf("   after (PN-Counter):     eu=%d us=%d  (3 + 2 - 1)\n", a.Value(), b.Value())
}

func register() {
	fmt.Println("2. LWW-Register with a clock 300 ms behind")
	a, b := &crdt.LWWRegister[string]{}, &crdt.LWWRegister[string]{}
	a.Set("blue", crdt.Stamp{Time: 1000, Replica: "a"})
	b.Merge(a)
	b.Set("green", crdt.Stamp{Time: 800, Replica: "b"})
	a.Merge(b)
	fmt.Printf("   wall-clock stamp:       a=%s b=%s  (b's later edit lost)\n", a.Value, b.Value)
	b.Set("green", b.NextStamp("b", 800))
	a.Merge(b)
	fmt.Printf("   max(now, seen+1) stamp: a=%s b=%s\n", a.Value, b.Value)
}

func carts() {
	fmt.Println("3. cart: phone removes \"book\"; laptop syncs a stale copy (before) or re-adds it concurrently (CRDT sets)")
	p, l := before.Cart{}, before.Cart{}
	p.Add("book")
	l.Receive(p)
	p.Remove("book")
	p.Receive(l)
	fmt.Printf("   before (union):  phone has book=%v  (sequential remove undone)\n", p["book"])

	tp, tl := crdt.NewTwoPSet(), crdt.NewTwoPSet()
	tp.Add("book")
	tl.Merge(tp)
	tp.Remove("book")
	tl.Add("book")
	tp.Merge(tl)
	fmt.Printf("   2P-Set:          book=%v  (remove wins, re-add impossible)\n", tp.Has("book"))

	op, ol := crdt.NewORSet(), crdt.NewORSet()
	op.Add("phone", "book")
	ol.Merge(op)
	op.Remove("book")
	ol.Add("laptop", "book")
	op.Merge(ol)
	ol.Merge(op)
	fmt.Printf("   OR-Set:          book=%v  (concurrent add wins)\n", op.Has("book"))
	ol.Remove("book")
	op.Merge(ol)
	fmt.Printf("   OR-Set:          book=%v  (a remove that saw every add sticks)\n", op.Has("book"))
}

func siblings() {
	fmt.Println("4. MV-Register: two concurrent title edits")
	a, b := &crdt.MVRegister[string]{}, &crdt.MVRegister[string]{}
	a.Set("a", "Draft")
	b.Merge(a)
	a.Set("a", "Q3 plan")
	b.Set("b", "Q3 roadmap")
	a.Merge(b)
	fmt.Printf("   siblings: %q\n", a.Values())
}

func text() {
	fmt.Println("5. RGA: Ana types \" Alice\", Ben types \" Charlie\" at the same spot, offline")
	ana, ben := crdt.NewReplica("ana"), crdt.NewReplica("ben")
	var log []crdt.Envelope[crdt.RGAOp]
	for i, c := range "Hello!" {
		log = append(log, ana.Insert(i, c))
	}
	for _, e := range log {
		ben.Receive(e)
	}
	var fromAna, fromBen []crdt.Envelope[crdt.RGAOp]
	for i, c := range " Alice" {
		fromAna = append(fromAna, ana.Insert(5+i, c))
	}
	for i, c := range " Charlie" {
		fromBen = append(fromBen, ben.Insert(5+i, c))
	}
	// Deliver Ben's ops to Ana in reverse: the causal inbox buffers them.
	for i := len(fromBen) - 1; i >= 0; i-- {
		ana.Receive(fromBen[i])
	}
	for _, e := range fromAna {
		ben.Receive(e)
	}
	fmt.Printf("   ana=%q ben=%q\n", ana.Text(), ben.Text())
	del := ana.Delete(0)
	ben.Receive(del)
	fmt.Printf("   after deleting \"H\": tombstones ana=%d ben=%d\n", ana.Doc.Tombstones(), ben.Doc.Tombstones())
	stable := crdt.Min(ana.Inbox.Delivered, ben.Inbox.Delivered)
	fmt.Printf("   stable=%v collected ana=%d ben=%d\n", stable, ana.Doc.Collect(stable), ben.Doc.Collect(stable))

	converged := 0
	for seed := range uint64(1000) {
		if randomSession(seed) {
			converged++
		}
	}
	fmt.Printf("   random 3-replica sessions converged: %d / 1000\n", converged)
}

// randomSession edits three replicas with random delivery order and reports
// whether they converge after every message is delivered.
func randomSession(seed uint64) bool {
	rng := rand.New(rand.NewPCG(seed, 7))
	reps := []*crdt.Replica{crdt.NewReplica("x"), crdt.NewReplica("y"), crdt.NewReplica("z")}
	inbox := make([][]crdt.Envelope[crdt.RGAOp], 3)
	send := func(from int, e crdt.Envelope[crdt.RGAOp]) {
		for to := range reps {
			if to != from {
				inbox[to] = append(inbox[to], e)
			}
		}
	}
	for range 60 {
		i := rng.IntN(3)
		n := len([]rune(reps[i].Text()))
		switch {
		case len(inbox[i]) > 0 && rng.IntN(3) == 0:
			k := rng.IntN(len(inbox[i]))
			reps[i].Receive(inbox[i][k])
			inbox[i] = append(inbox[i][:k], inbox[i][k+1:]...)
		case n > 0 && rng.IntN(4) == 0:
			send(i, reps[i].Delete(rng.IntN(n)))
		default:
			send(i, reps[i].Insert(rng.IntN(n+1), rune('a'+rng.IntN(26))))
		}
	}
	for i := range reps {
		for _, k := range rng.Perm(len(inbox[i])) {
			reps[i].Receive(inbox[i][k])
		}
	}
	return reps[0].Text() == reps[1].Text() && reps[1].Text() == reps[2].Text()
}

func delta() {
	fmt.Println("6. delta-state: G-Counter with 100 replica slots, one increment")
	g := crdt.NewGCounter()
	for i := range 100 {
		g.Inc(crdt.ReplicaID(fmt.Sprintf("r%03d", i)), 5)
	}
	d := g.Inc("r042", 1)
	full, _ := json.Marshal(g)
	small, _ := json.Marshal(d)
	fmt.Printf("   full state %d bytes, delta %d bytes: %s\n", len(full), len(small), small)
}
bash
cd docs/snippets/system-design/crdts/go
gofmt -l . && go vet ./... && go test ./...
go run ./cmd/lab

Output from an actual run on the author's machine (Go toolchain from Homebrew; schedules use fixed seeds):

text
1. likes: EU gets 3 likes, US gets 2, regions offline from each other
   before (number + LWW):  eu=2 us=2
   after (PN-Counter):     eu=4 us=4  (3 + 2 - 1)
2. LWW-Register with a clock 300 ms behind
   wall-clock stamp:       a=blue b=blue  (b's later edit lost)
   max(now, seen+1) stamp: a=green b=green
3. cart: phone removes "book"; laptop syncs a stale copy (before) or re-adds it concurrently (CRDT sets)
   before (union):  phone has book=true  (sequential remove undone)
   2P-Set:          book=false  (remove wins, re-add impossible)
   OR-Set:          book=true  (concurrent add wins)
   OR-Set:          book=false  (a remove that saw every add sticks)
4. MV-Register: two concurrent title edits
   siblings: ["Q3 roadmap" "Q3 plan"]
5. RGA: Ana types " Alice", Ben types " Charlie" at the same spot, offline
   ana="Hello Charlie Alice!" ben="Hello Charlie Alice!"
   after deleting "H": tombstones ana=1 ben=1
   stable=map[ana:13 ben:8] collected ana=1 ben=1
   random 3-replica sessions converged: 1000 / 1000
6. delta-state: G-Counter with 100 replica slots, one increment
   full state 907 bytes, delta 16 bytes: {"p":{"r042":6}}

Experiments.

  1. In crdt/set.go, change Merge so that a dot is kept only if both sides have it (drop the "not seen by the other context" branch). Run go test ./crdt -run ORSet: TestORSetAddWins fails, because a concurrent add is now treated as removed (you built a remove-wins set by accident).
  2. In crdt/counter.go, make GCounter.Merge add slots instead of taking the maximum. TestPNCounterMergeIsASemilatticeJoin reports the idempotence failure with the testing/quick counter-example.
  3. In crdt/rga.go, delete the for i < len(r.nodes) && op.ID.Less(...) loop. TestRGAConvergesForRandomOperationOrders fails with two different texts and the seed that produced them.
  4. In crdt/causal.go, make ready always return true (no causal delivery). The RGA tests panic with rga: anchor not delivered; causal delivery violated.
  5. Laravel endpoint (expected, not run): with the migration applied on PostgreSQL, send the same OR-Set state twice:
bash
curl -s -X POST https://app.example.test/api/crdt/list:42/sync \
  -H 'Authorization: Bearer <token>' -H 'Content-Type: application/json' \
  -d '{"device_id":"phone-7f3a","type":"or-set","state":{"entries":{"milk":[{"r":"phone-7f3a","c":1}]},"ctx":{"phone-7f3a":1}}}'
# expected, not run (both calls):
# {"type":"or-set","state":{"entries":{"milk":[{"r":"phone-7f3a","c":1}]},"ctx":{"phone-7f3a":1}},"value":["milk"]}

Then send from laptop-91c2 a state whose ctx is {"phone-7f3a":1} and whose entries is empty (it removed milk after seeing it): expected "value":[]. Send a state from a third device with ctx {"tablet-1":1} and entries {"milk":[{"r":"tablet-1","c":1}]} (a concurrent add): expected "value":["milk"].

  1. SQL merge (expected, not run): run the INSERT ... ON CONFLICT ... GREATEST statement twice with the same numbers; SELECT SUM(p) - SUM(n) returns the same value after the second run.

Common misconceptions ​

BeliefReality
"CRDTs eliminate conflicts"They pre-decide every conflict deterministically; the decision (add-wins, LWW, siblings) can still surprise users
"Strong eventual consistency is strong consistency"It is convergence: replicas with the same updates are equal; reads can be stale, invariants are not enforced
"LWW is a CRDT, so it is safe"It is a CRDT that discards one of every two concurrent writes, and clock skew picks which
"Counting with +1 messages is a CRDT counter"Only with exactly-once causal delivery; over at-least-once networks use per-replica slots with max-merge
"One counter slot per user is fine"Slots are per writing replica; per-user or per-device slots explode metadata
"Removing an element frees its memory"Tombstones or causal context remain until the removal is causally stable everywhere
"Op-based CRDTs need nothing from the network"They need causal, exactly-once delivery; state-based types are the ones that tolerate a sloppy network
"A merge is safe in SQL because it is conflict-free"The read-merge-write is a lost-update race; lock the row or merge in one SQL statement
"Convergent text is good text"Interleaving and broken formatting can converge too; intent needs algorithms like Fugue and Peritext
"CRDTs can enforce stock at least zero if each replica checks locally"Two replicas at 1 can both decrement to -1; global invariants need coordination or escrow
"Figma uses CRDTs"Figma says its system is "inspired by" CRDTs and "isn't using true CRDTs": the server orders changes
"CRDTs are secure in peer-to-peer apps"The classic model assumes non-Byzantine replicas; untrusted peers need signed, hash-linked operations

Cheat sheet ​

TopicRemember
SECSame updates delivered => same state, immediately, no consensus
CvRDTMerge = least upper bound: commutative, associative, idempotent; updates monotonic
CmRDTConcurrent ops commute; needs causal, exactly-once delivery
Delta-stateShip the delta, join it like a state; small messages on a sloppy network
G-Counter / PN-CounterSlot per writing replica, max-merge, sum; P - N may go negative
LWW-RegisterLoses concurrent writes; use max(now, seen+1) or HLC stamps
MV-RegisterKeeps siblings via version vectors; a later write covering them resolves
2P-SetRemove wins, forever
OR-SetDots + causal context; remove drops observed dots; add wins
Remove-wins setBias reversed; for permissions and blocklists
OR-MapKeys as OR-Set, values CRDTs; beware resurrected half-objects
SequencesIDs not indexes; RGA anchor + ID order; tombstones
TextYjs (YATA), Automerge (JSON CRDT, Peritext marks), Fugue for non-interleaving
GCOnly below the causal-stability frontier (min of all replicas' vectors)
LimitsNo global invariants; metadata grows; non-Byzantine assumption
ProductsRiak data types, Redis Active-Active (CRDB), Akka Distributed Data, Roshi, AntidoteDB; Figma CRDT-inspired

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is "merge = add the two counter values" not a valid CvRDT merge, while "per-slot maximum" is? Important ​

Answer

Answer: Adding is not idempotent: merging the same state twice (a retry, a duplicate gossip message) doubles the count. Per-slot maximum is commutative, associative and idempotent, so duplicates and reordering change nothing. See CvRDT and lab experiment 2.

2 — What does an operation-based CRDT need from the network that a state-based one does not? Important ​

Answer

Answer: Causal delivery, exactly once: an operation must not be applied before the operations it depends on (an insert before its anchor) and must not be applied twice. State-based CRDTs tolerate loss, duplicates and reordering because the join is idempotent. See CmRDT.

3 — EU has a PN-Counter state P{eu:3}, US has P{us:2} N{us:1}. What is the value after they sync, and after a duplicate sync? Important ​

Answer

Answer: P{eu:3, us:2} N{us:1}, value 4, on both sides; a duplicate sync leaves it at 4 because each slot takes the maximum. See Counters.

4 — Ana removes "milk" from a shared list while Ben, offline, adds "milk". What does an add-wins OR-Set show after sync, and why, in terms of dots? Good to know ​

Answer

Answer: "milk" is present. Ana's remove dropped only the dots she had observed; Ben's add created a new dot that is not in Ana's causal context, so the merge keeps it. See OR-Set and its diagram.

5 — When would you choose a remove-wins set over add-wins? Good to know ​

Answer

Answer: When a concurrent re-add must not silently undo a removal: permissions, blocklists, revoked keys. AntidoteDB offers both (AW-Set and RW-Set). See OR-Set and Choosing.

6 — A phone whose clock is 300 ms slow edits a title after syncing. With an LWW-Register, why can the edit be lost, and what one-line change prevents that? Important ​

Answer

Answer: Its wall-clock stamp is smaller than the stamp of the value it overwrote, so the merge keeps the older value. Stamping with max(now, seen + 1) (the hybrid-logical-clock idea) makes a causally later write always win. Truly concurrent writes still lose one. See Registers and the lab.

7 — Why can an RGA not simply delete an element, and when may the tombstone be removed? Good to know ​

Answer

Answer: A concurrent insert may still use the deleted element as its anchor. The tombstone can go once the delete is causally stable: every replica has delivered it, so no operation that could reference it can still arrive. See Metadata and GC.

8 — Two users type " Alice" and " Charlie" at the same position. Which outcomes are acceptable, and which algorithms can produce an unacceptable one? Good to know ​

Answer

Answer: "Hello Alice Charlie!" or "Hello Charlie Alice!". Logoot, LSEQ and Treedoc can interleave the letters; RGA does not for words typed left to right but has a lesser anomaly for backward typing; FugueMax is proven maximally non-interleaving. See Intent.

9 — Why does the Laravel sync endpoint lock the document row if the merge is conflict-free? Important ​

Answer

Answer: The merge is conflict-free, but read, merge in PHP, write back is a lost-update race: two concurrent syncs can both read the old state and the second save drops the first device's contribution until it syncs again. lockForUpdate() (or a single SQL UPDATE that merges in place) removes the race. See Laravel.

10 — A product owner wants a CRDT so that ticket sales never exceed capacity in any region. What do you answer? Must-know ​

Answer

Answer: Capacity is a global invariant; a CRDT cannot enforce it from local state (two replicas at 1 can both decrement). Use coordination for the sale (single owner per event, consensus) or escrow: give each region a quota of rights and coordinate only to rebalance. A CRDT can still serve the displayed "tickets left" estimate. See Limitations.

11 — Is Figma's multiplayer a CRDT system? Good to know ​

Answer

Answer: Figma says it is "inspired by" CRDTs but "isn't using true CRDTs": the server is the central authority that orders property changes (like an LWW-Register without timestamps), object existence is LWW-like, and children are ordered with fractional indexing. See CRDT vs OT and In production.

Glossary ​

TermMeaning
CRDT (conflict-free replicated data type)Data type whose replicas update without coordination and provably converge
Strong eventual consistency (SEC)Replicas that delivered the same updates have equivalent state
ConvergenceReplicas reaching the same state
State-based CRDT (CvRDT)Replicas exchange states and merge with a join
Operation-based CRDT (CmRDT)Replicas exchange operations; concurrent operations commute
Delta-state CRDTState-based CRDT that ships small delta-states produced by delta mutators
Delta mutatorUpdate function that returns the delta-state it produced
Join-semilatticePartial order where every pair has a least upper bound
Least upper bound (join)Smallest state greater than or equal to both inputs: the merge
MergeThe function that combines two replica states
CommutativeOrder of arguments does not matter: a merge b = b merge a
AssociativeGrouping does not matter: (a merge b) merge c = a merge (b merge c)
IdempotentRepeating does not matter: a merge a = a
MonotonicUpdates never move the state down the order
Causal deliveryOperations delivered after everything they depend on, exactly once
Causal broadcastProtocol that provides causal delivery to all replicas
Version vector / vector clockPer-replica counters that tell before, after or concurrent
Lamport timestampCounter that respects happened-before; with a replica ID gives unique, totally ordered IDs
Hybrid logical clock (HLC)Physical time plus logical counter, respecting causality
Dot(replica, counter) pair naming one event; a cheap unique tag
Unique tagIdentifier attached to each add in an OR-Set
Causal contextVersion vector of all dots a state has seen; lets an OR-Set remember removals
G-CounterGrow-only counter: per-replica slots, max-merge, sum
PN-CounterPair of G-Counters for increments and decrements
LWW-RegisterRegister where the larger timestamp wins
MV-RegisterRegister keeping all concurrent values (siblings)
SiblingsConcurrent values kept side by side for the reader to resolve
G-SetGrow-only set, merge by union
2P-SetAdd set plus remove (tombstone) set; remove wins; no re-add
U-Set2P-Set with unique elements (Wuu and Bernstein's construct)
LWW-Element-SetSet with a timestamp per add and remove; latest wins
OR-Set (observed-remove set)Set where a remove deletes only the add tags it observed
ORSWOTOR-Set without tombstones: dots plus causal context (Riak)
Add-winsConcurrent add and remove: element present
Remove-winsConcurrent add and remove: element absent
OR-MapMap with OR-Set keys and CRDT values
FlagBoolean CRDT (enable-wins or disable-wins)
Sequence CRDTCRDT for ordered lists and text
RGA (Replicated Growable Array)Sequence CRDT inserting after an anchor, ordering concurrent inserts by ID
WOOTFirst sequence CRDT; inserts between two neighbours
TreedocSequence CRDT using paths in a binary tree as positions
LogootSequence CRDT with dense position identifiers
LSEQLogoot variant with adaptive identifier allocation
YATAList CRDT behind Yjs (origin and right origin per item)
YjsJavaScript CRDT framework with shared types and editor bindings
State vectorYjs's per-client clock summary used to compute missing updates
AutomergeJSON-like CRDT library with a Rust core and history
Fugue / FugueMaxList CRDTs minimising interleaving; FugueMax proven maximally non-interleaving
PeritextCRDT for rich-text formatting spans
JSON CRDTCRDT for nested maps and lists (Kleppmann and Beresford)
TombstoneMarker kept for a deleted element or key
Garbage collectionDiscarding metadata that no future operation can need
Causal stabilityAn update is stable when all concurrent updates have been delivered everywhere
Stability frontierEntry-wise minimum of all replicas' delivered vectors
Interleaving anomalyConcurrent inserted runs mixed character by character
Intent preservationEach user's edit has its intended effect after the merge
Operational transformation (OT)Transforming index-based operations against concurrent ones
Fractional indexingOrdering items by a fraction between neighbours (Figma)
Global invariantA property that depends on all replicas' updates (balance at least zero)
Escrow / bounded counterPre-allocated rights to decrement per replica to keep a bound
Byzantine faultA replica that deviates arbitrarily or maliciously from the protocol
Local-firstSoftware where the device's copy is primary and sync is secondary
Riak data typesRiak KV's counters, sets, maps, registers, flags, HyperLogLogs
Redis CRDB / Active-ActiveRedis Enterprise's CRDT-based multi-primary geo-replication
Akka Distributed DataAkka's replicated data types over cluster gossip
RoshiSoundCloud's LWW-element-set over Redis, in Go
AntidoteDBGeo-replicated CRDT database with highly available transactions
Figma multiplayerFigma's server-ordered, CRDT-inspired collaboration system

References ​

Built by Morteza Negahi