Sub topic 15
Dashboards, Alerting, and Production Practices
Earlier chapters made the application emit health, metrics, and diagnostics. This chapter covers what happens next: a monitoring system collects the data, people read it on dashboards, and rules wake someone up when users are affected.
This chapter assumes you can expose the prometheus endpoint, you know what a Micrometer counter and timer are, and you can read basic YAML. You do not need prior PromQL (Prometheus's query language) knowledge.
The monitoring loop
Actuator does not store history. It reports the current state at the moment of a request. A separate system must ask for that state repeatedly and keep it.
Prometheus works by pulling. The application never pushes anything. This has a practical consequence: if a scrape fails, Prometheus records up == 0 for that target. The monitoring system itself therefore tells you the application is unreachable.
Preparing the application
Three settings make the data far more useful in a real environment.
management:
metrics:
tags:
application: orders
distribution:
percentiles-histogram:
http.server.requests: truemanagement.metrics.tags.applicationadds a common tag to every meter. With many services in one Prometheus, this lets a dashboard filter by service.percentiles-histogrampublishes histogram buckets for HTTP request timings. Prometheus can then compute percentiles across all instances. Without buckets, a percentile computed inside each instance cannot be combined with those of other instances.
Now tell Prometheus where to look. This configuration assumes the management port is 9090, as set in an earlier chapter.
scrape_configs:
- job_name: orders
metrics_path: /actuator/prometheus
scrape_interval: 15s
static_configs:
- targets: ['orders.internal:9090']In Kubernetes you would normally use service discovery instead of static_configs, but the path and port rules are the same.
Meter names change on export. Micrometer's orders.placed counter becomes orders_placed_total. The orders.processing timer becomes orders_processing_seconds_count, _sum, and _max. HTTP server timings appear as http_server_requests_seconds_*.
What belongs on a dashboard
A dashboard answers one question quickly: is the service healthy right now, and if not, where is the problem? Start with the request-oriented signals (rate, errors, duration), then add resource saturation.
| Question | Metric (Prometheus name) |
|---|---|
| How much traffic? | `http_server_requests_seconds_count` |
| How many requests fail? | same metric, filtered by `status=~"5.."` |
| How slow are requests? | `http_server_requests_seconds_bucket` |
| Is the heap filling up? | `jvm_memory_used_bytes`, `jvm_memory_max_bytes` |
| Is garbage collection hurting? | `jvm_gc_pause_seconds_sum` |
| Is the connection pool exhausted? | `hikaricp_connections_active`, `hikaricp_connections_max` |
| Are request threads busy? | `tomcat_threads_busy_threads` |
| Is the CPU saturated? | `process_cpu_usage` |
Counters only ever go up, so raw values are not useful. Use rate() to turn a counter into a per-second change over a window. Two queries cover most dashboards.
Error ratio over five minutes:
sum(rate(http_server_requests_seconds_count{application="orders", status=~"5.."}[5m]))
/
sum(rate(http_server_requests_seconds_count{application="orders"}[5m]))The 95th percentile latency across all instances, which requires the histogram setting above:
histogram_quantile(0.95,
sum by (le) (rate(http_server_requests_seconds_bucket{application="orders"}[5m])))Add your own business metrics next to these. A chart of rate(orders_placed_total[5m]) often reveals a problem before the error rate does, because a broken checkout flow may return clean 200 responses while producing no orders.
Alerting on symptoms
An alert should mean a person must act. Alert on what users experience (errors, latency, unavailability). Leave causes such as high CPU on the dashboard unless they reliably predict an outage.
groups:
- name: orders-alerts
rules:
- alert: HighErrorRate
expr: |
sum(rate(http_server_requests_seconds_count{application="orders", status=~"5.."}[5m]))
/
sum(rate(http_server_requests_seconds_count{application="orders"}[5m])) > 0.05
for: 10m
labels:
severity: page
annotations:
summary: "More than 5% of orders requests are failing"
- alert: InstanceDown
expr: up{job="orders"} == 0
for: 2m
labels:
severity: page
annotations:
summary: "Prometheus cannot scrape {{ $labels.instance }}"The for clause matters. The condition must hold for the whole period before the alert fires, which filters out brief spikes. Choose it by asking how long a problem must last before a human should care.
The first rule has a gap you should know about. If traffic drops to zero, the denominator is zero and the expression returns no data, so the alert does not fire. Pair error-ratio alerts with a rule on request rate or on up.
Production practices
Keep tag cardinality under control
Each distinct combination of tag values creates a separate time series that Prometheus must store. A tag with unbounded values, such as a user ID, an order ID, or a raw URL, can create millions of series and bring down the monitoring system.
Spring MVC records the URI template (/orders/{id}), not the actual path, so normal controllers are safe. Risk comes from your own meters and from clients hitting unmapped paths. A MeterFilter can set a hard limit as a safety net.
import io.micrometer.core.instrument.config.MeterFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MetricsGuardConfig {
@Bean
MeterFilter limitUriTags() {
// After 100 distinct uri values, further new meters are dropped.
return MeterFilter.maximumAllowableTags(
"http.server.requests", "uri", 100, MeterFilter.deny());
}
}Spring Boot registers every MeterFilter bean with the registry automatically.
Use probes for the right purpose
Kubernetes acts on probe results, so a wrong probe can cause an outage.
Restrict what leaves the application
- Expose only the endpoints you use. Do not expose
env,heapdump, orthreaddumpto a network that unauthenticated clients can reach. A heap dump can contain passwords and tokens. - Serve Actuator on the management port and block that port from the public ingress. Prometheus reaches it over the internal network.
- Require authentication for everything except
healthandinfo, as configured in the security chapter. - Treat
loggerswrite access as a privileged operation. Raising a package toDEBUGtemporarily is a good diagnostic step, but remember to reset it.
Make the data trustworthy
- Add the
applicationtag in every service, and an environment or region tag if you run more than one. - Alert on
upso a broken scrape is never silent. - Test alert rules with real conditions in a staging environment. An alert that has never fired has not been verified.
- Review alerts after each incident. Remove those nobody acted on, because noisy alerts train people to ignore pages.
Common mistakes
- Charting a raw counter instead of
rate(counter[5m]). The line only climbs and hides spikes. - Computing percentiles per instance and averaging them. Use histogram buckets and
histogram_quantileover the summed buckets. - Setting
for: 0mon alerts, which pages on every blip. - Setting a scrape interval shorter than the rate window needs. A
[1m]window with a 60-second scrape interval holds too few samples forrate(). - Exposing the management port through the same public load balancer as the application.
Exercise
A service's /actuator/health/liveness fails whenever the Postgres database is unreachable. During a database outage, Kubernetes restarts all pods repeatedly. What is wrong, and what is the fix?
Show answer
Liveness answers "is this process stuck beyond recovery?", but here it reports a dependency failure. Restarting the pods cannot repair the database and only adds load and delay. Remove the database check from the liveness group so it reflects only the application's own state. Keep it in the readiness group, so affected pods are taken out of traffic without being restarted.
Exercise
You add a timer orders.processing with a tag customerId. After a week, Prometheus memory use has grown sharply. Explain the cause and give two ways to prevent it.
Show answer
Each customer ID creates a new set of time series for the timer, so the number of series grows with the number of customers (high cardinality). Prevent it by removing the customerId tag and recording that detail in logs or traces instead. You can also add a MeterFilter.maximumAllowableTags(...) that denies new values past a fixed limit, as a safety net.
Exercise
Write the PromQL expression for the per-second rate of orders placed, averaged over five minutes, using the counter orders.placed from the earlier chapter.
Show answer
rate(ordersplacedtotal[5m]). Micrometer's dots become underscores and the Prometheus exporter adds the _total suffix to counters.