Designing custom business metrics with Micrometer and OTel
Design order-domain business metrics in Spring Boot 4 with Micrometer and OTel, control tag cardinality, and jump from Grafana panels to traces via exemplars.
Technical signals like HTTP latency can’t tell you whether orders are actually completing. This post covers designing order-domain metrics with Micrometer, bounding tag cardinality, and jumping straight from a Grafana spike to the underlying Tempo trace with exemplars.
Environment: Spring Boot 4.0.2 (Micrometer 1.16,
spring-boot-starter-opentelemetry), Kotlin 2.2, Java 21, homelab OTel Collector Contrib 0.144.0 (https://otel.namju.kim), Prometheus 2.54.1, Tempo 2.9.1, and Grafana 11.2.
Background
Looking back at real production incidents I’ve dealt with, the earliest alert wasn’t always an HTTP 5xx spike. More often, a business metric—”completed payments dropped below normal”—caught the problem first. When an external payment gateway returns HTTP 200 with a failure code inside the JSON body, standard infrastructure and HTTP dashboards stay completely green.
To test a clean pattern end to end, I added custom order-domain metrics to order-api in my homelab. The app exports metrics over OTLP to otel.namju.kim, and the Collector writes them to Prometheus via remote write, reusing the exact pipeline from my homelab OpenTelemetry Collector setup.
flowchart TD
A["Observation\norder.checkout"] --> B["Timer metric\n(low cardinality)"]
A --> C["Span\n(includes high cardinality)"]
B -->|"OTLP metrics"| D["Collector → Prometheus"]
C -->|"spanmetrics + exemplar"| D
D --> E["Grafana panel → Tempo trace"]
Choosing the right meter type
Pick the Micrometer meter type based on the question you want to answer in a dashboard or alert:
| Meter type | Question it answers | Order-domain example | Key caveat |
|---|---|---|---|
Counter | “How many times did this happen?” | Refund count (reason tag) | Monotonically increasing only; never use for values that go down |
Timer / Observation | “How long did it take and how often did it fail?” | Checkout latency and error rate | Enable histogram buckets if you need percentiles across instances |
DistributionSummary | “What does the size distribution look like?” | Order amount distribution | Define explicit bucket boundaries for continuous values like currency |
Gauge | “What is the current count right now?” | Orders currently awaiting payment | Holds a weak reference; store the backing object in a field |
When not to use it. Never put unbounded identifiers—like orderId, userId, or coupon codes—into metric tags. Every unique tag combination creates a separate time series, driving Prometheus memory usage up linearly until it crashes. Record high-cardinality identifiers in logs or span attributes, and reserve metrics for questions you aggregate over groups. Also, never use metrics for accounting or settlement totals that require exact counts. Metrics are approximations that tolerate dropped batches during restarts or network blips; query your database for exact figures.
How Observation works and implementation
Using Spring’s Observation API emits a metric and a trace span from a single block of code. When an Observation finishes, DefaultMeterObservationHandler records a Timer (order.checkout) and tracks in-flight executions with a LongTaskTimer (order.checkout.active). Simultaneously, DefaultTracingObservationHandler opens and closes a span with the same name.
The real advantage is how Observation separates keys at the API level: low-cardinality keys go to both metric tags and span attributes, while high-cardinality keys go to span attributes only. That makes cardinality hygiene part of the method signature instead of a code-review afterthought.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// src/main/kotlin/kim/namju/order/metrics/OrderMetrics.kt
package kim.namju.order.metrics
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.DistributionSummary
import io.micrometer.core.instrument.Gauge
import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.observation.Observation
import io.micrometer.observation.ObservationRegistry
import org.springframework.stereotype.Component
import java.util.concurrent.atomic.AtomicInteger
import java.util.function.Supplier
enum class PaymentMethod { CARD, TRANSFER, POINT }
enum class RefundReason { CUSTOMER_REQUEST, OUT_OF_STOCK, PAYMENT_ERROR }
@Component
class OrderMetrics(
private val meterRegistry: MeterRegistry,
private val observationRegistry: ObservationRegistry,
) {
// Gauge keeps a weak reference, so retain the backing AtomicInteger as a field
private val pendingOrders = AtomicInteger(0)
private val orderAmount = DistributionSummary.builder("order.amount")
.description("Order amount (KRW)")
.serviceLevelObjectives(10_000.0, 30_000.0, 50_000.0, 100_000.0, 300_000.0)
.register(meterRegistry)
init {
Gauge.builder("order.pending", pendingOrders) { it.get().toDouble() }
.description("Number of orders waiting for payment")
.register(meterRegistry)
}
fun <T> checkout(orderId: Long, method: PaymentMethod, amount: Long, block: () -> T): T {
pendingOrders.incrementAndGet()
try {
val result = Observation.createNotStarted("order.checkout", observationRegistry)
.lowCardinalityKeyValue("payment.method", method.name) // Metric + span
.highCardinalityKeyValue("order.id", orderId.toString()) // Span only
.observe(Supplier { block() })
orderAmount.record(amount.toDouble())
@Suppress("UNCHECKED_CAST")
return result as T
} finally {
pendingOrders.decrementAndGet()
}
}
fun refunded(reason: RefundReason) {
Counter.builder("order.refund")
.tag("reason", reason.name)
.register(meterRegistry)
.increment()
}
}
Even when you constrain tag values with Kotlin enums, another contributor can still introduce a free-form string tag later. Adding a MeterFilter bean enforces a hard ceiling at the registry level, and Spring Boot registers it automatically.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/main/kotlin/kim/namju/order/metrics/MetricsGuardConfig.kt
package kim.namju.order.metrics
import io.micrometer.core.instrument.config.MeterFilter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class MetricsGuardConfig {
// Drop new time series if payment.method on order.* metrics exceeds 10 distinct values
@Bean
fun paymentMethodCardinalityGuard(): MeterFilter =
MeterFilter.maximumAllowableTags("order.", "payment.method", 10, MeterFilter.deny())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
# src/main/resources/application.yml (metrics section)
management:
otlp:
metrics:
export:
url: https://otel.namju.kim/v1/metrics
step: 30s
headers:
Authorization: "Bearer ${OTEL_AUTH_TOKEN}"
metrics:
distribution:
slo:
order.checkout: 200ms,500ms,1s,3s
Linking metrics to traces with exemplars
Exemplars attach a sample trace_id to a histogram bucket so you can click an outlier dot on a latency graph and open the exact trace that caused it. When I checked Micrometer 1.16’s OTLP registry documentation, exemplar export wasn’t supported directly from the app’s Timer. Instead, I configured the Collector’s spanmetrics connector to derive latency histograms with exemplars directly from the order.checkout spans emitted by Observation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Addition to collector/config.yaml
connectors:
spanmetrics:
histogram:
explicit:
buckets: [50ms, 100ms, 200ms, 500ms, 1s, 3s]
dimensions:
- name: payment.method
exemplars:
enabled: true
metrics_flush_interval: 15s
service:
pipelines:
traces/spanmetrics: # Aggregate from all spans before tail sampling
receivers: [otlp/public, otlp/internal]
processors: [memory_limiter]
exporters: [spanmetrics]
metrics:
receivers: [otlp/public, otlp/internal, spanmetrics]
processors: [memory_limiter, batch]
exporters: [prometheusremotewrite]
Prometheus keeps exemplar storage behind a feature flag, so add --enable-feature=exemplar-storage to its startup flags. Then map the trace_id exemplar label to your Tempo data source in Grafana:
1
2
3
4
5
6
7
# Addition to jsonData in grafana/provisioning/datasources/prometheus.yml
jsonData:
timeInterval: 15s
httpMethod: POST
exemplarTraceIdDestinations:
- name: trace_id
datasourceUid: tempo
Grafana panels and alerting
I use three PromQL queries for the order dashboard and alert rules. Remember that prometheusremotewrite converts dots (.) to underscores and appends unit and type suffixes by default (add_metric_suffixes), so confirm the exact metric names in Prometheus’s metric explorer before saving alerts.
# Checkout failure rate by payment method (alert: > 5% for 5 minutes)
sum by (payment_method) (rate(order_checkout_milliseconds_count{error!="none"}[5m]))
/ sum by (payment_method) (rate(order_checkout_milliseconds_count[5m]))
# Checkout p95 latency (enable the Exemplars toggle in the Grafana panel)
histogram_quantile(0.95,
sum by (le) (rate(traces_span_metrics_duration_milliseconds_bucket{span_name="order.checkout"}[5m])))
# Hourly refund trend by reason
sum by (reason) (increase(order_refund_total[1h]))
For notifications, I reused the Contact Point from my homelab Grafana dashboard and alerting setup and set a 5-minute pending window on the checkout failure rate rule so brief payment-gateway blips don’t page me unnecessarily.
Keep your
rate()lookback window at least 4× the OTLP exportstep. With a 30-secondstep, queryingrate(...[1m])leaves two samples or fewer per window, causing gaps and broken lines on your graphs.
Because
spanmetricsaggregates every span before tail sampling, the latency distribution is accurate, but an exemplar’strace_idcan point to a trace that tail sampling later dropped. Error and slow traces match the retention policies so the outlier dots you actually click open cleanly in Tempo, while normal-latency exemplars may return “trace not found.”
Checklist
Designing business metrics turned out to be less about deciding what to measure and more about deciding what never belongs in a tag. Check these five items before deploying:
- Every metric tag value comes from a bounded set such as an enum
- High-cardinality identifiers (
orderId,userId) usehighCardinalityKeyValueso they stay on spans only - A
MeterFiltercaps the maximum number of tag values on custom metric prefixes - PromQL
rate()windows are at least 4× the OTLP exportstep - Tail-sampling retention rules preserve the slow and error traces that your exemplars point to