Hello, world: a counter that merges without coordination

The first post: a grow-only counter CRDT in Go and Postgres, why its merge never loses an increment, and a demo you can click through.

This blog is about Postgres internals, distributed systems, CRDTs, Go performance and infrastructure. The first post is a small example from the middle of that list: a counter that two replicas can update without talking to each other, and that still adds up once they do.

Why last-writer-wins loses increments

Link to section: Why last-writer-wins loses increments

If each replica stores the count as one number, a merge has to pick one of the two numbers, and the increments behind the other one are gone. Last-writer-wins picks the most recent write.

Say replica A counts 3 page views and replica B counts 2 while the network between them is down. When they reconnect, last-writer-wins keeps whichever number was written last, 3 or 2. The real total is 5.

Approach State per replica Merge Result after the example
Last writer wins One number Keep the newer number 3 or 2
Sum on merge One number Add both numbers 5, then 10 after a retry
Grow-only counter (G-Counter) One count per replica Keep the larger count per replica 5, however often it runs

Adding the numbers fixes the example and breaks the next one: a retried sync adds the same increments twice. The merge needs to be safe to repeat.

A grow-only counter stores a count for every replica, and each replica only ever increments its own. Its value is the sum of those counts.

gcounter.go
package gcounter
// Counter is a grow-only counter: one count per replica.
type Counter map[string]uint64
// Inc adds n to this replica's own count.
func (c Counter) Inc(replica string, n uint64) {
c[replica] += n
}
// Value is the sum of every replica's count.
func (c Counter) Value() uint64 {
var sum uint64
for _, n := range c {
sum += n
}
return sum
}
// Merge keeps the larger count for each replica.
func Merge(a, b Counter) Counter {
out := make(Counter, len(a))
for id, n := range a {
out[id] = n
}
for id, n := range b {
out[id] = max(out[id], n)
}
return out
}

The merge takes the larger count for each replica, and the maximum doesn’t care about order, grouping or repetition. In the paper’s terms the merge is commutative, associative and idempotent, which makes the counter a state-based CRDT11 Marc Shapiro, Nuno Preguiça, Carlos Baquero and Marek Zawirski, “Conflict-free Replicated Data Types”, SSS 2011. The Wikipedia article is a good overview of the other types.. Replicas can sync in any order, any number of times, and still end up equal.

Those three laws are cheap to test:

gcounter_test.go
func TestMerge(t *testing.T) {
a := Counter{"eu": 3, "us": 1}
b := Counter{"eu": 2, "us": 4}
c := Counter{"ap": 5}
t.Run("commutative", func(t *testing.T) {
if !maps.Equal(Merge(a, b), Merge(b, a)) {
t.Fatal("merge(a, b) != merge(b, a)")
}
})
t.Run("associative", func(t *testing.T) {
if !maps.Equal(Merge(Merge(a, b), c), Merge(a, Merge(b, c))) {
t.Fatal("grouping changed the result")
}
})
t.Run("idempotent", func(t *testing.T) {
if !maps.Equal(Merge(a, a), a) {
t.Fatal("merging with itself changed the counter")
}
})
t.Run("keeps every increment", func(t *testing.T) {
if got := Merge(a, b).Value(); got != 7 {
t.Fatalf("value = %d, want 7", got)
}
})
}
Terminal window
go test -v ./...
Output of go test -v: TestMerge and its four subtests, commutative, associative, idempotent and keeps every increment, all pass.
All four subtests pass on Go 1.24.

Tip

A grow-only counter can’t go down. For a counter that also decrements, keep two of them, one for increments and one for decrements, and subtract. That pair is called a PN-Counter.

The same merge works as an upsert: one row per counter and replica, and a conflict keeps the larger count. The value is the sum of the rows.

schema.sql
CREATE TABLE counter_replicas (
counter_id text NOT NULL,
replica_id text NOT NULL,
count bigint NOT NULL CHECK (count >= 0),
PRIMARY KEY (counter_id, replica_id)
);
SELECT sum(count) AS value
FROM counter_replicas
WHERE counter_id = 'page-views';

Moving from last-writer-wins to the counter is a one-line change in the merge query:

merge.sql
INSERT INTO counter_replicas (counter_id, replica_id, count)
VALUES ('page-views', 'eu-1', 42)
ON CONFLICT (counter_id, replica_id)
DO UPDATE SET
count = EXCLUDED.count;
count = GREATEST(counter_replicas.count, EXCLUDED.count);

Warning

The upsert is only a merge if every writer sends its replica’s full count. Sending a delta, such as “add 1”, turns it back into sum on merge, and retries count twice. See INSERT ... ON CONFLICT for how the conflict target is matched.

Add on either replica, then merge. The counter keeps every increment; the plain number keeps only the last replica that wrote.

Each replica's grow-only counter
ReplicaCount for ACount for BValue
A000
B000

Merged now, the counter reads 0. A single number where the last write wins would read 0.

Footnotes

  1. Marc Shapiro, Nuno Preguiça, Carlos Baquero and Marek Zawirski, “Conflict-free Replicated Data Types”, SSS 2011. The Wikipedia article is a good overview of the other types. ↩