Video in progress

Strong Middle 🌱 Spring

How do you add business metrics with Micrometer, and what mistakes should you avoid?

You create a Counter, Timer or Gauge through MeterRegistry, and Actuator exports them to Prometheus and others. The most common mistake is putting an unbounded value (user id, order id) in a tag: the number of metrics explodes.

📖 Answer

@Service
class CheckoutService {
    private final Counter paid;
    private final Timer paymentTimer;

    CheckoutService(MeterRegistry registry) {
        this.paid = Counter.builder("orders.paid")
                .description("Paid orders")
                .tag("channel", "web")
                .register(registry);
        this.paymentTimer = Timer.builder("payment.duration")
                .publishPercentileHistogram()
                .register(registry);
    }

    void pay(Order o) {
        paymentTimer.record(() -> gateway.charge(o));
        paid.increment();
    }
}

Or declaratively: @Timed("payment.duration") / @Observed (if the aspect is enabled).

Things to watch:

  • Tag cardinality. tag("userId", id) opens a separate time series per user, and Prometheus runs out of memory. Keep tag values to a small, fixed set: status, channel, provider.
  • Write names with dots (orders.paid); Micrometer converts them to the Prometheus format (orders_paid_total) itself.
  • Gauge holds a weak reference to the object — if you don't keep a reference to the measured object yourself, GC will collect it.
  • publishPercentiles is computed separately in each instance and can't be aggregated afterwards; if you run many instances, use publishPercentileHistogram.

For alerts, look at the rate of change: if rate(orders_paid_total[5m]) suddenly drops to zero, payments are broken.