Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

In a Spring Boot service, record the number of orders placed per payment method and the time taken to process an order with Micrometer. Which meter types do you use, and what is the cardinality risk?

We inject MeterRegistry and use a Counter tagged with the payment method, Counter.builder("orders.placed").tag("payment.method", method).register(registry).increment(), and a Timer for processing time, either Timer.builder("orders.processing").register(registry).record(() -> process(order)) or a Timer.Sample. Tags must have a small, bounded set of values: never user ids, order ids or raw URLs, because every distinct tag combination is a separate time series that multiplies storage and cost in the metrics backend. With micrometer-registry-prometheus on the classpath, Spring Boot exposes the metrics at /actuator/prometheus.

Why this question is asked

Business metrics such as orders per payment method are some of the most useful graphs a team can have, and Micrometer makes them a few lines of code. The part that goes wrong is not the code but the tags: one careless tag can create millions of time series and a surprising bill or a crashed metrics server. Interviewers ask this to check that we know which meter type fits which question and how to keep cardinality under control. In this answer, we will recap Micrometer's model, record the counter, time the processing in two ways, see what Prometheus receives, and look closely at cardinality.

1A Quick Recap of Micrometer

Micrometer is the metrics facade Spring Boot uses, much like SLF4J is for logging. We record measurements through its API, and a registry translates them for a particular backend such as Prometheus, Datadog or OTLP. Spring Boot auto-configures a MeterRegistry bean, so we just inject it.

A meter is identified by a name and a set of tags, key-value pairs that let us slice the data, such as payment.method=card. The meter type decides what is measured. A Counter counts events and only goes up. A Timer measures how long something takes and records the count, the total time and the maximum, plus optional percentiles or histogram buckets. A Gauge samples a current value, such as a queue's size.

2Counting Orders per Payment Method

Orders placed is a count of events, so we use a Counter with a payment.method tag.

Java
@Service
class OrderService {
private final MeterRegistry registry;
OrderService(MeterRegistry registry) { this.registry = registry; }
public void place(Order order) {
process(order);
Counter.builder("orders.placed")
.description("Orders placed")
.tag("payment.method", order.paymentMethod().name().toLowerCase()) // card, paypal, bank_transfer
.register(registry) // returns the existing counter after the first call
.increment();
}
}
// three card orders and one paypal order ->
// orders.placed{payment.method=card} = 3
// orders.placed{payment.method=paypal} = 1

Notice that calling register on every order is fine: the registry returns the existing counter for the same name and tags, so no duplicate meters are created. For a hot path, we can also cache counters per payment method in a map or an EnumMap to skip the lookup. Using an enum for the tag value is a good habit, because it guarantees a small, fixed set of values.

3Timing the Processing

Processing time is a duration, so we use a Timer. The simplest way is to let the timer run the code.

Java
private final Timer processing = Timer.builder("orders.processing")
.description("Time to process an order")
.publishPercentileHistogram() // buckets so the backend can compute p95, p99
.register(registry);
public void place(Order order) {
processing.record(() -> process(order)); // measures the lambda, records even if it is fast or slow
}
// when start and stop happen in different places, use a sample
Timer.Sample sample = Timer.start(registry);
try {
process(order);
} finally {
sample.stop(registry.timer("orders.processing", "outcome", "success")); // records the elapsed time
}

A Timer.Sample is useful when the operation does not fit inside one lambda, for example when we want to choose the tags after we know the outcome, such as success or failure. An outcome tag with two or three values is a good, bounded tag. Spring also offers the Observation API and @Observed, which produce timers and traces together; for a single business timer, the Timer API above is the most direct.

4What Prometheus Receives

With micrometer-registry-prometheus on the classpath and the endpoint exposed through management.endpoints.web.exposure.include=prometheus (or health,prometheus), Spring Boot serves the metrics at /actuator/prometheus. Micrometer converts dots to underscores, adds base units and suffixes, and Prometheus scrapes the text.

Java
# GET /actuator/prometheus
orders_placed_total{payment_method="card"} 3.0
orders_placed_total{payment_method="paypal"} 1.0
orders_processing_seconds_count 4.0
orders_processing_seconds_sum 0.812
orders_processing_seconds_max 0.305
orders_processing_seconds_bucket{le="0.1"} 1.0
# ... more buckets

