Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

You are adding per-endpoint request counters and a max-latency gauge to a service doing 100,000 requests per second across 32 cores. Which classes would you use and why?

For the per-endpoint counters I would use a LongAdder per endpoint, because it spreads updates across cells and scales under heavy write contention. For the maximum latency I would use a LongAccumulator with Math::max, which stripes updates the same way. The scraper's sum() or get() calls are cheap compared with a 15-second scrape interval, and the meters live in a map built at startup, or created once with computeIfAbsent, so the hot path never allocates. In a real service I would use Micrometer, which already does all of this.

Why this question is asked

At 100,000 requests per second across 32 cores, the metrics code runs as often as the business code, so a careless choice can cost more CPU than the endpoints themselves. Interviewers ask this scenario to see whether we can pick the right concurrent building blocks for a very common job and also recognise when not to build it ourselves. In this answer, we will see why a plain AtomicLong is the wrong counter here, use LongAdder for counts and LongAccumulator for the maximum, check that reading them is cheap, organise them so the hot path never creates objects, and finally look at how Micrometer gives us the same design ready-made.

1Why Not One AtomicLong per Endpoint?

At 100,000 requests per second, a popular endpoint may take half the traffic. An AtomicLong increment needs exclusive ownership of the cache line holding the value, so 32 cores incrementing it means that line moves between cores tens of thousands of times a second. Each increment then costs a cross-core transfer of around a hundred nanoseconds instead of a few, and that cost lands on every request thread.

We do not need what AtomicLong offers in exchange. Nobody on the request path needs the exact count after its own increment; only the scraper reads the total, every few seconds. So we can trade exact instant reads for cheap writes.

2Counters: A LongAdder per Endpoint

LongAdder keeps a base value and, once threads collide, an array of padded cells. Each thread updates its own cell, so increments from different cores stop contending. The scraper calls sum(), which adds the base and all cells.

Java
final class EndpointMetrics {
final LongAdder requests = new LongAdder();
final LongAdder errors = new LongAdder();
final LongAccumulator maxLatencyNanos = new LongAccumulator(Math::max, 0L);
}
// request thread, after handling the call
EndpointMetrics m = metrics.get(endpoint);
m.requests.increment(); // touches this thread's cell
if (failed) m.errors.increment();
m.maxLatencyNanos.accumulate(elapsedNanos); // keeps the largest value seen

Notice that the counters only ever go up. A monitoring system such as Prometheus computes rates from the difference between two scrapes, so we never reset counters; a reset would look like a counter restart and complicate the rate calculation.

3The Max Gauge: LongAccumulator With Math::max

A maximum is not a sum, so LongAdder does not fit, but LongAccumulator uses the same striped cells with any function that is associative and commutative, meaning the order in which values are combined does not matter. Math::max qualifies. Each thread folds its latency into its own cell, and get() combines the base and the cells with the same function.

A max latency gauge only makes sense over a window: the largest latency since the last scrape, not since the service started, otherwise one slow request at startup would dominate forever. So the scraper reads it with getThenReset(), which returns the current maximum and resets the cells to the identity value, 0 here. Like sum(), it is not atomic with respect to updates happening at the same moment, so a latency recorded during the reset may land in either window or, rarely, be missed. For a monitoring gauge that is an acceptable trade.

Java
// scraper thread, every 15 seconds
long count = m.requests.sum(); // for example 742_118_032, always increasing
long maxNanos = m.maxLatencyNanos.getThenReset(); // for example 183_400_000 (183 ms) in this window
Step throughRecording and scraping
Request threadsLongAdder / LongAccumulatorScraper
increment() into own cell
accumulate(latency) into own cell
100,000 updates per second
sum() every 15 s
base + cells
getThenReset() for max
max of window, cells reset

7 messages in order. Play them, or step through them one at a time.

Writers never contend on one variable; the occasional reader pays the cost of walking the cells.

4Reading Is Cheap Enough

sum() visits the base and at most about 32 cells on this machine, so it costs well under a microsecond. Doing that for a few hundred endpoints every 15 seconds is nothing compared with the work done by the request threads in the same period. This is the whole trade of striped counters: make the very frequent operation cheap and the rare operation a little more expensive.

5Keeping the Hot Path Free of Allocation

