4.5 Metrics & Observability
← Back to Chapter 4: Exception Handling, Logging & Production Support
Modern distributed architectures depend on the Three Pillars of Observability: Metrics, Logs, and Traces. Spring Boot integrates Micrometer as the vendor-neutral metrics facade (akin to SLF4J for metrics).
1. Micrometer Core Meter Types
| Meter Type | Characteristic | Real-World Application |
|---|---|---|
| Counter | Monotonically increasing value | Total HTTP requests, completed orders, error counts. |
| Gauge | Instantaneous snapshot value (can go up or down) | Current active thread count, database pool connections, queue size. |
| Timer | Measures both duration latency and count frequency | Endpoint execution time, DB query response times. |
| DistributionSummary | Tracks distribution of events not related to time | Payload sizes in bytes, batch processing sizes. |
2. Programmatic Metrics with MeterRegistry
@Service
public class CheckoutService {
private final Counter orderSuccessCounter;
private final Timer checkoutLatencyTimer;
public CheckoutService(MeterRegistry registry) {
this.orderSuccessCounter = Counter.builder("business.orders.placed")
.description("Total successfully placed orders")
.tag("region", "ap-south-1")
.register(registry);
this.checkoutLatencyTimer = Timer.builder("business.orders.checkout.time")
.description("Time taken to process complete checkout flow")
.publishPercentiles(0.5, 0.95, 0.99)
.register(registry);
}
public OrderResult process(OrderRequest request) {
return checkoutLatencyTimer.record(() -> {
// Execution logic
OrderResult result = executeCheckout(request);
orderSuccessCounter.increment();
return result;
});
}
}
3. Prometheus & Distributed Tracing Integration
Prometheus Scraping
Add micrometer-registry-prometheus. Actuator automatically exposes /actuator/prometheus formatted for Prometheus scraper jobs:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
Distributed Tracing in Spring Boot 3
Spring Boot 3 replaced Spring Cloud Sleuth with Micrometer Tracing supporting OpenTelemetry (OTel) and Brave/Zipkin:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>
With this dependency, every incoming HTTP request generates a traceId and spanId automatically propagated into logs and downstream network calls.