Metrics with Micrometer and Prometheus

Golden signals, a mean of 45.6 ms hiding a p99 of 1.7 s, two p99s averaged to 860 ms when the truth was 49, histogram buckets as estimates, and cardinality.

13 min read📈 Observability

Logs tell you what happened to one request. Metrics tell you what is happening to all of them: how many, how fast, how many failed, how close to full. They are numbers aggregated over time, cheap enough to keep for months, and they are what dashboards and alerts are built on.

This lesson covers the tools — Micrometer in the service, Prometheus to collect — and the two ideas that decide whether the numbers mean anything: percentiles instead of averages, and cardinality.

Micrometer, Prometheus, and pull

Micrometer is to metrics what SLF4J is to logging: a facade in your code, with a registry underneath for whichever monitoring system you use. Spring Boot Actuator configures it and records a large set of metrics without any code — HTTP server requests, JVM memory and GC, thread pools, connection pools, Kafka clients.

Prometheus collects them by pulling: every 15 or 30 seconds it requests /actuator/prometheus from each instance and stores the values as time series. Pulling means the monitoring system controls the rate, and an instance that stops answering is itself a signal.

The three meter types you will write yourself — reference code for the Micrometer API; the measurements later in this lesson come from a plain Java program, not a running registry:

java
// Counter: only goes up. Rate of change is what you graph.
Counter placed = Counter.builder("orders.placed")
        .tag("channel", "web")
        .register(registry);
placed.increment();
 
// Gauge: a value that goes up and down, read when scraped.
Gauge.builder("orders.pending", queue, Queue::size).register(registry);
 
// Timer: counts and measures durations, with a histogram when asked for.
Timer charge = Timer.builder("payment.charge")
        .publishPercentileHistogram()
        .register(registry);
charge.record(() -> gateway.charge(order));

A timer named payment.charge appears in Prometheus as payment_charge_seconds_count, _sum and, with the histogram enabled, _bucket — the names are converted to the monitoring system's conventions for you.

What to measure: the golden signals

