Sub topic 7
Micrometer and the metrics endpoint
This chapter assumes you have a Spring Boot application with spring-boot-starter-actuator on the classpath and know how to edit application.yml. It also assumes you can read JSON. Spring Security is not needed here. The earlier chapter on exposing endpoints covers how metrics becomes reachable over HTTP.
What Micrometer is
Micrometer is a metrics facade, a thin API that application code calls to record measurements. It plays the role for metrics that SLF4J plays for logging. Your code talks to Micrometer, and a separate registry implementation sends the data to a monitoring system such as Prometheus, Datadog, or CloudWatch.
Actuator depends on Micrometer. Spring Boot auto-configures a MeterRegistry bean and binds a set of built-in instruments to it. With no other registry on the classpath, Boot falls back to a SimpleMeterRegistry. That registry keeps values in memory, and the /actuator/metrics endpoint reads from it.
The main vocabulary is short:
- A meter is one named measuring instrument.
- A meter registry creates and stores meters.
- A tag is a key/value pair, such as
status=200, that splits one metric into dimensions. - A measurement (called a statistic in the endpoint output) is one number a meter reports, such as
COUNTorTOTAL_TIME.
The meter types
Micrometer offers several meter types. Choosing the right one matters more than any configuration.
| Type | Records | Typical use |
|---|---|---|
| Counter | A value that only goes up | Orders placed, errors thrown |
| Timer | Count and total duration of short events | Request latency, method duration |
| Gauge | A current value that can rise and fall | Queue size, cache entries |
| DistributionSummary | Distribution of non-time values | Payload size in bytes |
| LongTaskTimer | Duration of tasks still running | Long batch jobs |
A gauge differs from a counter in an important way. A counter accumulates, so you ask how fast it grew. A gauge is a snapshot, so you ask what it is right now. Do not use a gauge to count events, because events between two samples are lost.
Built-in metrics
Actuator registers many meters without any code from you. Common groups are:
- JVM:
jvm.memory.used,jvm.gc.pause,jvm.threads.live - System:
system.cpu.usage,process.uptime - HTTP server:
http.server.requests - Connection pool:
hikaricp.connections.active - Logging:
logback.events - Tomcat:
tomcat.sessions.active.current
http.server.requests is a timer. Boot tags it with method, uri, status, outcome, and exception. The uri tag uses the route template, such as /orders/{id}, so every order id shares one series.
Reading the metrics endpoint
First expose the endpoint:
management:
endpoints:
web:
exposure:
include: health,metricsA request to /actuator/metrics returns only the list of meter names:
{
"names": [
"http.server.requests",
"jvm.memory.used",
"jvm.gc.pause",
"system.cpu.usage"
]
}To read one meter, add its name to the path. A request to /actuator/metrics/http.server.requests returns this shape:
{
"name": "http.server.requests",
"baseUnit": "seconds",
"measurements": [
{ "statistic": "COUNT", "value": 42.0 },
{ "statistic": "TOTAL_TIME", "value": 3.18 },
{ "statistic": "MAX", "value": 0.61 }
],
"availableTags": [
{ "tag": "uri", "values": ["/orders/{id}", "/orders"] },
{ "tag": "status", "values": ["200", "404", "500"] }
]
}Average latency is TOTAL_TIME / COUNT, here about 0.076 seconds. The availableTags list tells you which filters you can apply.
Filtering by tag
Add one or more tag query parameters in the form key:value:
/actuator/metrics/http.server.requests?tag=status:500
/actuator/metrics/http.server.requests?tag=uri:/orders/{id}&tag=method:GETEach added tag narrows the result to the matching series. The endpoint then sums those series for you. Note that the endpoint shows the current cumulative values only. It does not show history or rates. A time-series database does that job, which is why the next chapter exports to Prometheus.
Customizing the registry
Common tags let you label every metric from one instance, which helps when many instances report to the same backend. Set them in configuration:
management:
metrics:
tags:
application: shop-service
region: eu-west-1You can also customize the registry in code with a MeterRegistryCustomizer. This bean runs before the registry is used:
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MetricsConfig {
@Bean
MeterRegistryCustomizer<MeterRegistry> commonTags(
@Value("${spring.application.name:app}") String appName) {
return registry -> registry.config().commonTags("application", appName);
}
}Percentiles and histograms
By default a timer reports count, total, and max. For latency targets you often need percentiles. Configure them per meter name prefix:
management:
metrics:
distribution:
percentiles-histogram:
http.server.requests: true
slo:
http.server.requests: 100ms,250ms,500ms
percentiles:
http.server.requests: 0.95,0.99The settings differ in an important way:
percentilescomputes values such as p95 inside the application. These cannot be combined across instances.percentiles-histogrampublishes histogram buckets. A backend like Prometheus can aggregate buckets across instances and compute percentiles from them.sloadds specific bucket boundaries that match your service-level objectives.
Prefer histograms when you run more than one instance.
Controlling which metrics exist
Metrics cost memory and storage. You can switch groups on or off with management.metrics.enable, using the meter name prefix:
management:
metrics:
enable:
jvm: true
tomcat: false
all: trueThe most specific prefix wins. Disabling a meter makes it a no-op, so calls to it stay safe but record nothing.
Common errors
The failures below come up often in real projects.
- A 404 on
/actuator/metrics. The endpoint is enabled but not exposed. Addmetricstomanagement.endpoints.web.exposure.include. - A meter name returns 404. The meter has not been created yet. Many meters appear only after the first event, so call the code path and ask again. Names are also exact. The dotted form
http.server.requestsis what the endpoint uses, even though Prometheus later shows it ashttp_server_requests_seconds. - Tag explosion. Never use unbounded values such as user ids, raw URLs, or session ids as tag values. Each distinct combination creates a new time series, which can exhaust memory in the application and the backend. Keep tag values to a small, known set.
- Inconsistent tag keys. A meter name must use the same set of tag keys every time. Some backends reject or silently drop the registration if they differ.
- Gauge loses its value. A gauge holds only a weak reference to the object it observes. If the object is garbage collected, the gauge reports
NaN. Keep a strong reference, or register with a long-lived bean such as a collection field. - Wrong meter type. Using a counter for a queue size gives a number that only grows. Use a gauge for current state.
- Missing tags on custom metrics. Common tags apply to meters registered after the customizer runs. Register custom meters from beans created after the registry, which injection of
MeterRegistryguarantees.
Naming conventions
Use lowercase, dot-separated names that go from general to specific, such as orders.processing. Do not put units in names, because the registry adds them for you. Do not include tag values in names. Micrometer converts names to each backend's style, so the same meter becomes orders_processing_seconds in Prometheus.
Exercises
Exercise
A request to /actuator/metrics/http.server.requests returns COUNT 200 and TOTAL_TIME 30.0 seconds. What is the average request time, and why can this endpoint not tell you whether latency got worse over the last five minutes?
Show answer
The average is 30.0 / 200 = 0.15 seconds. The endpoint reports cumulative values since the application started and keeps no history. To see change over time you need a time-series backend such as Prometheus to sample the values and compute rates.
Exercise
A developer adds a tag userId to a counter that records each login. Why is this a problem, and what is a safer design?
Show answer
Every distinct user id creates a new time series, so the number of series grows with the user base. This is tag explosion and can exhaust memory in the application and the monitoring backend. A safer design uses tags with a small fixed set of values, such as outcome=success or outcome=failure, and keeps per-user detail in logs.
Exercise
Your service runs as six instances. You need an accurate overall p99 latency for http.server.requests. Which setting should you use, percentiles or percentiles-histogram, and why?
Show answer
Use percentiles-histogram. Percentiles computed inside each instance cannot be averaged or merged into a correct overall value. Histogram buckets can be summed across instances by the backend, which then computes the p99 from the combined buckets.