Sub topic 8
Recording custom counters, timers, and gauges
This chapter assumes you have Actuator and Micrometer running, you can expose the metrics endpoint, and you can inject beans with constructor injection. Spring Boot's built-in metrics cover the JVM, HTTP requests, and the connection pool. They can't tell you how many orders your business accepted or how deep your work queue is. For that you register your own meters through Micrometer's MeterRegistry.
The three meters and when to use each
A meter is a named measurement with optional tags. Each meter type answers a different question.
| Meter | Question it answers | Behavior | Typical use |
|---|---|---|---|
| Counter | How many times did this happen? | Only goes up | Orders placed, errors, retries |
| Timer | How long did this take, and how often? | Records count, total time, and max | Request handling, database calls |
| Gauge | What is the value right now? | Goes up and down, sampled on read | Queue size, active sessions, cache size |
The most common beginner mistake is using a gauge for something that should be a counter. If you only ever add to a value and want a rate, use a counter. If the value can fall, use a gauge.
Counters
A counter is created through a builder and registered with the registry. The builder is useful because it lets you add a description and tags.
Counter placed = Counter.builder("orders.placed")
.description("Number of orders placed")
.tag("channel", "web")
.register(registry);
placed.increment();Registering is idempotent. If you call register again with the same name and the same tags, Micrometer returns the existing counter instead of creating a second one. That makes this shortcut safe even on a hot path:
registry.counter("orders.placed", "channel", "mobile").increment();The shortcut does a lookup on every call, so for very hot paths keep the Counter in a field.
Timers
A timer records how many events happened and how long they took. You can time a block of code directly, or start a sample and stop it later.
timer.record(Runnable)andtimer.record(Supplier<T>)time a block. If the block throws, the time is still recorded.Timer.start(registry)returns aTimer.Sample. You stop it withsample.stop(timer). This is the right choice when the tag you want, such as the outcome, is only known after the work finishes.
Never time work with System.currentTimeMillis() and pass raw numbers around. Timers use a monotonic clock and handle units for you.
Gauges
A gauge differs from the other two because you don't push values into it. You give Micrometer an object and a function. Each time the registry is read, Micrometer calls the function.
AtomicInteger inFlight = new AtomicInteger();
Gauge.builder("orders.in.flight", inFlight, AtomicInteger::get)
.description("Orders currently being processed")
.register(registry);The registry also offers registry.gauge("name", obj) and registry.gauge("name", collection). These return the object you passed in, so you can write AtomicInteger sessions = registry.gauge("sessions.active", new AtomicInteger()); and update it directly. The same weak-reference rule applies, so store the returned object in a field.
A complete service
This service uses all three meters. The timer tag is chosen after the work finishes, so it uses a sample.
import java.util.concurrent.atomic.AtomicInteger;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final MeterRegistry registry;
private final AtomicInteger inFlight = new AtomicInteger();
public OrderService(MeterRegistry registry) {
this.registry = registry;
Gauge.builder("orders.in.flight", inFlight, AtomicInteger::get)
.description("Orders currently being processed")
.register(registry);
}
public void placeOrder(Runnable work) {
Timer.Sample sample = Timer.start(registry);
String outcome = "success";
inFlight.incrementAndGet();
try {
work.run();
} catch (RuntimeException ex) {
outcome = "failure";
throw ex;
} finally {
inFlight.decrementAndGet();
sample.stop(Timer.builder("orders.processing")
.description("Time spent processing an order")
.tag("outcome", outcome)
.register(registry));
registry.counter("orders.placed", "outcome", outcome).increment();
}
}
}The finally block is deliberate. In the chapter's earlier simple version, orderProcessing.record(work) followed by ordersPlaced.increment() skips the counter whenever the work throws. Counting in finally with an outcome tag lets you compute an error ratio later.
Reading the meters through Actuator
Include metrics in the exposure list, call placeOrder a few times, then query the endpoint.
curl http://localhost:8080/actuator/metrics/orders.processing
curl "http://localhost:8080/actuator/metrics/orders.processing?tag=outcome:failure"The response lists measurements and the tags you can still filter by:
{
"name": "orders.processing",
"description": "Time spent processing an order",
"baseUnit": "seconds",
"measurements": [
{ "statistic": "COUNT", "value": 12 },
{ "statistic": "TOTAL_TIME", "value": 1.84 },
{ "statistic": "MAX", "value": 0.31 }
],
"availableTags": [
{ "tag": "outcome", "values": ["success", "failure"] }
]
}Without a tag parameter, the values are aggregated across all tag combinations. A gauge shows a single VALUE measurement, and a counter shows COUNT.
How the names look in Prometheus
Micrometer names use dots. The Prometheus registry converts them to its own conventions. Check the /actuator/prometheus output rather than guessing.
| Micrometer meter | Prometheus series |
|---|---|
| Counter `orders.placed` | `orders_placed_total` |
| Timer `orders.processing` | `orders_processing_seconds_count`, `_sum`, `_max` |
| Gauge `orders.in.flight` | `orders_in_flight` |
The average duration is rate(orders_processing_seconds_sum[5m]) / rate(orders_processing_seconds_count[5m]). Averages hide slow outliers. To compute percentiles in Prometheus, enable histogram buckets with .publishPercentileHistogram() on the timer builder. This adds a _bucket series per boundary, so each bucket multiplies the number of series you store.
Timing methods with @Timed
For simple cases you can annotate a method with @Timed instead of writing timer code. The annotation only works on Spring beans, and it needs the aspect registered. This also requires the spring-boot-starter-aop dependency.
import io.micrometer.core.aop.TimedAspect;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MetricsConfig {
@Bean
TimedAspect timedAspect(MeterRegistry registry) {
return new TimedAspect(registry);
}
}You then write @Timed(value = "orders.lookup", histogram = true) on a service method. Calls from within the same class bypass the Spring proxy and are not timed. This is a common reason an annotation seems to do nothing.
Tags, cardinality, and naming
Every unique combination of tag values creates a separate time series that Prometheus must store. Keep tag values to a small, bounded set.
- Good tags:
channel(web, mobile),outcome(success, failure),region. - Bad tags: user ID, order ID, raw URL with path parameters, exception message.
Other rules to follow:
- Use lowercase dotted names such as
orders.placed. Don't put units or_totalin the name, because the registry adds them. - Prometheus requires that all series with one name use the same set of tag keys. If one call site registers
orders.placedwithchanneland another withoutcome, the Prometheus registry can fail to register the second one. Choose one tag set per name. - Add tags shared by every meter, such as the application name, with
management.metrics.tags.application=shopinstead of repeating them in code.
Registering meters without a service
If a meter does not belong in a business class, implement MeterBinder. Spring Boot calls bindTo for each such bean once the registry exists.
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import java.io.File;
import org.springframework.stereotype.Component;
@Component
public class DiskSpaceMetrics implements MeterBinder {
private final File root = new File("/");
@Override
public void bindTo(MeterRegistry registry) {
Gauge.builder("app.disk.free.bytes", root, File::getUsableSpace)
.baseUnit("bytes")
.register(registry);
}
}The gauge observes root, which the component keeps as a field, so it can't be collected.
Common errors
- A gauge that reports NaN because its observed object was garbage collected.
- A counter that undercounts because
increment()sits after code that can throw. @Timedwith no effect, becauseTimedAspectis missing or the call is internal.- Tag values taken from user input, which creates unbounded series.
- Inconsistent tag keys for one metric name.
- Looking for
orders.placedin Prometheus instead oforders_placed_total.
Exercise
A teammate writes registry.gauge("queue.size", queue.size()) in a constructor. The metric always shows the same value, even as the queue changes. Explain why, and fix it.
Show answer
queue.size() returns a primitive int that is evaluated once, so the gauge observes a fixed boxed number and never calls the queue again. Pass the queue itself and a function: Gauge.builder("queue.size", queue, Queue::size).register(registry);. The queue must be kept in a field of a long-lived bean, so it is not garbage collected and the gauge doesn't turn into NaN.
Exercise
You want to count failed payments by reason. A developer proposes tag("reason", exception.getMessage()). What is the problem, and what would you do instead?
Show answer
Exception messages are unbounded and often contain IDs or timestamps, so each distinct message creates a new time series, which raises memory use in the application and in Prometheus. Map exceptions to a small fixed set of reason values, for example declined, timeout, and invalid_card, and use those as the tag value. Log the full message instead.