Instance-aware counters
Overview
Counters where each instance owns a slice of the total, with automatic cleanup of dead instances.
Instance-aware counters track each running instance's contribution separately. The cumulative total is the sum of all live instances. When an instance stops heartbeating for longer than dead_instance_threshold_ms (default 30 s), its slice is automatically removed from the cumulative the next time any surviving instance touches the same key.
They live behind the instance-aware-counter feature:
[dependencies]
distkit = { version = "0.5", features = ["instance-aware-counter"] }
When they fit
- Connection pool sizing - each server reports its own active connections; the cumulative is the cluster-wide total.
- Live session counting - a node's contribution disappears on its own when it restarts or crashes.
- Per-node metrics - you can see both the global total and each instance's individual slice.
The shape of every call
Operations return a pair (cumulative, instance_count) - the global total and this instance's own slice:
let (total, mine) = counter.inc(&key, 5).await?;
Each instance is assigned a UUID on construction, readable via instance_id().
The two variants
StrictInstanceAwareCounter- every call is immediately consistent.LaxInstanceAwareCounter-inc/decbuffer locally and flush on an interval.
Both implement InstanceAwareCounterTrait.
Conditional writes
The same comparator model applies, with one nuance:
inc_if/set_ifcompare against the cumulative total.set_on_instance_ifcompares against this instance's slice.- A failed comparison returns the current
(cumulative, instance_count)unchanged.