Starting from a blank dashboard is how teams end up with two hundred graphs nobody reads. Three well-known lists say what matters:

  • The four golden signals (Google's SRE book): latency, traffic, errors, saturation.
  • RED, for request-driven services: rate, errors, duration — the first three golden signals, per endpoint.
  • USE, for resources like CPU, pools and queues: utilisation, saturation, errors.

For a typical Spring service that means requests per second, error rate and latency percentiles per endpoint; and for each pool — HTTP threads, database connections, executor queues — how full it is and how long work waits for it. Saturation is the one people leave out, and it is the one that moves before latency does, as the capacity planning lesson's latency curve shows.

Averages lie

Here are 100,000 requests to one endpoint. Most take about 20 ms; 1.2% hit a slow path and take about two seconds. The distribution was generated with a fixed seed, and the statistics computed exactly:

plaintext
one endpoint               mean   45.6   p50   20.1   p90   32.0   p99  1736.4   p99.9  2347.6   max  2399.5  (ms)

The mean is 45.6 ms. No request took 45.6 ms. Almost all took about 20, and about one in a hundred took nearly two seconds. The average blends a healthy majority with a broken minority into a number that describes neither, and a dashboard showing it looks fine.

The percentiles tell the truth: p50 is the typical request, p99 is the worst one in a hundred. For a page that makes ten backend calls, most page loads include at least one call from the slowest tenth, so the tail is what users actually feel.

Percentiles do not add up

A service runs on two instances. Instance A handles 90% of the traffic and is healthy. Instance B handles 10%, and 5% of its requests take a slow path:

plaintext
instance A                 mean   21.3   p50   20.0   p90   31.3   p99    45.2   p99.9    58.6   max    87.1  (ms)
instance B                 mean   91.5   p50   20.4   p90   35.5   p99  1675.5   p99.9  1787.9   max  1799.5  (ms)
average of the two p99s: 860.3 ms   true p99 of all requests: 49.2 ms

A dashboard that averages each instance's p99 shows 860 ms. The real p99 of the service's requests is 49 ms, because B's slow requests are only half a percent of all traffic — below the 1% the p99 looks at. Averaging percentiles gave a number seventeen times too large here, and with different traffic it can just as easily be too small.

Percentiles cannot be averaged, summed or combined. That is why Micrometer has two options that look similar and are not:

  • publishPercentiles(0.99) computes the p99 inside each instance. Accurate for that instance, and impossible to combine correctly across instances.
  • publishPercentileHistogram() publishes bucket counts. Counts can be summed across instances, and Prometheus computes percentiles from the sum:
plaintext
histogram_quantile(0.99, sum by (le) (rate(http_server_requests_seconds_bucket[5m])))

Use histograms for anything you look at across more than one instance, which in production is everything.

Histograms are estimates

A histogram stores how many requests fell into each bucket — under 5 ms, under 10, under 25 and so on — not the requests themselves. histogram_quantile finds the bucket containing the percentile and interpolates linearly inside it. The same 100,000 requests, with the exact value and two bucket layouts:

plaintext
p50   exact    20.1   coarse buckets    20.1   buckets placed near the data    20.1
p95   exact    37.3   coarse buckets    46.8   buckets placed near the data    46.8
p99   exact  1736.4   coarse buckets  1278.5   buckets placed near the data  1584.6

The p95 is 37 ms, but it falls between the 25 ms and 50 ms boundaries, and interpolation says 47. The p99 falls between 1,000 and 2,500 in the coarse layout and comes out 26% low; adding boundaries near where the slow requests sit brought it within 9%. A histogram's accuracy is decided by where its buckets are, and the right place is near the values you care about.

That suggests the most useful change of all. Instead of asking "what is the p99?", ask "what share of requests finished within my target?" — and put a bucket boundary exactly on the target:

plaintext
share of requests at or under 300 ms: 98.77%

With a boundary at 300 ms, that figure is a ratio of two counts — no interpolation, no estimate. In Spring Boot, management.metrics.distribution.slo.http.server.requests=300ms adds that boundary. It is exactly the number an SLO is written in, which the alerting lesson builds on.

Cardinality: the metric that takes the platform down

Every distinct combination of tag values is a separate time series, with its own storage and its own entry in the index. The count multiplies:

plaintext
http_server_requests  ×  30 endpoints  ×  4 methods  ×  6 status codes  ×  3 instances

That is up to 2,160 series for one metric, and multiplied by the buckets of a histogram — say 20 — about 43,000. Manageable. Now add a tag for the user id, with 100,000 users:

plaintext
43,000 × 100,000 ≈ 4.3 billion possible series

No time-series database stores that. In practice the platform's memory climbs until it degrades for every team, and the cause is one line of code in one service. The logging and metrics platform design on this site names it as one of that platform's bottlenecks for that reason.

Spring's built-in HTTP metrics use the URI template for exactly this reason, and a request that matches no route gets a fixed value such as NOT_FOUND rather than its raw path — otherwise a scanner hitting random URLs would create a series per URL.

Under the hood: what a Micrometer Timer actually publishes, and how Prometheus turns it into a histogram

A Meter in Micrometer is not a metric — it is a handle to a MeterRegistry, and the registry is where the real work happens. Timer.builder("payment.charge").register(registry) looks up or creates one Timer instance keyed by the metric name plus its tags (a Counter, Gauge or Timer with a different tag value is a different meter, which is the whole reason cardinality multiplies the way this lesson's earlier section shows). Calling .record(...) on that Timer does two things internally: it increments an internal count and adds the duration to an internal sum, and — only if publishPercentileHistogram() or an explicit SLO boundary was configured — it also increments a counter for every configured bucket boundary the observed duration falls at or under.

That "at or under, every boundary" detail is the mechanism worth being precise about, because it is exactly what makes Prometheus's histogram format work. A Prometheus histogram is not a set of exclusive bins; it publishes cumulative bucket counts, one time series per boundary, each labelled le ("less than or equal"):

plaintext
payment_charge_seconds_bucket{le="0.05"}  812     # requests at or under 50 ms
payment_charge_seconds_bucket{le="0.1"}   4021     # requests at or under 100 ms — includes the 812 above
payment_charge_seconds_bucket{le="0.5"}   9950     # requests at or under 500 ms — includes everything smaller
payment_charge_seconds_bucket{le="+Inf"}  10000    # every request — the same as _count
payment_charge_seconds_count              10000
payment_charge_seconds_sum                612.4

Because each bucket already contains every smaller bucket's requests, the count in a specific range (say, between 100 ms and 500 ms) is a subtraction between two adjacent cumulative counters, not a lookup of one series — 9950 − 4021 = 5929 requests landed in that range. This is exactly what histogram_quantile automates: it treats the buckets as a cumulative distribution, finds which boundary the target percentile's count falls between, and — because it does not know the exact values inside a bucket, only how many observations landed at or under each boundary — linearly interpolates between that bucket's lower and upper edges. That interpolation is the entire reason this lesson's earlier section showed the p95 come out as 47 ms against an exact value of 37: the histogram only ever knows counts at its configured boundaries, never the individual durations, so anything between two boundaries is a straight-line guess.

Every bucket is its own Prometheus time series, which is why publishPercentileHistogram() multiplies cardinality the same way an extra tag does — the earlier section's cardinality arithmetic applies to histogram buckets too, not only to tags, and a metric with 20 buckets and 30 endpoints already has 600 series before a single tag is added.

The _count and _sum series, published for every Timer regardless of whether a histogram is enabled, are what makes a Prometheus rate query for average latency correct even without a histogram: rate(payment_charge_seconds_sum[5m]) / rate(payment_charge_seconds_count[5m]) is a true average over the scrape window (still subject to the averaging-lies problem this lesson opened with) — it is histogram_quantile, which needs the _bucket series, that requires the histogram to be turned on at all.

Try it yourself

Classify observations into cumulative Prometheus buckets by hand

A Timer is configured with bucket boundaries at 50 ms, 100 ms and 500 ms (plus the implicit +Inf). Five requests are recorded, with durations 30 ms, 80 ms, 80 ms, 200 ms and 600 ms. Using the "at or under" rule above — a request counts toward a bucket if its duration is less than or equal to that bucket's boundary, and therefore toward every larger bucket too — work out the value Prometheus would show for le="50", le="100", le="500" and le="+Inf" before checking the fence below.

java
int[] durationsMs = {30, 80, 80, 200, 600};
int[] boundaries = {50, 100, 500};
 
for (int boundary : boundaries) {
    int count = 0;
    for (int d : durationsMs) {
        if (d <= boundary) count++;
    }
    System.out.println("le=" + boundary + " -> " + count);
}
int total = durationsMs.length;
System.out.println("le=+Inf -> " + total);
Why each bucket count includes the ones before it

Only the 30 ms request is at or under 50 ms, so le="50" is 1. At or under 100 ms adds the two 80 ms requests to that same 30 ms request, so le="100" is 3 — the 30 ms observation is counted again, because a cumulative bucket does not "belong" to one boundary, it belongs to every boundary at or above its value. At or under 500 ms adds the 200 ms request, making 4; the 600 ms request never falls at or under any configured boundary except the implicit +Inf, which always equals the total observation count (5) by definition. This is exactly the arithmetic histogram_quantile runs across every scraped instance's summed buckets to estimate a percentile — the "coarse buckets vs buckets placed near the data" comparison earlier in this lesson is the same cumulative counting, just with different boundary placements producing different interpolation error.

Grafana: the dashboard is a query

Prometheus stores and queries; Grafana draws. A dashboard is a set of panels, each a PromQL query — histogram_quantile(0.99, sum(rate(http_server_requests_seconds_bucket[5m])) by (le, uri)) is the p99 per endpoint — with the same rules this lesson set for the metrics themselves: rates over windows, percentiles from histograms, never an average of averages. Two habits make one useful rather than pretty. Build it from the golden signals down — traffic, errors, latency, saturation on the first row, per-dependency detail below — so the first glance answers "is it broken" and the scroll answers "where". And version it as code (a JSON model in the repository, or the Grafana operator's dashboard objects in Kubernetes), because a dashboard edited by hand in production is the config drift the deployment lesson warns about, with a chart. Grafana also fronts the logs (Loki) and the traces (Tempo) with the same query bar, which is what makes "click the latency spike, see the traces in it" a single motion.

Misconceptions

  • "A Timer's _count and _sum need publishPercentileHistogram() to exist." They do not — every Timer publishes _count and _sum unconditionally, enough for a correct rate-based average. Only the per-boundary _bucket series, which histogram_quantile needs, require the histogram to be turned on, and turning it on is what multiplies the series count.
  • "A Prometheus bucket counts the requests that landed in that range." It counts every request at or under that boundary, cumulatively — le="100" includes everything le="50" already counted. The count in a specific range is the subtraction between two adjacent cumulative buckets, not a single series lookup.
  • "Pull-based collection means Prometheus can't see a spike that happens between scrapes." It is worse than "can't see" and more specific than that: a metric that resets or briefly spikes entirely between two scrape intervals can be invisible or under-counted in the stored series, which is exactly why Prometheus favours monotonic counters observed with rate() over point-in-time gauges wherever the underlying thing being measured allows it.

Sources

  • Micrometer documentation — MeterRegistry, Timer, DistributionSummary and percentile histograms.
  • Prometheus documentation, "Histograms and summaries" — cumulative buckets, le, and why summaries cannot be aggregated across instances.
  • Prometheus documentation, "Querying basics" — histogram_quantile and the pull-based scrape model.
  • Google, Site Reliability Engineering — the four golden signals.
Progress is saved on this device and to your account when signed in.