Sub topic 9
Exporting Metrics to Prometheus
This chapter covers how Spring Boot publishes Micrometer metrics in Prometheus format, how Prometheus collects them, and the mistakes that most often break the setup. It assumes you know the following:
- You have a Spring Boot application with Actuator on the classpath.
- You know how to expose endpoints with
management.endpoints.web.exposure.include. - You know what a Micrometer
MeterRegistryis, and you have seen a counter or a timer.
How Prometheus collects metrics
Prometheus is a monitoring system that uses a pull model. Your application does not send metrics anywhere. It serves its current values over HTTP as plain text, and the Prometheus server requests that page on a schedule. Each request is called a scrape. The page is a snapshot of every meter at that moment.
Micrometer is a facade, so the same meter code works with many monitoring systems. A registry is the adapter for one system. The Prometheus registry turns Micrometer meters into the Prometheus text format.
Adding the registry
The Actuator starter provides the endpoints. The Micrometer Prometheus registry provides the /actuator/prometheus endpoint. Without the registry, that endpoint does not exist.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<scope>runtime</scope>
</dependency>Spring Boot detects the registry and auto-configures it. You do not write any Java. Spring Boot manages the version of the registry, so you leave the version out.
Next, expose the endpoint. Endpoints are not exposed over HTTP by default, except health.
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheusStart the application and request the endpoint:
curl -s http://localhost:8080/actuator/prometheus | head -n 20You should see lines that start with # HELP, # TYPE, and then sample lines.
Reading the text format
Each meter becomes one or more lines. A sample line has a metric name, optional labels in braces, and a value.
# HELP orders_placed_total Number of orders placed
# TYPE orders_placed_total counter
orders_placed_total{channel="web",application="shop"} 42.0
# HELP orders_processing_seconds Time spent processing an order
# TYPE orders_processing_seconds summary
orders_processing_seconds_count{application="shop"} 42
orders_processing_seconds_sum{application="shop"} 8.4
orders_processing_seconds_max{application="shop"} 0.31A label is a key and value pair attached to a sample. Micrometer calls the same thing a tag. A time series is one metric name combined with one exact set of labels. Prometheus stores each series separately.
How Micrometer names are converted
Micrometer names use dots, such as orders.placed. Prometheus names use underscores and a unit suffix. The registry converts the names for you.
| Micrometer meter | Name in Micrometer | Name in Prometheus |
|---|---|---|
| Counter | `orders.placed` | `orders_placed_total` |
| Timer | `orders.processing` | `orders_processing_seconds_count`, `_sum`, `_max` |
| Gauge | `queue.size` | `queue_size` |
| Distribution summary | `payload.bytes` | `payload_bytes_count`, `_sum`, `_max` |
Two rules follow from this table:
- Counters get a
_totalsuffix. Do not add_totalyourself, or you will getorders_placed_total_total. - Timers are always reported in seconds. Do not put a unit in the name, such as
orders.processing.millis.
The meter types and what they let you ask
The Prometheus type of each meter decides which questions you can answer.
- A counter only goes up, and it resets to zero when the application restarts. You almost never use its raw value. You use
rate()to see how fast it grows. - A gauge goes up and down, such as queue size or active sessions. You read its current value.
- A timer gives a count and a sum, so you can compute an average. By default it does not give percentiles that you can combine across instances.
Here are a few PromQL queries. PromQL is the Prometheus query language.
rate(orders_placed_total[5m])
rate(orders_processing_seconds_sum[5m]) / rate(orders_processing_seconds_count[5m])
sum by (application) (rate(http_server_requests_seconds_count{status=~"5.."}[5m]))The first query gives orders per second over the last five minutes. The second gives the average processing time. The third gives the 5xx error rate for each application.
Histograms and percentiles
An average hides slow requests. To see the 99th percentile you need a histogram. Micrometer can publish histogram buckets, which are counters of how many observations fell under each upper bound. Prometheus can then compute percentiles on the server, and it can combine buckets from many instances.
You can enable buckets for one meter in code, or for the HTTP server metrics in configuration:
management:
metrics:
distribution:
percentiles-histogram:
http.server.requests: true
slo:
http.server.requests: 100ms,250ms,500ms,1sThen query the percentile in PromQL:
histogram_quantile(0.99,
sum by (le) (rate(http_server_requests_seconds_bucket[5m])))Buckets add series. Each bucket is one series for every label combination. Enable them only on meters where you need percentiles.
The alternative is percentiles in Micrometer, which computes quantiles inside each application. Those values cannot be averaged or combined across instances, so prefer histograms when you run more than one instance.
Common tags for every metric
When you run several instances or services, you need to tell their series apart. Prometheus adds an instance label from the scrape target. You can also add tags for every meter through configuration:
management:
metrics:
tags:
application: ${spring.application.name}
environment: prodSet spring.application.name as well. Otherwise the tag is empty.
Configuring Prometheus to scrape the application
Prometheus reads a YAML file that lists scrape targets. This minimal file scrapes one application every 15 seconds.
global:
scrape_interval: 15s
scrape_configs:
- job_name: shop
metrics_path: /actuator/prometheus
static_configs:
- targets: ["localhost:8080"]The metrics_path setting matters. Prometheus uses /metrics by default, and Actuator does not serve that path. If you forget this setting, the target appears as down with a 404 error.
If you moved Actuator to its own port, as in management.server.port: 9090, point the target at that port instead. If you secured the endpoint, add credentials:
scrape_configs:
- job_name: shop
metrics_path: /actuator/prometheus
basic_auth:
username: prometheus
password_file: /etc/prometheus/shop-password
static_configs:
- targets: ["shop:9090"]Do not leave /actuator/prometheus open on a public port. Metrics reveal internal names, traffic levels, and error rates.
In Kubernetes you usually do not list targets by hand. Prometheus discovers pods through the Kubernetes API. The Prometheus Operator uses a ServiceMonitor object to declare which service to scrape and on which path. The rule is the same in both cases: the scrape path and port must match what the application serves.
Running Prometheus locally
A quick way to try this is with Docker. Save the scrape file as prometheus.yml, then run:
docker run -p 9091:9090 \
-v "$PWD/prometheus.yml:/etc/prometheus/prometheus.yml" \
prom/prometheusOpen http://localhost:9091/targets and check that the target is UP. Then open the graph page and type rate(http_server_requests_seconds_count[1m]). If Prometheus runs in a container and the application runs on your host, localhost inside the container does not reach the host. Use host.docker.internal as the target on Docker Desktop.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| `/actuator/prometheus` returns 404 | The registry dependency is missing, or `prometheus` is not in the exposure list | Add `micrometer-registry-prometheus` and include `prometheus` |
| Prometheus shows the target as down with 404 | `metrics_path` is still `/metrics` | Set `metrics_path: /actuator/prometheus` |
| Target is down with 401 or 403 | The endpoint is secured and Prometheus sends no credentials | Add `basic_auth` or a bearer token |
| Counter appears as `x_total_total` | The counter name already ended in `_total` | Remove the suffix from the Micrometer name |
| Series count grows without bound | A tag takes unbounded values, such as a user ID or full URL | Use only low-cardinality tags |
| Counter drops to zero after deploy | The process restarted | Use `rate()` or `increase()`, which handle resets |
Cardinality
Cardinality is the number of distinct time series. Each unique label combination creates a new series in memory in your application and in the Prometheus database. A tag such as userId with a million values creates a million series for one meter. This can exhaust memory and make queries slow.
// Avoid: one series per user
Counter.builder("orders.placed").tag("userId", userId).register(registry).increment();
// Prefer: a small, fixed set of values
Counter.builder("orders.placed").tag("channel", "web").register(registry).increment();Spring Boot's http.server.requests metric uses the URI template, such as /orders/{id}, rather than the real path. That keeps its cardinality low. Keep your own tags to values you can list in advance.
Short-lived jobs
Pull needs the target to be alive when Prometheus visits. A batch job that finishes in five seconds can be missed with a 15-second interval. For this case Prometheus offers the Pushgateway, and Spring Boot supports it through management.prometheus.metrics.export.pushgateway. Use it only for jobs, not for ordinary services, because the gateway keeps the last pushed value forever unless you delete it.
Summary of settings
| Setting | Purpose |
|---|---|
| `management.endpoints.web.exposure.include` | Adds `prometheus` to the exposed endpoints |
| `management.metrics.tags.*` | Adds common tags to every meter |
| `management.metrics.distribution.percentiles-histogram.*` | Publishes histogram buckets |
| `management.metrics.distribution.slo.*` | Publishes buckets at chosen thresholds |
| `management.endpoint.prometheus.access` | Controls access to the endpoint in Spring Boot 3.4 and later |
Exercise
Your application defines a counter named orders.placed. In Prometheus, you search for orders_placed and find nothing, and the target is UP. What name should you search for, and why?
Show answer
Search for orders_placed_total. The Prometheus registry replaces dots with underscores and adds the _total suffix to every counter.
Exercise
A teammate adds a customerEmail tag to a request counter. Prometheus memory use climbs over the following days. What is the cause, and what do you change?
Show answer
The tag has unbounded values, so every new email creates a new time series (high cardinality). Remove the tag, or replace it with a small fixed set of values such as customer tier, and record per-customer detail in logs instead.
Exercise
Prometheus shows your target as down with a 404 error. curl http://localhost:8080/actuator/prometheus works from your machine. Name the most likely scrape setting at fault and the correct value.
Show answer
The metrics_path setting is probably missing, so Prometheus requests /metrics. Set metrics_path: /actuator/prometheus in the scrape configuration.