Metrics / Reading
Reading
read gives series as they were written: each with its name, labels and
samples, every value bit for bit. latest gives each series' newest sample.
names, labelNames and labelValues list what a store holds, for the
menus of a dashboard, without reading a sample.
const { series } = await store.metrics.read({ name: 'cpu', where: { host: 'web-1' }, since: '1h' })
for (const { labels, times, values } of series) chart.line(labels.host, times, values)series = (await store.metrics.read(name="cpu", where={"host": "web-1"}, since="1h")).series
for s in series:
chart.line(s.labels["host"], s.times, s.values)A series comes back with its samples as two columns: times, unix
milliseconds in a Float64Array, which a chart and new Date take, and
values, a Float64Array whose bytes keep every value's bits. Python gives
the same two arrays; Go and Rust a slice of samples. A NaN in values is a
value that was stored, never a missing one.
Conditions
const { series: failing } = await store.metrics.read({
name: 'http_requests_total',
since: '1h',
where: { status: ['500', '502'], env: { not: 'dev' }, host: { prefix: 'api-' } },
})
const { series: host } = await store.metrics.read({ where: { host: 'web-1' }, since: '10m' }) // every name of one hostfailing = (await store.metrics.read(
name="http_requests_total",
since="1h",
where={"status": ["500", "502"], "env": {"not": "dev"}, "host": {"prefix": "api-"}},
)).series
host = (await store.metrics.read(where={"host": "web-1"}, since="10m")).seriesfailing, err := metrics.Read(ctx, store, metrics.Query{Name: "http_requests_total", Since: time.Hour,
Where: metrics.Where{"status": metrics.OneOf("500", "502"), "env": metrics.Not("dev"), "host": metrics.Prefix("api-")}})
host, err := metrics.Read(ctx, store, metrics.Query{Where: metrics.Where{"host": "web-1"}, Since: 10 * time.Minute})| In a query | Finds |
|---|---|
name | the series of this name; a timer's name, all it writes |
{ host: 'a' } | a label equal to this value |
['500', '502'] | equal to one of these |
{ not: 'dev' } | equal to none of these, or absent |
{ prefix: 'api-' } | starting with this text |
since | the span before now, '1h'; or from and to |
- Every condition holds. A query needs a
name, or a label's value, list or prefix, to find its series:notalone isinvalid, since it would read every series. There are no regular expressions. - A number in
whereis its text:{ status: 200 }finds"200". - A condition given as
undefinedisinvalid, never left out. - A field a query does not take is
invalidand named, never dropped:nameson a metrics query saysno field `names`; did you mean `name`?. A metrics query names one series name,name; a records query a list,names. - A query is data: the same object is kept in a dashboard's settings, sent over the wire, and read the same in every language.
The newest value
latest gives one sample a series, the newest in the range. A series without
one is left out, so the range bounds how stale an answer may be: a host that
went down leaves the answer rather than showing its last value for ever. It
reads one small piece of each series, however long the range.
What a store holds
const page = await store.metrics.names({ prefix: 'http_' })
// { names: [{ name, kind, seriesCount, unit, help, keep, retainedFrom, newest }, …], next }
const { labels } = await store.metrics.labelNames('http_requests_total') // ['route', 'status']
const { values } = await store.metrics.labelValues('http_requests_total', 'route', { prefix: '/api' })
await store.metrics.describe('cpu', { unit: '%', help: 'Busy time of a core.' })page = await store.metrics.names(prefix="http_")
labels = (await store.metrics.label_names("http_requests_total")).labels
values = (await store.metrics.label_values("http_requests_total", "route", prefix="/api")).values
await store.metrics.describe("cpu", unit="%", help="Busy time of a core.")page, err := metrics.Names(ctx, store, metrics.Prefix("http_"))
labels, err := metrics.LabelNames(ctx, store, "http_requests_total")
values, err := metrics.LabelValues(ctx, store, "http_requests_total", "route", metrics.Prefix("/api"))
err = metrics.Describe(ctx, store, "cpu", metrics.Description{Unit: "%", Help: "Busy time of a core."})let page = stats.names().prefix("http_").page()?;
let labels = stats.label_names("http_requests_total").page()?.labels;
let routes = stats.label_values("http_requests_total", "route").prefix("/api").page()?.values;
stats.describe("cpu", Description { unit: "%".into(), help: "Busy time of a core.".into() })?;None of them reads a sample: the file keeps what they give beside the series,
so a dashboard's menus stay fast however much the store holds. Pages are
1,000 entries unless limit says; after: page.next reads the next.
Cost before it runs
const plan = await store.metrics.explain({ name: 'cpu', since: '30d', every: '1h', op: 'avg' })
// { series: 40, bytes: 1310720, decoded: 960 }A query is bounded before it starts: series, bytes read, samples decoded and
the size of the answer are separate budgets. Without limit, a query past one
fails with a limit error that names it, never a smaller answer. explain says how many series, bytes and
decoded samples a read or an aggregate would spend, and in exceeds the
bound it would stop at, answer included.
| Bound | A query's limit |
|---|---|
| series | 1,000 |
| bytes read | 16 MiB |
| samples decoded | 1,048,576 |
| an answer | 100,000 samples or buckets |
To read past these bounds, read in pages. A read's pages go past every one
of them. An aggregate's pages go past every one too, except what a single
bucket or a single group needs, since a page never splits either: see
aggregate in pages.
Read a long range in pages
Thirty days of one sample per second is 2.6 million samples per series, more
than one read may answer. Give limit, and read returns a page of that many
samples at most, with next when there is more:
const query = { name: 'ping_rtt_ms', since: '30d', limit: 10_000 }
const page = await store.metrics.read(query)
const more = await store.metrics.read({ ...query, after: page.next })
for await (const part of page) chart.append(part.labels, part.times, part.values) // this page, then every page after itpage = await store.metrics.read(name="ping_rtt_ms", since="30d", limit=10_000)
more = await store.metrics.read(name="ping_rtt_ms", since="30d", limit=10_000, after=page.next)
async for part in page: # this page, then every page after it
chart.append(part.labels, part.times, part.values)q := metrics.Query{Name: "ping_rtt_ms", Since: 30 * 24 * time.Hour, Limit: 10_000}
page, err := metrics.Read(ctx, store, q)
q.After = page.Next
more, err := metrics.Read(ctx, store, q)
for part, err := range page.All(ctx) { // this page, then every page after it
chart.Append(part.Labels, part.Samples)
}- Without
limit,readworks as before: the whole answer, or alimiterror. With it, a page holds 1 to 100,000 samples. - The answer goes series by series, each series' samples in time order. A
long series is split across pages. Its last part on a page has
more: true, and the next page starts with the rest of it. - A page can hold fewer samples than
limitand still havenext, when it reached another bound first, but never none: it skips the series with no samples in the range, however many come first. Only the last page has nonext, and only the last can be empty. - Walking a page reads the pages after it one at a time, so only one page is
in memory. In async Rust,
page.all()is aStream. nextkeeps the range of the first page, sosince: '30d'means the same 30 days on every page. Passnextwith the same query andlimit: another query is refused asinvalid.aggregatetakeslimitandaftertoo, and its page holds buckets. See Aggregates.
Each page is read on its own, not from one snapshot. If samples are written between pages, a page sees those written ahead of where the last page ended, and misses those written behind it. A series deleted between pages is missing from the pages after.
To export a range and resume after a crash, save next after you write each
page. The last page has no next, so also save that the export is done.
Otherwise a restart reads everything again:
let saved = await loadCursor() // { after: undefined, done: false } on the first run
while (!saved.done) {
const page = await store.metrics.read({ name: 'ping_rtt_ms', since: '30d', limit: 10_000, after: saved.after })
await writeOut(page.series)
saved = { after: page.next, done: page.next === undefined }
await saveCursor(saved)
}saved = load_cursor() # {"after": None, "done": False} on the first run
while not saved["done"]:
page = await store.metrics.read(name="ping_rtt_ms", since="30d", limit=10_000, after=saved["after"])
write_out(page.series)
saved = {"after": page.next, "done": page.next is None}
save_cursor(saved)saved := loadCursor() // {After: "", Done: false} on the first run
for !saved.Done {
page, err := metrics.Read(ctx, store, metrics.Query{Name: "ping_rtt_ms", Since: 30 * 24 * time.Hour, Limit: 10_000, After: saved.After})
if err != nil {
return err
}
writeOut(page.Series)
saved = Saved{After: page.Next, Done: page.Next == ""}
saveCursor(saved)
}let mut saved = load_cursor(); // Saved { after: None, done: false } on the first run
while !saved.done {
let mut query = stats.query().name("ping_rtt_ms").since(Duration::from_hours(30 * 24)).limit(10_000);
if let Some(after) = &saved.after {
query = query.after(after);
}
let page = query.read()?;
write_out(&page.series);
saved = Saved { done: page.next.is_none(), after: page.next };
save_cursor(&saved);
}Removing a series
await store.metrics.delete({ name: 'cpu', labels: { host: 'web-1' } }) // true if it held that serieslet held = stats.delete("cpu", [("host", "web-1")])?;delete removes the one series of exactly these labels and all its samples.
The labels are always given, so a delete never reads as one of every series of
a name. A series whose bytes changed under it reads corrupt, stops taking
samples, and is listed by damaged; delete removes it.
See also
- Metrics: the engine's overview.
- Aggregates: rates, averages and percentiles by bucket.