Skip to content

lattice / field guide

Counters

Using GCounter and PNCounter for distributed counting.

Counters are provided by the lattice_counters package. If you installed the lattice_crdt umbrella, they are already available.

Use counters when replicas need to accumulate numeric state and later merge without coordination.

GCounter is grow-only. Each replica can increase its own contribution, and merge takes the per-replica maximum before summing the result.

import lattice_core/replica_id
import lattice_counters/g_counter
pub fn main() {
let assert Ok(left) =
g_counter.new(replica_id.new("node-a"))
|> g_counter.increment(2)
let assert Ok(right) =
g_counter.new(replica_id.new("node-b"))
|> g_counter.increment(5)
let merged = g_counter.merge(left, right)
g_counter.value(merged)
// -> 7
}

g_counter.increment returns Result. A negative delta returns Error(NegativeDelta(delta)) without changing the counter. Handle this error when amounts come from external input; the examples assert known positive values.

PNCounter supports both increments and decrements by pairing two internal GCounters.

import lattice_core/replica_id
import lattice_counters/pn_counter
pub fn main() {
let assert Ok(counter) =
pn_counter.new(replica_id.new("node-a"))
|> pn_counter.increment(10)
let assert Ok(counter) = pn_counter.decrement(counter, 3)
pn_counter.value(counter)
// -> 7
}

Both pn_counter.increment and pn_counter.decrement require non-negative deltas. To subtract 3, call pn_counter.decrement(counter, 3) rather than passing -3. Both operations return Result, including their delta variants.

Counters also expose delta-aware mutators:

  • g_counter.increment_with_delta
  • pn_counter.increment_with_delta
  • pn_counter.decrement_with_delta

Each returns Ok(#(new_state, delta)) or a typed error. Remote replicas apply the delta with the existing merge function. See Delta-State Replication for the shared convention.

The former try_increment, try_decrement, and corresponding delta names have been replaced by the plain Result-returning names.