Metrics with Jennifer: Prometheus™, StatsD and InfluxDB™

Jennifer

Counters, gauges and histograms from a Jennifer service: scraped by Prometheus™, pushed by a batch job, sent over UDP to StatsD, written as points to InfluxDB™.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 23

Logs, alerts and metrics

AnswersCosts
Logswhat happened to this request?grows with traffic
Metricshow many, how fast, how full, over time?grows with series
Alertsdoes someone have to act now?built on the two above
2 / 23

Four kinds of metric

TypeGoesExampleAsk it
counteronly up (reset on restart)requests servedrate() per second
gaugeup and downqueue depth, temperaturethe value itself
histogramcounts per bucketrequest durationhistogram_quantile()
summaryquantiles, computed in the programjob durationx{quantile="0.9"}

A histogram's buckets can be summed across instances; a summary's quantiles cannot: averaging two 95th percentiles is meaningless.

3 / 23

Labels and cardinality

shop_http_requests_total{code="500",route="/checkout"}   one series
shop_http_requests_total{code="200",route="/checkout"}   another one
4 / 23

Pull or push: three decks

@deckyard/prometheus@deckyard/statsd@deckyard/influxdb
Modelpull: scrapedpush: UDPpush: HTTP POST
Keepstotals, in your programtotals, in the agentevery point, raw
Dimensionslabelsdots, DogStatsD tagstags
jvc add @deckyard/prometheus
jvc add @deckyard/statsd
jvc add @deckyard/influxdb
jvc install
5 / 23

A counter in a value-semantic deck

func inc(m as prometheus.Metric, labels as map of string to string) {
    def v as float init 0.0;
    for (def s in $m.samples) {
        if ($s.labels == $labels) {
            $v = $s.value;
        }
    }
    return prometheus.observe($m, $labels, $v + 1.0);
}
6 / 23

The shop's three metrics

def const BUCKETS as list of float init
    [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0];
def reqs as prometheus.Metric init prometheus.counter(
    "shop_http_requests_total", "HTTP requests by route and status");
def dur as prometheus.Metric init prometheus.histogram(
    "shop_latency_seconds", "Time to answer", BUCKETS);
def info as prometheus.Metric init prometheus.gauge(
    "shop_build_info", "Version of the running shop");
$info = prometheus.observe($info, {"version": "1.4.2"}, 1.0);
7 / 23

Serving /metrics from one httpd loop

while (true) { # lint-disable: L105
    def req as httpd.Request init httpd.accept($srv);
    def route as string init routeOf($req);   # "other" for a 404
    if ($route == "/metrics") {
        scrape($req, [$reqs, $dur, $info]);   # render, respond
        continue;
    }
    def t0 as int init time.unixNanos(time.now());
    def code as int init handle($req);        # answers the request
    def secs as float init (time.unixNanos(time.now()) - $t0) / 1e9;
    $reqs = inc($reqs, {"route": $route, "code": "{$code}"});
    $dur = prometheus.observe($dur, {"route": $route}, $secs);
}
8 / 23

Prometheus scrapes the shop

global:
  scrape_interval: 5s
scrape_configs:
  - job_name: shop
    static_configs:
      - targets: ["127.0.0.1:8080"]
# TYPE shop_http_requests_total counter
shop_http_requests_total{code="200",route="/checkout"} 438.0
shop_http_requests_total{code="500",route="/checkout"} 46.0
# TYPE shop_latency_seconds histogram
shop_latency_seconds_bucket{le="0.1",route="/checkout"} 231.0
shop_latency_seconds_bucket{le="+Inf",route="/checkout"} 484.0
shop_latency_seconds_count{route="/checkout"} 484.0
9 / 23

PromQL from Jennifer: rate and quantiles

func show(promql as string, label as string) {
    def r as prometheus.Result init prometheus.query(PROM, $promql);
    for (def s in $r.series) {
        io.printf("%s|pad=10 %f|prec=3\n", $s.metric[$label],
            $s.values[0].value);
    }
}
show("sum by (code) (rate(shop_http_requests_total[1m]))", "code");
show("histogram_quantile(0.95, sum by (le, route) " +
    "(rate(shop_latency_seconds_bucket[1m])))",
    "route");
200 6.655     404 2.364     500 0.600
/   0.005     other 0.005     /checkout 0.236
10 / 23

Batch jobs: push to a Pushgateway

def body as string init prometheus.render([
    gauge("backup_last_success_timestamp_seconds", "Last OK", $now),
    gauge("backup_duration_seconds", "Run time", $secs),
    gauge("backup_size_bytes", "Size of the last backup", $size)
]);
def path as string init prometheus.pushgatewayPath("backup",
    {"host": "nas1"});
def r as http.Response init http.put(GATEWAY + $path, "text/plain",
    $body, {});
PUT /metrics/job/backup/host/nas1 -> 200
backup on nas1: 100 s ago        # time() - backup_last_success_...
11 / 23

StatsD: one UDP line per event

