Functional Weave
Code in TypeScript

monitor.counter-increase@1.0.0

README.md

2,174 bytes · view raw

# monitor.counter-increase

How much a counter (requests served, bytes sent, errors) grew over a series
of samples, and its average rate per second. Counters only go up, except when
the process that owns them restarts and they begin again at zero.

## Counter resets

The rule is Prometheus's: any drop between two consecutive samples means the
counter restarted from zero, so the new value is all increase. Samples
100, 160, 20, 50 grew by 60, then 20 (the restart), then 30: 110, with one
reset. `last - first` would say -50.

A restart the samples never see is invisible: if a counter at 100 restarts and
climbs past 100 before the next sample, the growth before the restart is lost.
MetricSample more often than restarts happen.

## No extrapolation

Prometheus's `increase()` and `rate()` extrapolate from the first and last
samples out to the edges of the query window, which is why they return
fractional increases for a counter of whole requests. This function does not:
the increase is exactly what the samples show between the first and the last,
and the rate is that increase over `lastAt - firstAt`. Pass the samples of the
window you care about (`monitor.series-window` picks them).

`ratePerSecondMilli` is `increase * 1000 / (lastAt - firstAt)` rounded half
up, so 1.25 requests a second is 1250. It is null with fewer than two samples,
where there is no interval. The multiplication is done in exact integer
arithmetic (BigInt, i128), so a byte counter in the trillions still rounds
correctly.

## Errors

- `samples must be in strictly ascending time order: 10 follows 10`
- `counter value must not be negative: -1 at 10`

## Sources

- Prometheus, Query functions, `resets()`: "Any decrease in the value between
  two consecutive float samples is interpreted as a counter reset"; `increase()`:
  "The increase is extrapolated to cover the full time range as specified in
  the range vector selector",
  https://prometheus.io/docs/prometheus/latest/querying/functions/
- Prometheus, Metric types: Counter ("a cumulative metric ... whose value can
  only increase or be reset to zero on restart"),
  https://prometheus.io/docs/concepts/metric_types/#counter