Sub topic 8
Recording custom counters, timers, and gauges
This chapter assumes you have Actuator and Micrometer running, know how to expose the metrics endpoint, and can inject beans in Spring Boot. The built-in metrics cover the JVM, HTTP requests, and the connection pool. Your own business events need custom meters.
The three meter types
Micrometer gives you a MeterRegistry. You register meters on it, and Actuator then shows them under /actuator/metrics and in the Prometheus output.
| Meter | Measures | Typical use |
|---|---|---|
| Counter | A value that only goes up | Orders placed, errors raised |
| Timer | How long short events take and how often they happen | Request handling, database calls |
| Gauge | A value that goes up and down | Queue size, cache entries, active sessions |
A counter records how many times something happened. A timer records a count, a total time, and a maximum. A gauge reports the current value when a monitoring system reads it.
Counters and timers
Inject MeterRegistry and register each meter once, in the constructor. Registering the same name and tags again returns the existing meter, so this is safe, but you avoid repeated lookups by keeping a field.
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final Counter ordersPlaced;
private final Timer orderProcessing;
public OrderService(MeterRegistry registry) {
this.ordersPlaced = Counter.builder("orders.placed")
.description("Number of orders placed")
.tag("channel", "web")
.register(registry);
this.orderProcessing = Timer.builder("orders.processing")
.description("Time spent processing an order")
.register(registry);
}
public void placeOrder(Runnable work) {
orderProcessing.record(work);
ordersPlaced.increment();
}
}Timer.record(Runnable) runs the work and measures it. If the work throws, the time is still recorded and the exception propagates. The counter increments only when the work succeeds, because the exception skips the next line.
Gauges
A gauge differs from the other two: you do not push values into it. You give Micrometer an object and a function, and it calls the function each time the meter is read.
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.springframework.stereotype.Component;
@Component
public class JobQueue {
private final Queue<String> pending = new ConcurrentLinkedQueue<>();
public JobQueue(MeterRegistry registry) {
Gauge.builder("jobs.pending", pending, Queue::size)
.description("Jobs waiting to run")
.register(registry);
}
public void submit(String job) {
pending.add(job);
}
}Micrometer holds only a weak reference to the observed object. If nothing else references it, the garbage collector can remove it, and the gauge then reports NaN. Here the JobQueue bean owns the queue, so it stays alive.
Reading the results
Call GET /actuator/metrics/orders.processing to see the statistics. The response lists COUNT, TOTAL_TIME, and MAX. To filter by tag, add a query parameter such as ?tag=channel:web.
Common errors
- Unbounded tag values. Each distinct tag value creates a new time series. Tagging by user ID or order ID can exhaust memory and overload your monitoring system. Use tags with a small, fixed set of values, such as channel or status.
- Inconsistent tag keys. Meters with the same name must use the same set of tag keys. Prometheus rejects a meter whose tag keys differ from the first registration.
- Gauge for a count of events. If a value only increases, use a counter. Gauges can miss changes that happen between two reads.
- Names in the wrong style. Use lowercase dot-separated names such as
orders.placed. The Prometheus registry converts them toorders_placed_total.
Exercise
A gauge you registered for a list of active sessions reports NaN after some time. The list was created as a local variable inside a method. What is the likely cause, and how do you fix it?
Show answer
Micrometer holds only a weak reference to the observed object, so once the method returns and nothing else references the list, it is garbage collected. Fix it by keeping the list in a field of a long-lived bean, such as a singleton service, and registering the gauge against that field.
Exercise
You want to count orders by customer ID so you can chart each customer. Why is this a poor use of tags, and what could you do instead?
Show answer
Every customer ID creates a new time series, so the number of series grows without limit and strains memory and the monitoring system. Tag by a bounded value such as channel or status, and look up per-customer data in logs or a database.