def c as statsd.Client init statsd.clientWith($agent, "shop.worker");
statsd.increment($c, "jobs");
statsd.timing($c, "job.duration", $ms);
for (def lookup in 0..100) {             # 100 cache lookups per job
    if (math.rand() < 0.1) {
        statsd.countRate($c, "cache.lookups", 1, 0.1);
    }
}
statsd.gauge($c, "queue.depth", 17);
20 bytes: shop.worker.jobs:1|c
30 bytes: shop.worker.job.duration:53|ms
34 bytes: shop.worker.cache.lookups:1|c|@0.1      (12 times)
28 bytes: shop.worker.queue.depth:17|g
12 / 23

StatsD into Prometheus, and fire-and-forget

shop_worker_cache_lookups 2190          # 20 jobs x 100, sampled 1:10
shop_worker_jobs 20
shop_worker_job_duration{quantile="0.9"} 0.087
shop_worker_job_duration_count 20
shop_worker_queue_depth 17
13 / 23

InfluxDB: one line per point

def p as influxdb.Point init influxdb.point("shop_job");
$p = influxdb.tag($p, "queue", "orders");
$p = influxdb.field($p, "duration_ms", 53.2);
$p = influxdb.intField($p, "items", 3);
io.printf("%s\n", influxdb.line($p));
io.printf("%s\n", influxdb.line(influxdb.atTime($p, time.now())));
shop_job,queue=orders duration_ms=53.2,items=3i
shop_job,queue=orders duration_ms=53.2,items=3i 1795091540169180680
14 / 23

Timestamps and batches

$right = influxdb.atTime($right, $now);
$wrong = influxdb.at($wrong, time.unix($now));     # seconds, not ns
...
if (len($pending) == $batch) {
    influxdb.write($db, $pending);                 # one HTTP POST
    ...
    $pending = [];
}
1970-01-01T00:00:01.795091416Z 2
2026-11-19T12:30:16.798577523Z 1
2000 points in 2000 writes, 13381 ms
2000 points in 4 writes, 635 ms
15 / 23

Flux from Jennifer: exact quantiles

def body as string init influxdb.queryFlux($db, 'from(bucket: "shop")
  |> range(start: -15m)
  |> filter(fn: (r) => r._field == "duration_ms")
  |> group(columns: ["queue"])
  |> quantile(q: 0.95)');
for (def row in csv.toRecords(csv.parse(strings.trim($body)))) {
    io.printf("%s|pad=8 %f|prec=1 ms\n", $row["queue"],
        convert.toFloat($row["_value"]));
}
images   173.0 ms
mails    169.3 ms
orders   172.8 ms
16 / 23

Tags, fields and cardinality

for (def i in 0..2000) {
    def p as influxdb.Point init influxdb.point("shop_job_by_id");
    $p = influxdb.tag($p, "job", "j{100000 + $i}");    # an id: wrong
    $batch[] = influxdb.field($p, "duration_ms", 50.0);
}
shop_job         9 series
shop_job_by_id   2000 series
17 / 23

Naming conventions

PrometheusStatsDInfluxDB
Shapeapp_thing_unit_totalapp.area.thingapp_thing + fields
Allowed[a-zA-Z_:][a-zA-Z0-9_:]*letters, digits, _ - .anything, escaped
Unitsbase units: _secondsthe type: msfield key: _ms
Countersend in _totalno suffixcount in the query
Dimensionslabelssegments, DogStatsD tagstags

One prefix per program (shop_, shop.worker); one unit per metric.

18 / 23

What Prometheus and StatsD throw

[prometheus] prometheus: invalid metric name: shop-requests
[prometheus] prometheus: invalid label name: __name
[prometheus] 400 bad_data: prometheus: invalid parameter "query":
  1:6: parse error: expected type range vector in call to function
  "rate", got instant vector
[net] net.connect: 127.0.0.1:9999: dial tcp 127.0.0.1:9999: connect:
  connection refused
[statsd] metric name is empty, has an empty segment, or an illegal
  character (allowed: letters, digits, and . _ -)
def p as prometheus.PrometheusError init $e;  # after kind matched
19 / 23

What InfluxDB throws

[401 unauthorized] influxdb: HTTP 401: unauthorized access
[404 not found] influxdb: HTTP 404: bucket "shpo" not found
[422 unprocessable entity] influxdb: HTTP 422: failure writing
  points to database: partial write: field type conflict: input
  field "duration_ms" on measurement "shop_job" is type integer,
  already exists as type float dropped=1
[0 ] influxdb: point "shop_job" has no fields
[net] net.connect: 127.0.0.1:8099: dial tcp 127.0.0.1:8099: connect:
  connection refused
def ie as influxdb.InfluxdbError init $e;  # $ie.status, $ie.code
20 / 23

From metrics to alerts

- alert: ShopErrorsHigh
  expr: |
    sum(rate(shop_http_requests_total{code=~"5.."}[1m]))
      / sum(rate(shop_http_requests_total[1m])) > 0.02
  for: 30s
  labels: {severity: warning}
def r as prometheus.Result init prometheus.query(PROM,
    'ALERTS{alertstate="firing"}');
firing: ShopErrorsHigh (warning)

Delivery, once and resolved: the alerting talk.

21 / 23

Which one when

22 / 23

Takeaways and read more

Based on Jennifer 0.27.0, November 2026.

23 / 23