Expose Metrics with Micrometer and Prometheus
How to expose custom application metrics using Micrometer and Prometheus in Spring Boot, including counters, gauges, timers, and histograms.
Overview
Micrometer is a metrics facade — your code talks to a vendor-neutral API, and a registry implementation ships the numbers to a monitoring backend. The Prometheus registry exposes everything under /actuator/prometheus in the text exposition format, ready for a Prometheus server to scrape on a fixed interval.
That pull model is the important part: your application never pushes anything. It keeps an in-memory registry of counters, gauges and timers, and the scraper reads a snapshot whenever it wants. This recipe wires that registry up in Spring Boot, then goes through the four meter types you will actually use, label handling, and the mistakes that silently break dashboards.
When to Use
- Tracking business metrics (orders placed, payments processed, active users)
- Measuring operation latency (database queries, API calls, cache lookups)
- Monitoring resource pools (connection pool size, queue depth, thread count)
- Setting up alerts in Prometheus/Grafana based on application metrics
- Building dashboards for SLO tracking (error rate, latency percentiles)
When NOT to Use
- Simple scripts or CLI tools — metrics add overhead and complexity
- Logging-only observability — if you don’t have a Prometheus server, metrics are useless
- High-cardinality data (per-user metrics) — Prometheus handles low-cardinality labels well, but thousands of label values cause cardinality explosions
Solution
Setup with Spring Boot
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
Enable the Prometheus endpoint
# application.yml
management:
endpoints:
web:
exposure:
include: health,info,prometheus
# Common tags land on every meter — they show up as Prometheus labels
metrics:
tags:
application: user-service
environment: ${spring.profiles.active:default}
Metrics are now readable at http://localhost:8080/actuator/prometheus as plain text — one line per time series.
Counter — count events
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final Counter ordersCreated;
private final Counter ordersFailed;
public OrderService(MeterRegistry registry) {
this.ordersCreated = Counter.builder("orders.created")
.description("Total orders created")
.tag("type", "standard")
.register(registry);
this.ordersFailed = Counter.builder("orders.failed")
.description("Total orders that failed processing")
.tag("type", "standard")
.register(registry);
}
public void createOrder(OrderRequest request) {
try {
// ... create order ...
ordersCreated.increment();
} catch (Exception e) {
ordersFailed.increment();
throw e;
}
}
}
Gauge — track the current value
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.concurrent.atomic.AtomicInteger;
@Service
public class ConnectionPoolMonitor {
private final AtomicInteger activeConnections = new AtomicInteger(0);
public ConnectionPoolMonitor(MeterRegistry registry) {
Gauge.builder("connection.pool.active", activeConnections, AtomicInteger::doubleValue)
.description("Current active database connections")
.tag("pool", "primary")
.register(registry);
}
public void acquireConnection() {
activeConnections.incrementAndGet();
}
public void releaseConnection() {
activeConnections.decrementAndGet();
}
}
One caveat worth knowing: Micrometer holds a weak reference to the gauge’s state object. If activeConnections were a short-lived object instead of a field, the gauge would report NaN after garbage collection.
Timer — measure operation duration
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
private final Timer paymentProcessingTimer;
public PaymentService(MeterRegistry registry) {
this.paymentProcessingTimer = Timer.builder("payment.processing.duration")
.description("Time spent processing payments")
.tag("provider", "stripe")
.publishPercentiles(0.5, 0.95, 0.99)
.register(registry);
}
public PaymentResult processPayment(PaymentRequest request) {
return paymentProcessingTimer.record(() -> {
// ... process payment ...
return new PaymentResult("success");
});
}
}
Timer with manual start/stop
Keep the Timer as a field. Building or registering a meter inside the request path does a registry lookup per call — small, but it adds up on hot endpoints and it’s exactly what the best practices below tell you to avoid.
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;
@Service
public class DatabaseQueryExecutor {
private final MeterRegistry registry;
private final Timer dbQueryTimer;
private final JdbcTemplate jdbcTemplate; // injected
private final RowMapper<User> userRowMapper; // injected
public DatabaseQueryExecutor(MeterRegistry registry, JdbcTemplate jdbcTemplate,
RowMapper<User> userRowMapper) {
this.registry = registry;
this.jdbcTemplate = jdbcTemplate;
this.userRowMapper = userRowMapper;
this.dbQueryTimer = Timer.builder("db.query.duration")
.tag("operation", "find_users")
.register(registry);
}
public List<User> findUsers(String query) {
Timer.Sample sample = Timer.start(registry);
try {
return jdbcTemplate.query(query, userRowMapper);
} finally {
sample.stop(dbQueryTimer);
}
}
}
If the outcome matters — say you want a status tag that flips between success and error — keep two timer fields and stop the matching one. A Sample can’t change the tags of the timer it stops.
Distribution summary — track distribution of values
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.MeterRegistry;
@Service
public class OrderSizeTracker {
private final DistributionSummary orderItemCounts;
public OrderSizeTracker(MeterRegistry registry) {
this.orderItemCounts = DistributionSummary.builder("order.item.count")
.description("Number of items per order")
.publishPercentiles(0.5, 0.95, 0.99)
.register(registry);
}
public void recordOrder(int itemCount) {
orderItemCounts.record(itemCount);
}
}
Using @Counted and @Timed annotations
import io.micrometer.core.annotation.Counted;
import io.micrometer.core.annotation.Timed;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Counted(value = "users.searched", description = "Total user searches")
@Timed(value = "users.search.duration", description = "User search time",
percentiles = {0.5, 0.95, 0.99})
public List<User> searchUsers(String query) {
// ... search logic ...
return results;
}
}
Spring Boot auto-configures TimedAspect whenever AOP is on the classpath, so @Timed works out of the box. @Counted needs its aspect declared by hand:
import io.micrometer.core.aop.CountedAspect;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MetricsConfig {
// TimedAspect comes from Spring Boot's MetricsAspectAutoConfiguration —
// only @Counted needs an explicit bean.
@Bean
public CountedAspect countedAspect(MeterRegistry registry) {
return new CountedAspect(registry);
}
}
Multi-dimensional labels
Counter.builder("api.requests")
.tag("method", "GET")
.tag("endpoint", "/api/users")
.tag("status", "200")
.register(registry)
.increment();
Custom metrics with MeterBinder
MeterBinder is a callback interface — implement it, pass in whatever holds your state, and bind gauges to real objects. Here both fields are injected rather than implied:
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
@Configuration
public class CustomMetrics implements MeterBinder {
private final BlockingQueue<Runnable> orderQueue;
private final Map<String, ?> userCache;
public CustomMetrics(BlockingQueue<Runnable> orderQueue, Map<String, ?> userCache) {
this.orderQueue = orderQueue;
this.userCache = userCache;
}
@Override
public void bindTo(MeterRegistry registry) {
Gauge.builder("queue.depth", orderQueue, BlockingQueue::size)
.description("Current queue depth")
.tag("queue", "order-processing")
.register(registry);
Gauge.builder("cache.size", userCache, Map::size)
.description("Current cache entry count")
.tag("cache", "user-cache")
.register(registry);
}
}
How It Works
Every meter you register lands in the MeterRegistry, which keeps one time series per unique combination of name and tag values. Counter.builder("orders.created").tag("type", "standard") produces orders_created_total{type="standard"}. Add another tag value and you get a second, independent series — that’s where cardinality comes from.
The registry then renders all of those series into the Prometheus text exposition format on each scrape. A line looks like orders_created_total{application="user-service",type="standard",} 42.0, with the common tags from management.metrics.tags merged into every label set. Your app keeps writing to memory; Prometheus polls the endpoint every scrape_interval (usually 15s) and stores what it read.
Two consequences of the pull model matter day to day:
- Stale data survives restarts. A counter resets to zero when the JVM bounces, but Prometheus keeps the old samples.
rate()andincrease()handle resets correctly — raw values don’t. - Short-lived jobs need a different path. Batch jobs that die before the next scrape never get read; that’s what the Pushgateway is for — a different recipe.
Picking the right meter type is mostly about what question you want to ask in PromQL:
| Meter | Records | Typical PromQL |
|---|---|---|
Counter | Monotonic totals (orders, errors) | rate(orders_created_total[5m]) |
Gauge | Current values (queue depth, memory) | queue_depth directly |
Timer | Duration + count (request latency) | histogram_quantile(0.95, rate(payment_processing_duration_seconds_bucket[5m])) |
DistributionSummary | Sizes (items per order, payload bytes) | rate(order_item_count_sum[5m]) / rate(order_item_count_count[5m]) |
A note on percentiles: publishPercentiles(0.5, 0.95, 0.99) computes approximated percentiles inside your app per instance — you can’t aggregate them across replicas. publishPercentileHistogram() exposes Prometheus buckets instead, which histogram_quantile() can aggregate across all pods. For multi-instance dashboards, buckets win; for a single service, client-side percentiles are cheaper and simpler.
Cardinality deserves one concrete number before you tag anything: Prometheus keeps a time series per label combination, and each series costs a few KB of memory plus index overhead. A user_id tag on a counter with 50,000 users means 50,000 series on every scrape — the classic way people take down their own monitoring.
Variants
Using Micrometer without Spring Boot
With micrometer-registry-prometheus on Micrometer 1.12+ (Spring Boot 3.2+), the registry lives in the prometheusmetrics package and the HTTP endpoint comes from the Prometheus client 1.x builder API:
import io.micrometer.core.instrument.Counter;
import io.micrometer.prometheusmetrics.PrometheusConfig;
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
import io.prometheus.metrics.exporter.httpserver.HTTPServer;
public class StandaloneApp {
public static void main(String[] args) throws Exception {
PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
Counter counter = Counter.builder("app.requests")
.tag("endpoint", "/api")
.register(registry);
// Replaces the legacy new HTTPServer(port) from the 0.x simpleclient
HTTPServer server = HTTPServer.builder().port(9090).buildAndStart();
counter.increment();
server.stop();
}
}
If you’re stuck on the legacy Prometheus simpleclient 0.x, use the micrometer-registry-prometheus-simpleclient module instead — there the registry is io.micrometer.prometheus.PrometheusMeterRegistry and io.prometheus.client.exporter.HTTPServer still exists.
Using Micrometer with Kotlin
@Service
class OrderService(registry: MeterRegistry) {
private val ordersCreated = Counter.builder("orders.created")
.description("Total orders created")
.register(registry)
fun createOrder(request: OrderRequest) {
ordersCreated.increment()
}
}
Best Practices
- Use tags for dimensions (method, status, endpoint) — don’t create separate metric names per combination
- Keep cardinality low — avoid tagging with user IDs, request IDs, or other high-cardinality values
- Prefer
publishPercentileHistogram()overpublishPercentiles()when you aggregate across instances - Name metrics with dots:
orders.created, notorders_created— Micrometer normalizes to the registry’s convention - Register metrics at construction time, not in hot paths — a
Samplestops an already-registered timer - Use
@Timedand@Countedfor simple cases — manual timers for fine-grained control or outcome-dependent tags - Set
management.metrics.tags.applicationglobally to identify your service in multi-service dashboards - For a deeper walkthrough of the Actuator side, see Custom Health Checks with Spring Boot Actuator and the sibling Prometheus API monitoring recipe
Common Mistakes
- High-cardinality labels: tagging with
user_idorrequest_idcreates a new time series per value. Prometheus memory explodes. - Creating meters in hot paths:
Counter.builder().register(registry)inside a request handler pays a registry lookup on every call. Register once in the constructor. - Client-side percentiles in dashboards:
publishPercentilesgives per-instance approximations that can’t be summed or averaged across replicas. Use histogram buckets for anything fleet-wide. - Gauges bound to temporary objects: the registry weak-references the state object — if it gets garbage-collected, the gauge silently reads
NaNinstead of failing. - Not exposing the endpoint: forgetting
management.endpoints.web.exposure.include: prometheusmeans Prometheus can’t scrape. - Declaring
TimedAspectmanually: Spring Boot already registers it viaMetricsAspectAutoConfiguration; a second bean is redundant. OnlyCountedAspectneeds the explicit bean.
See Also
- Micrometer reference documentation — meters, registries, and concepts
- Prometheus exposition formats — the text format your registry emits
- Spring Boot Actuator metrics — auto-configured meters and endpoint flags
- Complete guide: Prometheus and Grafana on this site
- Runnable companion code — the services and standalone app from this recipe
Frequently Asked Questions
How do I scrape metrics with Prometheus?
Add a scrape config in prometheus.yml pointing at the Actuator endpoint:
scrape_configs:
- job_name: "user-service"
metrics_path: "/actuator/prometheus"
static_configs:
- targets: ["localhost:8080"]
What is the difference between a Counter and a Gauge?
A counter only goes up (until the process restarts) — use it for totals. A gauge moves both ways — use it for current state like queue depth or active connections. If the number you care about can decrease, it's a gauge.
How do I reset metrics between tests?
Call registry.clear() in @BeforeEach, or use a SimpleMeterRegistry for unit tests so nothing touches your real registry.
Can I use Micrometer with non-Spring applications?
Yes — build a PrometheusMeterRegistry directly and expose an HTTPServer for the scrape endpoint. The meter API is identical; only the wiring changes.
How do I track error rate as a metric?
Keep two counters — requests_total and requests_failed — and compute the ratio in Grafana with PromQL:
rate(requests_failed_total[5m]) / rate(requests_total[5m])
Related Resources
Expose Custom Application Metrics with Python and Prometheus
Build a custom Prometheus metrics exporter in Python using prometheus_client. Covers counters, gauges, histograms, summaries, and Flask/FastAPI integration.
RecipePrometheus API Monitoring
Monitor API performance and health with Prometheus metrics, custom collectors, and alerting rules.
RecipeMetrics Collection: Prometheus, StatsD & OpenTelemetry
Collect, aggregate, and expose application and infrastructure metrics with Prometheus, StatsD, and OpenTelemetry for monitoring and alerting.
GuidePrometheus and Grafana: Metrics, Dashboards, Alerting
Instrument services with Prometheus metrics, query them in PromQL, build Grafana dashboards, and ship alerting rules that don't flap.
RecipeCustom Health Checks with Spring Boot Actuator
How to implement custom health indicators with Spring Boot Actuator, including database, Redis, external API checks, and Kubernetes readiness probes.
RecipeDistributed Tracing with OpenTelemetry
How to implement distributed tracing in Python with OpenTelemetry SDK, including spans, context propagation, auto-instrumentation, and Jaeger export.