Metrics / Aggregates
Aggregates
aggregate cuts a range into buckets of every and answers each with one
exact value: an increase, a rate, an average, a percentile. It is what a
dashboard draws: requests per minute by route, the p95 latency of each five
minutes, the average queue depth of each hour.
const { groups: traffic } = await store.metrics.aggregate({
name: 'http_requests_total',
since: '24h',
every: '1h',
op: 'increase',
by: ['route'],
})
// [{ name, labels: { route: '/notes' }, buckets: [{ at, value: 1840, samples: 240, resets: 0 }, …] }, …]
const { groups: p95 } = await store.metrics.aggregate({ name: 'http_request_ms', since: '1h', every: '5m', op: 'p95' })
// [{ name, labels: {}, buckets: [{ at, lower: 25, upper: 50, samples: 3812 }, …] }]traffic = (await store.metrics.aggregate(name="http_requests_total", since="24h", every="1h", op="increase", by=["route"])).groups
p95 = (await store.metrics.aggregate(name="http_request_ms", since="1h", every="5m", op="p95")).groupstraffic, err := metrics.Aggregate(ctx, store, metrics.Query{Name: "http_requests_total", Since: 24 * time.Hour,
Every: time.Hour, Op: metrics.Increase, By: []string{"route"}})
p95, err := metrics.Aggregate(ctx, store, metrics.Query{Name: "http_request_ms", Since: time.Hour, Every: 5 * time.Minute, Op: metrics.Percentile(95)})let stats = store.metrics()?;
let traffic = stats
.query()
.name("http_requests_total")
.since(Duration::from_hours(24))
.every(Duration::from_hours(1))
.by(&["route"])
.aggregate(Op::Increase)?.groups;
let p95 = stats.query().name("http_request_ms").since(Duration::from_hours(1)).every(Duration::from_mins(5)).aggregate(Op::Percentile(95.0))?.groups;A total for a range
Without every the range is one bucket, so a total for the range is one
call, one bucket a group:
const { groups } = await store.metrics.aggregate({ name: 'calls', since: '30d', op: 'increase' })
const calls = groups[0]?.buckets[0]?.value // calls in 30 days, with no buckets to sumgroups = (await store.metrics.aggregate(name="calls", since="30d", op="increase")).groups
calls = groups[0].buckets[0].value if groups else NoneOps
op | Of | A bucket's answer |
|---|---|---|
count | any | how many samples; a timer's, how many durations |
sum, avg | a gauge, a timer | their exact sum; that over their count |
min, max | a gauge; max of a timer | the least and greatest sample; a timer's longest |
increase | a counter | how much it grew, resets counted |
rate | a counter, a timer | that a second of the bucket |
delta | a gauge | its last sample less the one before its first |
first, last | a gauge, a counter | the bucket's first and last sample, bit for bit |
p50, p95 … | a gauge, a timer | a gauge's sample at that rank; a timer's bucket holding it, lower to upper |
Every value is exact and rounded once: a sum is the exact sum of its samples, rounded to the nearest float, whatever order or blocks they were kept in.
Buckets add up to the range
Buckets are spans of every counted from 1970 in UTC, so 1h buckets begin
on the hour. An increase, a rate and a delta count each step between two
samples in the bucket where the step ends, and the first bucket takes its step
from the newest sample before the range:
a counter growing by 1 a second, sampled every 15 s, read 10:00 to 11:00
1h buckets 3600
5m buckets 300 + 300 + 300 + … + 300 = 3600
1m buckets 60 + 60 + 60 + … + 60 = 3600Buckets of any width add up to the range, and two adjacent ranges to the
range they make. Nothing is interpolated or extrapolated to a bucket's edges,
unlike Prometheus' increase, whose answer changes with the window.
Days in a time zone
A day of every: '1d' runs from midnight to midnight in UTC. A shop in
Moscow counts its orders from its own midnight, which is 21:00 in UTC. Ask
for buckets of the calendar instead, with the zone's IANA name:
const { groups: days } = await store.metrics.aggregate({ name: 'orders', since: '30d', op: 'sum', calendar: 'day', timeZone: 'Europe/Moscow' })days = (await store.metrics.aggregate(name="orders", since="30d", op="sum", calendar="day", time_zone="Europe/Moscow")).groupscalendarisday,weekormonth. A week begins on Monday, as ISO 8601 counts weeks, and a month on its first day, each at local midnight.- A bucket's
atis the instant its local day, week or month begins, and itsdatethe local date it begins on,'2026-11-19': a week's Monday, a month's first. A chart labels it withdateand does no zone math of its own. A bucket ofeveryhas nodate,every: '1d'included. dateis text in TypeScript, Go (Date) and Rust (aLocalDate, whoseto_string()is the text), and adatetime.datein Python.- A day is 23 or 25 hours long on the days the clock moves, and a month is as
long as it is. A
ratedivides by the seconds its bucket has. calendartakes a time zone, and goes in place ofevery. Both at once fail with an invalid error, and so does a zone no one has.
Partial buckets and gaps
| A bucket says | When | A chart |
|---|---|---|
partial: true | the range, the store's clock or retention cut it | shows it apart, or leaves the unfinished edge out |
gap: true | a whole bucket of every before it had no samples | shows a gap, or asks a wider every |
http_requests_total 100 on 1 October, nothing since, 300 at 11:59 on 11 October
11:00 to 12:00 { value: 200, gap: true }What a counter grew over a gap is counted in the bucket after it, since when
it grew is not known. A bucket without samples is left out of the answer,
unless the query asks fill.
Every bucket, with fill
A chart of errors by hour wants every hour of the day, the ones without
errors too. fill gives every bucket of the range:
const { groups } = await store.metrics.aggregate({ name: 'errors_total', since: '1d', every: '1h', op: 'increase', fill: true })
const hours = groups[0]?.buckets.map(hour => hour.value ?? 0) // 25 hours, an empty one drawn as 0groups = (await store.metrics.aggregate(name="errors_total", since="1d", every="1h", op="increase", fill=True)).groups
hours = [hour.value or 0 for hour in groups[0].buckets]- A bucket without samples comes with
samples: 0and novalue(Value::Emptyin Rust,nilin Go,Nonein Python). It is no zero: over an empty hour a counter's process may have been down, and what it grew then is counted in the next bucket that has samples, with itsgap. The chart picks its zero,hour.value ?? 0. In TypeScriptvalueis optional in the type of an aggregate givenfill: true. - The range is what retention leaves of it: nothing is filled before the
oldest time the name keeps. A bucket the range, the clock or retention cut
is
partial, as any bucket is. - A group without a sample in the range is still left out, since nothing
names it. Without
everyorcalendarthe range is one bucket, which a group has already. filltakessinceorfrom, since a range from 1970 has no first bucket to fill: without one it isinvalid. Withoutlimit, a range of more than 100,000 buckets a group is alimiterror before anything is read.- With
limit,fillworks in pages too, and the pages give the buckets one call gives. Therelimitcounts every bucket a page answers, the empty ones too, so a page oflimit: 1000holds 1000 buckets whether or not they have samples. This is the way to fill a year of minutes: 525,601 buckets in six pages oflimit: 100_000.
NaN from an exporter
A Prometheus summary writes NaN for a quantile while it has nothing to
measure, for example while a service is idle. An aggregate over a NaN fails
with an invalid error, so a panel of scraped quantiles stays empty for as long
as the range holds one. Pass skipNaN to skip those samples instead:
const { groups } = await store.metrics.aggregate({ name: 'rpc_seconds', since: '1h', every: '1m', op: 'avg', by: ['quantile'], skipNaN: true })
// [{ labels: { quantile: '0.5' }, buckets: [{ at, value: 0.21, samples: 3, skipped: 1 }, …] }, …]groups = (await store.metrics.aggregate(name="rpc_seconds", since="1h", every="1m", op="avg", by=["quantile"], skip_nan=True)).groups- A NaN counts in no bucket's value or
samples. Each bucket'sskippedsays how many NaN samples it skipped, so you can see what the value was computed from. - A bucket that holds only NaN samples has no value, so it is left out of the answer, as a bucket without samples is. It never becomes a zero.
- An infinity still fails with an invalid error, because it is a value and not a missing one.
- An
increase, arateor adeltasteps from the last sample before the NaN to the first one after it. If the samples that the store reads before the range are all NaN, the step into the first bucket is not known, and that bucket ispartial. - The samples are stored as they came, NaN included, and a read returns them bit for bit. Only the aggregate skips them.
- Without
skipNaN, nothing changes: a NaN fails the aggregate.
Percentiles
p95of a gauge is the sample at that rank, nearest rank: a value that was stored, exact.p95of a timer is the bucket of its spread that holds the rank:lowerandupper, both exact, and novalue, since any one number would be read as the percentile. Past the last boundupperisInfinity.estimate: trueaddsestimate, a point between them interpolated as Prometheus'histogram_quantiledoes, named so nobody takes it for a measurement.- A timer without
bucketshas no percentile:invalid, naming it. p50throughp99.9and any rank between;p99.9ranks at 999 in 1,000 exactly.
Five durations, 0.8, 41, 42, 43 and 44 ms, give these p95s, kept as a
gauge's samples or by a timer with the buckets [1, 5, 10, 25, 50]:
| Kept as | p95 |
|---|---|
| a gauge | value: 44 |
| a timer | lower: 25, upper: 50 |
a timer, estimate: true | lower: 25, upper: 50, estimate: 48.4375 |
| one 0.4 ms, in such a timer | lower: 0, upper: 1, estimate: 0.95 |
The gauge's is the sample at rank 5 of 5. The timer's rank 5 falls in the bucket from 25 to 50, and its estimate is 3.75 of that bucket's 4 samples into it; one duration below the first bound is somewhere from 0 to 1.
An estimate is only as close as the bounds around it: put bounds where the
answer matters, around the 50 ms a page must load in. A program that shows
one number shows value when there is one and the estimate, marked as one,
when there is not; in Go Value is nil for a timer's percentile, never 0.
Groups
Without by, every series of the name is one group and one answer. by keeps
the labels it names; without keeps all but those; without: [] keeps every
series apart.
Each series' bucket is computed exactly, then joined, and the group's value
rounded once: counts, sums and increases add; avg divides every sample's sum
by every sample's count, never averaging averages; p95 ranks every sample of
the group, or adds a timer's bucket counts before it ranks. last adds up
too: the last of several queues' depths is their total at the bucket's end.
So by merges series exactly, a timer's percentiles among them. A timer
labelled fn and cached grouped by: ['fn'] gives each function's p95
over its cached and uncached calls together, ranked over both spreads'
counts, which no weighting of two percentiles gives.
const { groups: backlog } = await store.metrics.aggregate({ name: 'queue_depth', since: '1d', every: '1h', op: 'last' })backlog = (await store.metrics.aggregate(name="queue_depth", since="1d", every="1h", op="last")).groupsA heatmap
const { groups: heat } = await store.metrics.aggregate({ name: 'http_request_ms_bucket', since: '1h', every: '1m', op: 'increase', by: ['le'] })heat = (await store.metrics.aggregate(name="http_request_ms_bucket", since="1h", every="1m", op="increase", by=["le"])).groupsHow many durations fell under each bound, each minute: a timer's buckets are counters, one a bound.
Fast over long ranges
The store packs a series' samples into blocks where whole hours begin, each
with an exact summary. A bucket that holds whole blocks answers from their
summaries, so a month drawn by the hour decodes almost nothing; a bucket finer
than a block, and a gauge's percentile always, decode its samples.
explain says what a query will cost.
Aggregate in pages
A year of one-minute buckets is 525,600 buckets per group, more than one
aggregate may answer. Give limit, and aggregate returns a page of that many
buckets at most, with next when there is more:
const query = { name: 'requests_total', since: '365d', every: '1m', op: 'rate', limit: 10_000 } as const
const page = await store.metrics.aggregate(query)
const more = await store.metrics.aggregate({ ...query, after: page.next })
for await (const group of page) chart.appendBuckets(group.labels, group.buckets) // this page, then every page after itpage = await store.metrics.aggregate(name="requests_total", since="365d", every="1m", op="rate", limit=10_000)
async for group in page: # this page, then every page after it
chart.append_buckets(group.labels, group.buckets)q := metrics.Query{Name: "requests_total", Since: 365 * 24 * time.Hour, Every: time.Minute, Op: metrics.Rate, Limit: 10_000}
page, err := metrics.Aggregate(ctx, store, q)
for group, err := range page.All(ctx) { // this page, then every page after it
chart.AppendBuckets(group.Labels, group.Buckets)
}- The answer goes group by group, each group's buckets in time order. A page
ends only between two whole buckets. A group that a page cuts has
more: true, and the next page starts with the rest of its buckets. - A walk of the pages,
for await,async for,Allorall(), joins a group's parts across pages and gives each group once, whole, withmorefalse. It holds one group's buckets at a time, which the range bounds. A walk of a read's pages gives a series in its parts, since a series is what pages exist to bound. limitcounts only buckets that hold samples, so a stretch with none costs a page nothing, unless the aggregate fills, when it counts every bucket. A page holds fewer thanlimitbuckets only when it is the last, when a bound stops it, when a short gap lies inside samples dense enough to have one in every bucket, whose empty buckets count so that the page needn't read every sample's time, or when a timer measured nothing in a bucket:avg,maxand percentiles leave that bucket out, though its counters have samples there. A page skips the groups with no samples in the range, however many come first, so a page withnextalways holds a bucket unless every bucket it reached is a timer's that measured nothing.next, walking a page and writes between pages work as for a read in pages.- Each bucket is computed from every series of its group, as without
limit. Arateor anincreasein the first bucket of a page starts from the sample before it, and the edge of a page never makes a bucketpartial. - A bucket is never split. If one bucket alone passes a bound, such as a
percentile over a year without
every, the aggregate fails with alimiterror. - A page reads the samples of its own groups alone, 1,000 series at most, so
pages go past the 1,000 series a query may find one group at a time. A
timer with 12 bounds, grouped
byfnover 92 functions, is 1,104 series, and its pages hold 83 functions, 996 series, and then 9. - A group with more than 1,000 series alone is read in parts, 1,000 series
at a time, and is alone on its page. This is how a counter with 5,000
series gives one total: ask with
limit, withoutby. Everyopbut a percentile adds up this way. A percentile ranks the samples of the whole group at once, so for it such a group is still alimiterror: groupbymore labels, or usewhereto find fewer.
Samples you don't store
A Rust program that reads numbers live and never keeps them, such as rows of
another database or a payments API, can aggregate them without a store. Call
query on a Series you built in memory. It returns the same buckets that a
store's query returns for the same samples, because the same code counts
them, and it writes nothing to disk.
use tinystore::metrics::{self, ExactSum, Op, Series};
let requests = Series::counter("requests").sample(t0, 100.0).sample(t0 + Duration::from_secs(10), 150.0)
.sample(t0 + Duration::from_secs(20), 20.0); // the process restarted
let minute = requests.query().from(t0).to(t0 + Duration::from_mins(1)).aggregate(Op::Increase)?;
// minute.buckets[0]: value 70, resets 1, as a store's query of these samples gives
let fleet = metrics::query(&[web1, web2]).calendar(Calendar::Day, "Europe/Moscow").aggregate(Op::Sum)?;
// one group: each series summed exactly, then the group, rounded once
let total: ExactSum = amounts.iter().copied().collect();
let paid = total.value(); // 1.0 for ten amounts of 0.1, where a float sum gives 0.9999999999999999querytakesfrom,to,every,calendar,estimateandskip_nan, as a store's query does. Withoutfromandto, the range runs from the first sample to the last.- The series that you pass are one group, which you choose. They must share a name and a kind. The answer's labels are the ones that every series has.
- A bucket is
partialagainst your machine's clock, as a store's query is against the store's. ExactSumis the sum alone:add,sub,mergefor a group of sums, andvalue, rounded once.- Only Rust has it so far. Bun, Node, Python and Go reach the metrics engine through a store.
Errors
| Error | When |
|---|---|
invalid | an op the kind has not; a percentile of a timer without buckets; a gauge bucket holding an infinity, or a NaN without skipNaN; a counter below zero |
invalid | samples you hold: series of two names or kinds, or two samples of one series in the same millisecond |
limit | without limit, past 100,000 buckets or a bound of the query, which it names; with it, one bucket or one group that passes a bound |
invalid | fill without since or from |
See also
- Metrics: the engine's overview.
- Instruments: what writes these series.
- How logs and metrics pack in the Handbook.