Low-overhead counter and latency-sample store for SuperCache observability.
All state is held in a single :public ETS table owned by this GenServer.
Writes use update_counter/3 (atomic) and are safe to call from any
process without coordination overhead.
Counter keys
Counters are stored as {namespace, field} tuples:
{:tpc, :committed}
{:tpc, :aborted}
{:api, :put}, :calls} # note: nested via get_all/1
{{:api, :put}, :errors}Latency samples
Latency samples use a fixed-size ring buffer written directly by the
caller — push_latency/2 performs one atomic counter update and one
:ets.insert/2, with no GenServer message and no intermediate list
allocation. Each key stores at most 256 samples in slots
keyed {:latency, key, slot}; the oldest slot is overwritten when the
ring wraps, so memory per key is constant regardless of call volume.
Concurrent writers are safe: sequence numbers come from
:ets.update_counter/4, so each sample lands in its own slot and the
buffer never grows past the cap. A write that races with another may
overwrite a slot, which only drops a sample; it cannot corrupt counters
or produce unbounded state.
get_latency_samples/1 returns the retained values newest-first.
Usage
# In Router / Replicator — after an operation completes:
Metrics.increment({:api, :put}, :calls)
Metrics.push_latency({:api_latency_us, :put}, elapsed_us)
# Reading back:
Metrics.get_all({:api, :put})
# => %{calls: 1_200, errors: 2}
Metrics.get_latency_samples({:api_latency_us, :put})
# => [45, 110, 88, ...]
Summary
Functions
Returns a specification to start this module under a supervisor.
Return all counters for namespace as %{field => count}.
Uses compiled match spec for better performance.
Return all retained latency samples for key, newest first.
Atomically increment counter field under namespace by amount (default 1).
Push a latency sample (microseconds) into the ring buffer for key.
Reset all counters and latency samples for namespace.
Uses compiled match specs for better performance.
Functions
Returns a specification to start this module under a supervisor.
See Supervisor.
Return all counters for namespace as %{field => count}.
Uses compiled match spec for better performance.
@spec get_latency_samples(term()) :: [non_neg_integer()]
Return all retained latency samples for key, newest first.
Atomically increment counter field under namespace by amount (default 1).
@spec push_latency(term(), non_neg_integer()) :: :ok
Push a latency sample (microseconds) into the ring buffer for key.
The sample is written synchronously by the calling process. The buffer is capped at 256 entries; oldest samples are dropped when the cap is reached.
@spec reset(term()) :: :ok
Reset all counters and latency samples for namespace.
Uses compiled match specs for better performance.