ckms #
Streaming quantiles with targeted error bounds, in pure OCaml.
A service that reports its p50, p90 and p99 latency cannot keep every request
time it has ever seen, and a fixed-bucket histogram only gives quantiles as
precise as its buckets. ckms implements the algorithm of Graham Cormode, Flip
Korn, S. Muthukrishnan and Divesh Srivastava for biased quantiles over data
streams (ICDE 2005), which Prometheus summaries also use. Each quantile of
interest is registered with a permitted rank error, for example p99 within
0.1%. The rank of a value is its position among the observations in sorted
order, so after n observations a query for quantile φ with error ε returns a
value whose rank lies between (φ − ε)n and (φ + ε)n. For p99 within 0.1% and a
million observations, that is one of the values ranked 989,000 to 991,000:
the bound is on the position, not on the distance in milliseconds.
The estimator keeps a sorted list of tuples (v, g, Δ): an observed value v,
the gap g between its lowest possible rank and the previous tuple's, and the
uncertainty Δ of its rank. Every 128 insertions it merges a tuple into its
neighbour while g + Δ stays within f(r, n), the minimum over the targets of
2εr/φ when the rank r is at least φn and 2ε(n − r)/(1 − φ) below it. Near a
target the band is 2εn ranks wide and it widens linearly away from it, so
the list holds few tuples where no target asks for precision. On the streams
the paper measures, its size s grows far more slowly than n, but the paper
proves no worst-case bound on s for targeted quantiles. An insertion walks the
list to its rank, so it costs O(s), and a compression pass every 128
insertions costs O(s) as well.
Ckms.Sliding reports quantiles over a sliding time window, as a Prometheus
summary does, so that a latency spike fades from the p99 once it is older than
the window. The clock is passed in as a function, so the estimator does no I/O
and tests can drive time by hand.
Installation #
$ opam install ckms
If opam cannot find the package, it may not yet be released in the public
opam-repository. Add the overlay repository, then install it:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install ckms
API #
Ckms.v targetscreates an estimator for a list of
{ quantile; error }targets.Ckms.insertrecords an observation, andCkms.query t qreturns the
estimated value at quantileq(nanbefore the first observation).Ckms.count,Ckms.targetsandCkms.resetreturn the number of
observations and the targets, and clear the observations.Ckms.Sliding.v ~now ?max_age ?age_buckets targetscreates a windowed
estimator overmax_ageseconds (600 by default), rotated inage_buckets
steps (5 by default), withobserve,queryandcount.
An estimator is mutable and must not be used from several domains at once.
lib/ckms.mli documents the full interface.
Licence #
ISC. See LICENSE.md.