Explain CRDTs in one paragraph, then show a tiny G-Counter in Rust.

Claude Code 4 turns Never disappears

User

Explain CRDTs in one paragraph, then show a tiny G-Counter in Rust.

Assistant

A CRDT (Conflict-free Replicated Data Type) is a data structure designed for distributed systems where replicas can update independently and concurrently without coordination, then merge into a consistent state. The trick is that all operations are commutative, associative, and idempotent — so it doesn't matter in what order or how many times merges happen.

A G-Counter (grow-only counter) is the canonical state-based CRDT:

use std::collections::HashMap;

#[derive(Default, Clone)]
struct GCounter {
    counts: HashMap<String, u64>,
}

impl GCounter {
    fn inc(&mut self, node: &str) {
        *self.counts.entry(node.into()).or_insert(0) += 1;
    }
    fn value(&self) -> u64 {
        self.counts.values().sum()
    }
    fn merge(&mut self, other: &GCounter) {
        for (k, v) in &other.counts {
            let e = self.counts.entry(k.clone()).or_insert(0);
            *e = (*e).max(*v);
        }
    }
}

Merging is just the pointwise max of each node's local count — which is commutative, associative, and idempotent.

User

Why pointwise max and not pointwise sum?

Assistant

Because each node only ever increments its own slot. If you summed slots during merge, you'd double-count: node A's slot already contains everything A has ever counted, and merging A's view of A with B's view of A should give the latest value A reported, not the sum of the two views.

Outline4 turns

  1. Explain CRDTs in one paragraph, then show a tiny G-Counter in Rust.
  2. A **CRDT** (Conflict-free Replicated Data Type) is a data structure designed fo…
  3. Why pointwise max and not pointwise sum?
  4. Because each node only ever *increments its own slot*. If you summed slots duri…

Ask

TL;DR

Listen6 passages

Read aloud in your browser, a different voice per speaker. Code blocks are announced rather than spelled out.

Not playing

Code

Continue

Copy the whole conversation plus a continue-here instruction, ready to paste into another assistant.

Compare