CRDTs in Go: Merging Replicas Without Conflicts
November 19, 2026 · 9 min read · Lire en français
Contents
Two servers must end up with identical data. While users are writing, they do not talk to each other. The messages between them arrive late, out of order, or twice. And neither server may ask the other for permission or elect a leader first.
That sounds impossible, and for arbitrary data and arbitrary updates there is no such guarantee. But for data built in a particular way, a short argument proves it works. This article shows that argument, three equations about a merge function, and four small data types in Go that satisfy it: CRDTs, Conflict-free Replicated Data Types. It is the third in a series on the math inside distributed systems, and it picks up where the vector clocks article stopped: the component-wise maximum used to merge clocks is exactly the operation these types are built on.
The math: three laws and a semilattice
Replicas converge by exchanging their state and merging it. Call the merge operation ⊔ (read "join"). It takes two states and returns one. For replicas to agree no matter what the network does, ⊔ must obey three laws:
- Commutative:
a ⊔ b = b ⊔ a. The order of the two inputs does not matter. - Associative:
(a ⊔ b) ⊔ c = a ⊔ (b ⊔ c). The grouping does not matter. - Idempotent:
a ⊔ a = a. Merging the same state twice changes nothing.
Together they are called ACI. Each one answers a specific network fault: commutativity and associativity absorb reordering, idempotence absorbs duplicate delivery. To see that none is optional, here is a plausible merge rule that breaks each law:
| Merge rule | Law it breaks | What goes wrong |
|---|---|---|
| Add the two counters | Idempotent | A state delivered twice is counted twice. In my test a counter that should read 3 read 4. |
| "Take the incoming value" | Commutative | A merging B gives B, B merging A gives A. The replicas swap values and never agree. |
| Average the two values | Associative | (0 ⊔ 4) ⊔ 8 = 5 but 0 ⊔ (4 ⊔ 8) = 3. The result depends on delivery grouping. |
Why ACI means convergence
A set of states with a merge that obeys ACI has a name: a join-semilattice. Equivalently, it is a set with a partial order ≤ (the same kind of order as in the vector clocks article) in which any two elements a and b have a least upper bound, the smallest state that is above both. That bound is a ⊔ b, and a ≤ b simply means a ⊔ b = b.
Picture a hill. Every state sits somewhere on it, updates can only move a state up, and merging two states takes you to the lowest point that is above both. Now take any set of updates. Whatever order or grouping the network delivers them in, and however many times, every replica that has seen all of them ends up at the same place: the least upper bound of everything. That is the whole proof of convergence, and it is why this is called strong eventual consistency: replicas that received the same updates are in the same state, with no coordination.
There is one design constraint hiding in the picture: local updates must only move up. A state may never go down. This is why the data types below look slightly odd, and decrementing a counter will need a trick.
G-Counter: a counter that only grows
Give each replica its own slot. A replica only ever increments its own slot. The value is the sum of all slots, and merging takes the maximum of each slot.
type GCounter map[string]uint64
func (g GCounter) Inc(id string) { g[id]++ }
func (g GCounter) Value() (s uint64) {
for _, x := range g {
s += x
}
return
}
// Merge is the join: component-wise max.
func (g GCounter) Merge(o GCounter) {
for k, v := range o {
if v > g[k] {
g[k] = v
}
}
}
Why max and not a sum? Because each slot only grows, so a larger value is simply a more recent view of the same slot, and max is commutative, associative and idempotent. Delivering the same state twice is harmless. This is the same operation as the vector clock merge, and for the same reason.
PN-Counter: decrementing without going down
A counter that supports Dec seems to break the "only up" rule. The trick is not to lower anything: keep two G-Counters, P for increments and N for decrements, and report P − N. Each of the two only grows, so the pair still lives on a hill.
type PNCounter struct{ P, N GCounter }
func (c *PNCounter) Inc(id string) { c.P.Inc(id) }
func (c *PNCounter) Dec(id string) { c.N.Inc(id) }
func (c *PNCounter) Value() int64 { return int64(c.P.Value()) - int64(c.N.Value()) }
func (c *PNCounter) Merge(o *PNCounter) { c.P.Merge(o.P); c.N.Merge(o.N) }
The merge of a pair is just the merge of each part, which keeps ACI for free. Remember this pattern, since it is the standard way to build a bigger CRDT: combine smaller CRDTs and merge component by component.
LWW-Register: pick a winner
For a single value (a username, a setting), the usual rule is last writer wins. Attach a timestamp to each write, and merge by keeping the write with the larger one. If two timestamps tie, break the tie with the replica id, so the order is total and max is well defined.
type LWW struct {
Val string
Ts uint64
Node string // tie-break
}
func (r *LWW) Merge(o LWW) {
if o.Ts > r.Ts || (o.Ts == r.Ts && o.Node > r.Node) {
*r = o
}
}
max over a total order satisfies ACI, so replicas converge. But convergence is not the same as being right. Two users write concurrently with the same timestamp, alice on replica A and bob on B. After merging, both replicas hold bob, and alice's write has silently vanished. It is also only as trustworthy as its timestamps, which brings back the problem of the previous article: with wall clocks, a skewed server can win every conflict. Use logical or hybrid clocks if the loss matters.
OR-Set: a set that handles add and remove
A set looks easy, but concurrent add(x) and remove(x) is a real conflict. If the merge is a plain union of elements, a removal is undone by any replica that still has x. If we track removals as a second set, an element can never be added back.
The observed-remove set fixes this by tagging. Every Add creates a unique tag (replica id plus a local counter). Remove does not delete the element: it records the tags this replica has seen for it as tombstones. An element is present if at least one of its tags is not tombstoned. Merging is a union of all adds and a union of all tombstones, and both are grow-only sets, so merge is ACI.
type Tag string
type ORSet struct {
Adds map[string]map[Tag]struct{} // element -> tags that added it
Tombs map[Tag]struct{} // removed tags
n uint64
}
func (s *ORSet) Add(id, e string) {
s.n++
t := Tag(fmt.Sprintf("%s:%d", id, s.n))
if s.Adds[e] == nil {
s.Adds[e] = map[Tag]struct{}{}
}
s.Adds[e][t] = struct{}{}
}
// Remove tombstones only the tags this replica has observed.
func (s *ORSet) Remove(e string) {
for t := range s.Adds[e] {
s.Tombs[t] = struct{}{}
}
}
func (s *ORSet) Has(e string) bool {
for t := range s.Adds[e] {
if _, dead := s.Tombs[t]; !dead {
return true
}
}
return false
}
The behaviour on a concurrent add and remove is the interesting part. Replica 1 and replica 2 both hold milk. Replica 1 removes it while replica 2 adds it again with a new tag that replica 1 has never seen. After merging, replica 1's tombstones cover the old tag only. The new tag is alive, so milk is in the set on both replicas. This is add-wins semantics: a removal can only cancel what it had observed. It is a choice, and a remove-wins variant exists. The point is that the choice is explicit and deterministic.
Checking convergence
The argument is clean, so it deserves a brute-force test. Take 10,000 random executions with 3 replicas and 60 steps each. Every step applies a random update (increment, decrement, write, add, remove) at a random replica, and sometimes takes a snapshot of a replica and puts it on a pretend network. Snapshots are then delivered to random replicas at random times, so they arrive stale, duplicated and out of order. At the end every replica merges every snapshot, twice, in a random order.
Over 1.57 million merges, all four types (G-Counter, PN-Counter, LWW-Register, OR-Set) converged to identical state on all three replicas in 10,000 of 10,000 runs. A separate check of the three laws on 10,000 random triples of G-Counters passed every time. This tests that order and duplication do not matter, which is the guarantee being claimed. It does not test that an intermediate state is meaningful, only that the replicas end up agreeing.
Limits
- State grows. A G-Counter keeps a slot per replica forever, and an OR-Set keeps every tombstone. Removing them safely needs agreement that every replica has seen a removal, which is coordination again.
- Invariants need coordination. A PN-Counter can go negative when two replicas each approve a withdrawal against the same balance. CRDTs guarantee convergence, not rules like "never below zero" or "usernames are unique". Those need coordination, which is the trade-off the CAP theorem describes.
- Semantics are choices. LWW loses a write, the OR-Set favours adds. Convergence tells you replicas agree, not that they agree on what you wanted.
- State-based vs operation-based. This article ships whole states. Operation-based and delta CRDTs ship much less, at the price of requiring more from the network.
- Where they run. Riak's data types, Redis Enterprise's Active-Active databases, and collaborative editing libraries such as Yjs and Automerge are all built on CRDTs.
Takeaways
- Replicas converge without coordination if the merge
⊔is commutative, associative and idempotent (ACI). Each law covers a network fault: reordering, regrouping, duplication. - ACI makes the states a join-semilattice: updates move states up, and merge goes to the least upper bound, so replicas that saw the same updates agree.
- Local updates must only move up. That is why a PN-Counter is two grow-only counters, and why you combine small CRDTs component by component.
- The component-wise max of the vector clocks article is the same join that powers the G-Counter.
- Convergence is not correctness. LWW can lose a write, the OR-Set favours adds, and invariants such as "balance at least zero" still need coordination.
Next in the series: gossip protocols, and how a rumor reaches every node in logarithmic time.
Subscribe to future posts
Get future posts in your inbox. No spam, unsubscribe any time.
Related posts
Gossip Protocols in Go: Why a Rumor Reaches Every Node in Logarithmic Time
One node learns something and no one is in charge. Each round, every node talks to one random peer. The news reaches 100,000 nodes in about 29 rounds, or 14 with a better exchange rule. We derive why with a few lines of math (doubling, then a tail that behaves very differently for push and pull), then check every formula against a Go simulation.
November 23, 2026
Lamport and Vector Clocks in Go: Ordering Events Without a Shared Clock
Two servers write the same key and your logs say one came 3 ms before the other. Can you trust that? Not without a shared clock. We build Lamport and vector clocks in Go, explain the small amount of math behind them (partial orders, the happened-before relation, component-wise comparison), and test both against 6.7 million event pairs to see exactly what each one can and cannot tell you.
November 14, 2026
Consistent Hashing in Go: Why hash(key) % N Breaks and How a Ring Fixes It
Add one server to a cache cluster that uses hash(key) % N and about 91% of your keys change owner overnight. Consistent hashing cuts that to roughly K/N. We build the ring in Go, add virtual nodes, and measure real remapping and load balance, including the hash function mistake that quietly wrecks it.
November 9, 2026