The metrics objects should exist before requests arrive. If the endpoints are known at startup, which they usually are with Spring MVC or WebFlux mappings, we build an immutable map once. If they are discovered dynamically, a ConcurrentHashMap with computeIfAbsent creates each entry exactly once. Since Java 9, computeIfAbsent first checks for an existing value without locking, so after the first call per key it is just a lookup.

Java
private final ConcurrentHashMap<String, EndpointMetrics> metrics = new ConcurrentHashMap<>();
EndpointMetrics forEndpoint(String routeTemplate) {
return metrics.computeIfAbsent(routeTemplate, k -> new EndpointMetrics()); // created once per route
}

The key must be the route template, such as /orders/{id}, never the raw path /orders/12345. With raw paths every order id would create a new entry, the map would grow without bound, and we would have built a memory leak with very precise metrics. The broken version is easy to write, which is why the rule deserves a code review check.

6Use Micrometer Rather Than Custom Code

Everything above is what Micrometer, the metrics library Spring Boot uses, already does. A Counter in its registries is backed by a striped adder, a Timer records count, total time and a decaying maximum over a rolling window, and meters are cached by name and tags so repeated lookups return the same object. Spring Boot even records per-endpoint HTTP server timers automatically under http.server.requests, tagged by URI template, method, status and outcome. Writing our own would mean reimplementing export formats, window handling for the max and percentile histograms, with more bugs and no gain. So in a real service the answer is: let Micrometer do it, keep tag values bounded, and register our own meters once.

Java
Timer timer = Timer.builder("orders.lookup")
.tag("route", "/orders/{id}")
.register(registry); // registered once, kept in a field
timer.record(elapsedNanos, TimeUnit.NANOSECONDS); // count, total and max over a rolling window

7Follow-up questions

Why not compute percentiles on the request path?

Exact percentiles need every value or a sorted structure, which is expensive to update concurrently. Micrometer offers histogram buckets, which are a set of striped counters, and client-side percentile estimates; for aggregation across instances, histogram buckets are the better choice because percentiles cannot be averaged.

Is volatile long with a CAS loop for max any worse?

Under low contention it is fine. At this rate, with most requests hitting a few endpoints, a single AtomicLong updated with accumulateAndGet(latency, Math::max) has the same cache line problem as a counter, while LongAccumulator stripes it. Most updates do not raise the maximum, which helps either way.

What happens if the scraper is slower than expected?

Counters are cumulative, so a missed scrape only lowers resolution. The max gauge covers a longer window than intended, which is harmless. Nothing on the request path depends on the scraper.

8Conclusion

In this answer, we chose LongAdder per endpoint for counters because it spreads writes across cells under heavy contention, and LongAccumulator with Math::max for the maximum latency, read with getThenReset so each scrape covers its own window. Reading is cheap relative to the scrape interval, the meters are created at startup or once with computeIfAbsent keyed by route template, and in practice Micrometer already provides this design, so we use it rather than write our own.

What to say in the interviewAbout 90 seconds aloud

Open with

At a hundred thousand requests a second on 32 cores, the main concern is that recording metrics doesn't contend, because it runs on every request. So I wouldn't use AtomicLong; all cores would fight over one cache line per endpoint.

Then, if they want more

For counters I'd use a LongAdder per endpoint, which gives contending threads separate padded cells, and the scraper calls sum. For the maximum latency I'd use a LongAccumulator with Math max, which stripes the same way, and the scraper reads it with getThenReset so each scrape reports the max of its own window rather than since startup.

Reading isn't atomic with concurrent updates, but that's fine for monitoring, and it's cheap: a sum over about 32 cells every 15 seconds is nothing compared with the request load.

I'd make sure nothing is allocated on the hot path: build the map of endpoint metrics at startup from the route mappings, or use computeIfAbsent on a ConcurrentHashMap, which is just a lookup after the first call. And the key must be the route template, not the raw path, or every id creates a new entry and we leak memory.

In practice, though, I'd use Micrometer, which Spring Boot already wires up: its counters and timers use the same striped structures, the timer keeps a rolling max, and http server request metrics are recorded per URI template automatically.

About this answer

Last updated
12 November 2026
Versions it names
Java 9
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 "You are adding per-endpoint request counters and a max-latency gauge to a service doing...": https://scrivio-interview-library.netlify.app/java/atomics/91d6503a83/