The Analogy: The Factory Control Room, the Shift Log, and the Main Breaker
Walk into the control room of a bottling plant and the first thing you see is a wall of gauges. One dial reads line speed, another the fill-head pressure, another the reject-chute count, another the motor temperature. Not one of them tells the story of a single bottle. Together they tell you, at a glance, whether the line is healthy: pressure climbing while throughput falls means a blockage is forming downstream, and you know it before a single crate ships short. That wall is your metrics -- a small set of continuously readable numbers, each folding thousands of individual events into a shape a human can scan in a second.
Beside the panel sits a bound shift logbook. When something notable happens, the operator writes a dated line: which machine, which batch, what was observed, what was done. The log is not for the glance; it is for the investigation afterwards. A gauge tells you the reject rate doubled somewhere in the last hour, but the logbook, if the entries are disciplined and each carries the batch number, tells you which batch, which operator, and what changed. A panel without a log leaves you knowing that something broke but not what; a log without a panel leaves you reading every line to notice a trend the eye would have caught in an instant.
The room draws its power from one supply, and that supply is protected by a main breaker rated for a fixed number of amps. Every machine on the floor pulls from it. The breaker does not care what any single machine is doing; it sums the whole floor's draw, and the instant that sum crosses the rating it trips and the entire line goes dark -- not the one greedy machine, everything. Sizing is therefore a whole-room question: the sum of every machine's peak draw, plus a margin, must sit under the rating. A plant that commissions a new machine rated to pull right up to the last spare amp, with no headroom, has built a line that trips on the first ordinary surge.
The failure mode is two-sided and both sides are common. First, an eager engineer decides the panel should carry a separate labelled gauge for every work-order number that passes through, and within a shift the wall needs thousands of tiny dials, overflows the room, and no human can read any of it; the panel that was meant to be scannable has become unreadable noise, and the recorder behind it runs out of paper. Second, the new machine is sized to draw right up to the breaker's rating, so the moment metaspace, thread stacks, and buffers pull their share on top of the heap, the summed draw crosses the limit and the main breaker trips, killing every process in the room with no warning light and no note in the log -- just a dark room and a restart.
Syntax or Core Structure
Metrics in Spring Boot come from Micrometer, a vendor-neutral facade: you instrument once and choose a backend by adding a dependency. spring-boot-starter-actuator plus micrometer-registry-prometheus exposes JVM, HTTP, and connection-pool metrics at /actuator/prometheus with no code at all. The one rule that governs every cost decision downstream is this: each distinct combination of a meter's tag values is a separate stored time series -- one more dial on the wall.
@Service
public class OrderMetrics {
private final MeterRegistry registry;
public OrderMetrics(MeterRegistry registry) {
this.registry = registry;
}
// method (4 verbs) x uri (10 templates) x status (5 classes)
public void record(String method, String uri, int status, long ms) {
Timer.builder("http_server_requests")
.tag("method", method) // GET, POST, PUT, DELETE
.tag("uri", uri) // templated: /orders/{id}
.tag("status", String.valueOf(status)) // 200, 400, 404, 409, 500
.register(registry)
.record(ms, TimeUnit.MILLISECONDS);
}
}
One meter name is declared, but the registry keeps one time series per distinct tag-value combination it has ever observed. With a bounded method, uri, and status vocabulary the series count is simply the product of the distinct values, and that product is exactly how many dials the backend must hold on the wall:
Output:
tag distinct values running product
----------------------------------------------
method 4 4
uri 10 40
status 5 200
----------------------------------------------
one timer registered : 1
time series exported : 200
Three small vocabularies already produce two hundred series from a single meter name, and that is perfectly fine -- two hundred dials fit on a wall. The count stays readable only because every tag draws from a fixed, small set of values. The moment one tag can take an unbounded set of values, the product runs away from you, which is exactly the trap the next section takes apart.
Technical Depth: Percentiles, Cardinality and the JVM Footprint
The starter hands you meters for free, but reading them well rests on three ideas: which meter type answers which question, why percentiles beat averages and how they are actually computed, and how a single careless tag turns a readable panel into thousands of unreadable dials.
| Meter | Emits | Read it for |
|---|---|---|
| Counter | a monotonic running total | request counts, error counts |
| Gauge | the current instantaneous value | queue depth, pool usage, cache size |
| Timer | count, sum, max, and rank estimates | latency of an operation |
| DistributionSummary | count, sum, max, and a histogram | payload and batch sizes |
Percentiles by nearest rank
An average latency hides the shape of the distribution: if ninety-five requests in a hundred take 50 ms and five take 8 seconds, the mean still looks calm while a twentieth of your users suffer. Percentiles read the tail directly. The nearest-rank method sorts the sample of N observations and returns the value at rank ceil(p/100 * N), counting from one -- no interpolation, always a real observed value.
// sorted latency sample, N = 20 (ms)
int[] s = {10,12,14,15,18,20,21,23,25,28,30,33,35,40,45,50,60,75,90,120};
int n = s.length;
for (int p : new int[]{50, 75, 90, 95, 99}) {
int rank = (int) Math.ceil(p / 100.0 * n); // 1-indexed
System.out.println("p" + p + " = " + s[rank - 1] + " ms");
}
Output:
percentile fractional rank ceil rank latency (ms)
-------------------------------------------------------
p50 10.00 10 28
p75 15.00 15 45
p90 18.00 18 75
p95 19.00 19 90
p99 19.80 20 120
-------------------------------------------------------
sample size : 20
max observed (ms) : 120
p99 by nearest rank : 120
The p99 lands on the single worst observation only because this sample is tiny; on a real stream the rank picks the value 99 percent of requests come in under. The number that matters operationally is that tail, not the 28 ms typical case. One caution the table cannot show: a client-side percentile is computed per instance, so you cannot average three pods' p99 values and recover the fleet p99 -- averaging percentiles is meaningless. To aggregate correctly you export histogram buckets with percentiles-histogram and let the backend merge them.
When one tag explodes the whole panel
Because the series count is a product, adding a tag does not add series -- it multiplies them by that tag's distinct-value count. The two hundred series from the previous section are the safe baseline. Add a userId tag carrying five thousand active users and every one of those two hundred series forks into five thousand; add a raw sessionId and it is worse again. The meter name has not changed at all; the wall has.
// baseline: method(4) x uri(10) x status(5)
int base = 4 * 10 * 5; // 200
int withUser = base * 5_000; // one tag, 5000 users
int withSession = base * 20_000; // one tag, 20000 sessions
Output:
scenario base series multiplier total series
--------------------------------------------------------------
templated, bounded tags 200 1 200
plus userId (5000) 200 5000 1000000
plus sessionId (20000) 200 20000 4000000
--------------------------------------------------------------
prometheus soft budget : 100000
bounded within budget : yes
userId within budget : no
worst-case series : 4000000
The baseline sits comfortably under a typical hundred-thousand-series budget, but the single userId tag blows straight through it by an order of magnitude, and the scrape then carries a million lines the backend must ingest, index, and hold in memory on every interval. This is the panel overflowing with a dial per work-order: not a gradual slowdown but a cliff, and it takes monitoring down for every service that shares the backend. The remedy is a discipline, not a setting -- keep identifiers in logs, where one more field costs one more field, and keep tags to templated paths and status classes, whose vocabulary is fixed and small.
Real World Example: Sizing a Metered Service in a 512 MiB Container
The store API ships as a layered image, runs as a non-root user, exposes Prometheus and split health probes, and is deployed with a 512 MiB memory limit. Everything below is one deployable unit: the runtime image, the management configuration, and the memory intent handed to the JVM.
FROM eclipse-temurin:21-jre AS runtime
WORKDIR /app
RUN useradd --system --shell /usr/sbin/nologin appuser
COPY --from=build /app/extracted/dependencies/ ./
COPY --from=build /app/extracted/application/ ./
USER appuser
# container limit is 512Mi, so 75 percent of it is handed to the heap
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
management:
endpoints:
web:
exposure:
include: health,metrics,prometheus
endpoint:
health:
probes:
enabled: true # liveness and readiness reported separately
logging:
structured:
format:
console: ecs # one JSON event per line, identifiers not PII
The JVM's resident memory is never the heap alone: metaspace, thread stacks, the code cache, GC structures, and direct byte buffers all live outside it, and here they total a fixed reserve of roughly 160 MiB. MaxRAMPercentage=75 sizes the heap as a fraction of the container limit, and the resident set is that heap plus the off-heap reserve. Whether the pod runs or is OOM-killed with exit 137 is decided by one comparison -- resident set against the limit:
Output:
limit (MiB) MaxRAM% heap (MiB) off-heap (MiB) RSS (MiB) verdict
--------------------------------------------------------------------------
512 75 384 160 544 OOMKilled 137
768 75 576 160 736 running
1024 75 768 160 928 running
512 50 256 160 416 running
--------------------------------------------------------------------------
off-heap reserve (MiB) : 160
container limit (MiB) : 512
heap at 75 percent (MiB) : 384
resident set (MiB) : 544
over the limit by (MiB) : 32
exit code on kill : 137
The first row is the deployment as written, and it is dead on arrival. At a 512 MiB limit, 75 percent gives a 384 MiB heap; add the 160 MiB the JVM needs off-heap and the resident set is 544 MiB, 32 MiB over the breaker's rating. The kernel does not send an OutOfMemoryError the application could catch -- it kills the process outright, the orchestrator records exit 137, and the pod restarts into the same doomed arithmetic. This is the machine wired to draw right up to the main breaker: the heap alone fits, but the whole-room draw does not, and the line goes dark on the first ordinary load. The other rows show the two honest fixes. Keep the 512 MiB limit but drop MaxRAMPercentage to 50, giving a 256 MiB heap and a 416 MiB resident set with room to breathe; or keep 75 percent and raise the limit to 768 MiB, where a 576 MiB heap plus the reserve lands at 736 MiB. Which you choose is a cost decision -- more limit spends cluster capacity, less heap spends throughput and raises GC frequency -- but both keep the summed draw under the rating.
Two flaws are baked into the manifest as shown, beyond the fatal first-row sizing. First, the 160 MiB off-heap reserve is treated as a constant, and it is not: thread stacks grow with pool sizes and direct buffers grow with in-flight I/O, so a 75 percent heap that "just fits" an idle pod can still cross the limit under a connection burst -- the safe percentage must be sized against peak off-heap, not idle. Second, prometheus and health are added to the web exposure with no mention of protecting the management endpoints; if that port is reachable from outside the cluster the metrics leak internal topology, latencies, and pool sizes to anyone who scrapes it, and the structured-logging block cannot by itself stop a careless addKeyValue("token", secret) from writing a credential into the log store. The panel and the breaker are only ever as safe as the discipline around them.
Common Mistakes
- Tagging a metric with an unbounded value. A
userId,orderId, or raw URL tag multiplies your whole series count by its distinct-value count, and a two-hundred-series meter becomes a million overnight. It is one of the fastest ways to take down monitoring for an entire organisation. Put identifiers in logs; tag only bounded vocabularies. - Reading averages instead of percentiles. A mean of 28 ms is a comfortable lie when the p99 is 8 seconds. Averages hide the tail that users actually feel. Alert and report on p95 and p99, and keep the mean only for capacity sums.
- Averaging percentiles across instances. The p99 from three pods cannot be averaged into a fleet p99 -- percentiles are not additive. Export histogram buckets with
percentiles-histogramand let the backend merge them, or your dashboards quietly report a number that means nothing. - Logging secrets or full request bodies. Tokens, passwords, card numbers, and
Authorizationheaders written to a log store leak to a far wider audience than your database, retained for months. A singleaddKeyValue("token", secret)is a credential breach with a long tail. - Setting the heap equal to the container memory limit.
-Xmx512min a 512Mi container leaves nothing for metaspace, stacks, and buffers, so the kernel OOM-kills the process with exit 137 and noOutOfMemoryError. Size the heap below the limit by the off-heap reserve, or useMaxRAMPercentage. - Assuming an old JVM sees the container limit. JVMs without container support read the host's total RAM and size the heap for a machine they are not allowed to use, then get killed. Run a container-aware JVM and express memory as a percentage of the limit.
- Exposing every actuator endpoint publicly.
include: "*"publishesenv,heapdump, andthreaddump, handing configuration, secrets in properties, and a full memory image to anyone who can reach the port. Expose onlyhealth,info, andprometheus, and secure the management port. - Conflating liveness and readiness. If a readiness failure on a slow dependency is wired to the liveness probe, every instance restarts at once and you turn a slow dependency into a full outage. Liveness answers "restart this?"; readiness answers "route to this?".
- Paging on causes instead of symptoms. Alerting on CPU at 80 percent, a single slow request, or a GC pause fires pages nobody acts on, and alert fatigue means the one real page is ignored. Page on error rate and tail latency; leave the rest on a dashboard.
Best Practices
- Add the actuator and Prometheus starters first and lean on the built-in JVM, HTTP, and pool metrics before writing a single custom meter.
- Keep every tag vocabulary bounded -- templated paths, status classes, outcomes -- and push all identifiers into structured logs where a new field costs one field.
- Report and alert on percentiles rather than averages, and export
percentiles-histogrambuckets so the tail aggregates correctly across instances. - Emit one JSON event per line, attach a trace id through the MDC so a request can be followed across services, and never write secrets or personal data.
- Express container memory as
MaxRAMPercentagesized against peak off-heap use, and enableExitOnOutOfMemoryErrorso a dying JVM is replaced instead of thrashing. - Build layered images on a JRE base, run as a dedicated non-root user, and keep secrets out of image layers, which persist in history even after deletion.
- Split liveness and readiness so a slow dependency stops routing to an instance instead of restarting every instance at once.
- Page only on user-visible symptoms such as error rate and tail latency; leave causes like CPU and GC pauses on a dashboard, not a pager.
Practice Exercises
- A
Timernamedhttp_server_requestscarries tagsmethod(5 values),uri(12 values), andstatus(6 values). Compute the exported series count, then the new count after adding anoutcometag with 3 values, then the count after also adding auserIdtag with 8000 users. State which of the three totals stay under a 100000-series budget. - Given the sorted latency sample in milliseconds 8, 10, 12, 15, 20, 25, 30, 45, 70, 110, compute p50, p90, and p99 by the nearest-rank method (rank = ceil(p/100 * N), counted from one). Give N, the three ranks, and the three latency values.
- A container has a 640Mi memory limit,
MaxRAMPercentage=75, and a fixed 160Mi off-heap reserve. Compute the heap size, the resident set, and whether the pod runs or is OOM-killed, then find the largest whole-numberMaxRAMPercentagethat keeps it running. - An actuator configuration uses
include: "*"on a port reachable from outside the cluster and logsaddKeyValue("authHeader", header). Name the exposure each of those two choices creates and state the change you would make to close it.