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 incrementsIf 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 in Go
Link to section: A grow-only counter in GoA 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.
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}Why taking the maximum is safe
Link to section: Why taking the maximum is safeThe 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:
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) } })}go test -v ./...
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.
Storing the counter in Postgres
Link to section: Storing the counter in PostgresThe 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.
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 valueFROM counter_replicasWHERE counter_id = 'page-views';Moving from last-writer-wins to the counter is a one-line change in the merge query:
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.
Try it
Link to section: Try itAdd on either replica, then merge. The counter keeps every increment; the plain number keeps only the last replica that wrote.
| Replica | Count for A | Count for B | Value |
|---|---|---|---|
| A | 0 | 0 | 0 |
| B | 0 | 0 | 0 |
Merged now, the counter reads 0. A single number where the last write wins would read 0.
Footnotes
-
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. ↩