Quick revision
The short answer
The recording path should use striped structures such as LongAdder and LongAccumulator so hot paths never contend on one variable, and meters should be created at startup or cached so that recording does no lookup or allocation per call. Reads of a value during updates are approximate, which is fine for metrics. The rules for teams are about cardinality: every distinct tag combination creates its own meters and memory, so tag values must come from small bounded sets. And rather than writing all of this from scratch, the platform team should build a thin layer on an established library such as Micrometer.
What to remember
In this answer, we designed a shared metrics library around its hot path: striped LongAdder and LongAccumulator state so recording never contends, meters created once and kept in fields so recording never looks up or allocates, and lock-free approximate reads by the exporter, which is the right trade for cumulative metrics. The rules for teams centre on bounded tag cardinality, enforced by limits and review, and the whole design is best delivered as a thin layer of conventions over Micrometer rather than a new library.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The recording path should use striped structures such as LongAdder and LongAccumulator so hot paths never contend on one variable, and meters should be created at startup or cached so that recording does no lookup or allocation per call. Reads of a value during updates are approximate, which is fine for metrics. The rules for teams are about cardinality: every distinct tag combination creates its own meters and memory, so tag values must come from small bounded sets. And rather than writing all of this from scratch, the platform team should build a thin layer on an established library such as Micrometer.
Why this question is asked
A shared metrics library is code that runs inside every request of every service, written by a team that does not own those services. That gives its design an unusual weight: a lock or an allocation in the wrong place multiplies across the company, and a missing rule about tags can take down a monitoring system. Interviewers ask this design question at senior level because it combines low-level concurrency choices with API and policy design. In this answer, we will go through the recording path, the registration of meters, the read side, the cardinality rules, and finally why building on Micrometer is the right base.
1The Shape of the Library
It helps to see the parts before designing them. At the top is the API that service code calls, such as counter.increment() or timer.record(duration). Below it, each meter holds its own concurrent state. A registry maps a name and a set of tags to a meter. An exporter reads all meters periodically and sends or exposes them, for example as a Prometheus endpoint. The concurrency demands differ sharply between these layers: recording happens millions of times a second, registration happens a few hundred times at startup, and export happens every few seconds.
- Service codeholds meter references in fields; calls
increment()andrecord() - MetersCounter, Timer, Gauge,
DistributionSummarywith striped state - Registryname + tags -> meter; created once, cached
- Exporterreads every meter each 15 to 60 s; Prometheus, OTLP and others
4 layers, from the top down. Step through them one at a time.
Only the top two layers are on the hot path, so that is where the concurrency design matters most.
2Recording Without Contention
A counter is a LongAdder: under contention, threads spread their increments over padded cells, so 32 cores incrementing the same counter do not fight over one cache line. A timer records a count, a total and a maximum, which map to two LongAdders and a LongAccumulator with Math::max. Histogram buckets for latency distributions are an array of LongAdders, one per bucket, and recording means finding the bucket with a binary search over fixed boundaries and incrementing it.
Notice what is absent: no lock, no synchronized, no map lookup and no allocation. Every recording operation should be a few nanoseconds of uncontended work. We would enforce that with JMH benchmarks in the library's own build at 1, 8 and 32 threads, failing the build if the recording path regresses.
3Registration: Create Once, Cache Forever
Looking up a meter by name and tags means building a key, hashing it and querying a concurrent map, which costs far more than recording. So the rule is to look up meters once, at startup or on first use, and keep the reference in a field, as the example above does. For tags that are only known per request, such as an HTTP status, the library should offer a small cached lookup, for example a pre-built meter per status class, rather than encouraging registry.counter(name, tags) on every call.
Inside the registry, a ConcurrentHashMap with computeIfAbsent guarantees that two threads registering the same meter get the same object. Registration happens rarely, so its cost is unimportant; what matters is that it never happens on the hot path by accident. A debug mode that logs registrations after startup helps teams find code that does.
4Accepting Approximate Reads
The exporter reads each LongAdder with sum() and each max with a get-and-reset style call. These reads take no lock and do not stop writers, so an increment that happens during the read may or may not be included. We document that this is by design: counters are cumulative, so anything missed in one scrape appears in the next, and the monitoring system computes rates from differences between scrapes. Locking the hot path to make one read exact would trade a large, constant cost for a correction nobody needs.
5Rules for Teams: Cardinality
The most important rule is not about threads. Every distinct combination of tag values is a separate time series, with its own meter in memory and its own storage in the monitoring system. A timer tagged with endpoint and status is fine: 50 endpoints times 5 status classes is 250 series. The same timer tagged with userId, with a million users, creates a million meters per instance, each with several adders and maybe 30 histogram buckets. Memory grows without bound, exports grow huge, and the monitoring backend may refuse or drop data for the whole company.
So the library should make the safe path the easy one. Tag values come from bounded sets: route templates instead of raw paths, status classes instead of free-form messages, and enum types where possible. The library can enforce a per-meter-name limit on distinct tag combinations, logging a warning and dropping new combinations beyond it, which Micrometer supports through meter filters. We write these rules in a short guide with examples of good and bad tags, and we review new meters in code review the same way we review new database columns.
| Tag | Distinct values | Verdict |
|---|---|---|
| route template /orders/{id} | about 50 | Good |
| status class 2xx, 4xx, 5xx | 5 | Good |
| raw path /orders/12345 | unbounded | Never: one series per id |
userId or orderId | millions | Never: use logs or traces |
| exception class name | tens | Acceptable, bounded in practice |
6Build on Micrometer, Do Not Replace It
Everything above already exists in Micrometer, which Spring Boot configures by default: striped counters, timers with a rolling maximum, histograms, a registry that caches meters, meter filters for limiting and renaming, and exporters for Prometheus, OTLP and many other backends. Writing our own library would mean re-solving the concurrency problems, the window logic for maxima and the export formats, then maintaining it forever for every service.
The platform team's real value is a thin layer on top: shared naming conventions, common tags such as service and region applied by a MeterFilter, default histogram boundaries suited to our latency targets, cardinality limits switched on by default, and the documentation and review rules. That is a small amount of code that encodes the decisions, while the hard concurrent code stays in a library used and tested by many companies.
7Follow-up questions
Should timers record full histograms by default?
Not for every timer. Each histogram adds dozens of counters per tag combination. A good default is count, total and max for all timers, with histograms enabled for a chosen set of service-level endpoints where percentiles drive alerts.
How do you stop one team's bad tags from hurting others?
With limits in the library, such as a maximum number of tag combinations per meter name, and with limits in the monitoring backend per service. Both should alert the owning team, so the damage stays local and the fix is obvious.
Where do per-request identifiers belong then?
In traces and logs. A trace carries the user or order id for a single request, while metrics describe aggregate behaviour. Exemplars can link a histogram bucket to a sample trace id without making the id a tag.
8Conclusion
In this answer, we designed a shared metrics library around its hot path: striped LongAdder and LongAccumulator state so recording never contends, meters created once and kept in fields so recording never looks up or allocates, and lock-free approximate reads by the exporter, which is the right trade for cumulative metrics. The rules for teams centre on bounded tag cardinality, enforced by limits and review, and the whole design is best delivered as a thin layer of conventions over Micrometer rather than a new library.
Open with
I'd design it around the fact that recording happens on every request in every service, so it has to be nearly free. Counters are striped, LongAdder style, so 32 cores incrementing the same counter don't contend on one cache line; a timer is a count and a total in adders plus a max in a LongAccumulator; histogram buckets are an array of adders.
Then, if they want more
The recording path has no locks, no map lookups and no allocation, and I'd guard that with JMH benchmarks in the library's build. Meters are looked up once, at startup or on first use, and kept in fields; the registry uses computeIfAbsent so two threads get the same meter, but teams shouldn't call registry lookups per request.
On the read side, the exporter reads sums without locking, so a value read during updates is approximate, which is fine because counters are cumulative and rates come from differences between scrapes.
The rule I'd stress most for teams is cardinality: every tag combination is its own set of counters and its own time series, so tags must come from small bounded sets, route templates and status classes, never user ids or raw paths; the library should enforce a limit per meter name and warn.
And I wouldn't write the core from scratch. Micrometer already does all of this, so the platform team should add a thin layer: naming conventions, common tags, histogram defaults, cardinality limits and documentation.
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.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
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 "Your platform team is building a shared metrics library used by every service. Hot paths...": https://scrivio-interview-library.netlify.app/java/atomics/98f6f84b6c/