From these series, a Prometheus query such as rate(orders_placed_total[5m]) gives orders per second per payment method, and histogram_quantile over the buckets gives the p99 processing time. Notice that the counter got a _total suffix and the timer is reported in seconds, which are Prometheus conventions that Micrometer applies for us.

5The Cardinality Risk

Cardinality is the number of distinct time series a metric produces, and it equals the number of distinct combinations of tag values. Each series costs memory in our application, storage and indexing in the metrics backend, and often money, because many hosted services bill per series.

With payment.method having 4 values, orders.placed has 4 series. If we add region with 3 values and outcome with 2, it has 4 x 3 x 2 = 24, still fine. But if someone adds a customer.id tag, with 2 million customers, the metric has millions of series, and every histogram bucket of the timer multiplies that again. The application's memory grows, scrapes become slow, and the backend may refuse the data or produce a huge bill.

How tags multiply time series
Tags on orders.placedValues eachSeries
payment.method44
payment.method, region, outcome4 x 3 x 224
... plus customer.idx 2,000,00048,000,000
... plus raw URL path with idsunboundedgrows forever

6Keeping Tags Bounded

The rule is that every tag must have a small, known set of values, typically under a hundred. User ids, order ids, email addresses, session ids and raw URLs with ids in them are never tags. For HTTP metrics, Spring Boot already tags with the URI template, such as /orders/{id}, rather than the raw path, for exactly this reason. When we need per-order or per-customer detail, it belongs in logs or traces, which are designed for high-cardinality data.

As a safety net, a MeterFilter can cap the number of distinct values for a tag and deny further ones, so a mistake cannot bring down the metrics pipeline.

Java
@Bean
MeterFilter limitPaymentMethods() {
return MeterFilter.maximumAllowableTags("orders.placed", "payment.method", 20, MeterFilter.deny());
}
// after 20 distinct payment.method values, new ones are dropped instead of creating series

7Follow-up questions

Why not use a Gauge for the number of orders?

A gauge samples a current value, such as items in a queue right now, and can go up and down. Orders placed is a stream of events, and we want rates over time; a counter that only increases lets the backend compute rates correctly even across restarts, which a gauge cannot.

Should the timer also count orders, so we do not need the counter?

A timer does record a count, so orders_processing_seconds_count already counts processed orders. A separate counter is still clearer when the business question is orders by payment method, and it can be incremented only on success while the timer records every attempt.

How do you add common tags such as the application name?

With management.metrics.tags.application=orders-service in configuration, or a MeterRegistryCustomizer bean. Common tags are applied to every meter, so they must be low-cardinality too.

8Conclusion

In this answer, we used Micrometer to count orders per payment method with a tagged Counter and to measure processing time with a Timer, either by recording a lambda or with a Timer.Sample. Spring Boot exposes them at /actuator/prometheus when the Prometheus registry is present. Every distinct combination of tag values is its own time series, so tags must have small, bounded value sets, and per-customer or per-order detail belongs in logs and traces.

What to say in the interviewAbout 100 seconds aloud

Open with

I would inject the MeterRegistry that Spring Boot auto-configures. Orders placed is a count of events, so I use a Counter: Counter dot builder orders dot placed, with a tag payment dot method set from an enum, register it with the registry and increment.

Then, if they want more

Calling register each time is fine because the registry returns the existing counter for the same name and tags, but on a hot path I might cache them per payment method.

Processing time is a duration, so I use a Timer: Timer dot builder orders dot processing, usually with publishPercentileHistogram so the backend can compute p95 and p99, and then timer dot record with a lambda around the processing.

If the start and stop are in different places, or I want to tag the outcome after the fact, I use Timer dot start to get a Sample and stop it with the timer.

With micrometer-registry-prometheus on the classpath and the endpoint exposed, these appear at slash actuator slash prometheus as orders_placed_total by payment method and orders_processing_seconds count, sum, max and buckets. The cardinality risk is that each unique combination of tag values is a separate time series.

Payment method with four values is four series, but tagging with a customer id or order id or raw URL would create millions, blowing up memory and the backend's cost. So tags must have small bounded value sets, high-cardinality detail goes to logs and traces, and I would add a MeterFilter that caps tag values as a safety net.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In a Spring Boot service, record the number of orders placed per payment method and the...": https://scrivio-interview-library.netlify.app/spring-boot/observability/fa5d169959/