distkit
Counters

StrictCounter

Atomic, immediately consistent distributed counting.

StrictCounter executes every operation as an atomic Lua script on Redis. One call is one round-trip, and the stored value is always authoritative - a get reflects every inc from every instance.

Use it when accuracy is non-negotiable: billing, inventory, quotas.

Construct

use distkit::{DistkitRedisKey, counter::{CounterOptions, StrictCounter, CounterTrait}};

let prefix = DistkitRedisKey::try_from("my_app".to_string())?;
let counter = StrictCounter::new(CounterOptions::new(prefix, conn));

new returns Arc<StrictCounter>, so you can clone it across tasks freely.

The basics

let key = DistkitRedisKey::try_from("orders".to_string())?;

counter.inc(&key, 1).await?;    // HINCRBY via Lua; returns the new value
counter.dec(&key, 1).await?;    // decrement; returns the new value
counter.get(&key).await?;       // current value
counter.set(&key, 100).await?;  // overwrite; returns the new value
counter.del(&key).await?;       // remove the entry; returns the old value
counter.clear().await?;         // remove every key under this counter's prefix

Every method comes from CounterTrait, so keep the trait in scope.

Conditional and batch

StrictCounter supports conditional writes (inc_if, set_if) and batch operations (inc_all, get_all, and the *_if forms), all atomic. They are covered in Conditional & batch operations.

Cost

The trade-off is one Redis round-trip per call. If you are incrementing thousands of times a second per key and can tolerate a small lag, LaxCounter does the same work with batched I/O.