Observability
Metrics
Numbers about your running application: how many, how fast, how full.
Logs tell you what happened to one request. Metrics tell you how the whole application is doing over time: requests per second, how many fail, how slow the slowest ones are, how much memory is used. They are tiny (a number and a timestamp), cheap to store for months, and they are what you draw on a dashboard and alert on.
Your application only keeps the numbers and shows them at GET /metrics; a server called Prometheus comes to read them regularly (this is called scraping) and stores the history. Or, if you cannot be scraped, the application can push them instead.
Turn it on
Kest.run<AppModule> { import(MetricsModule.forRoot { jvm = true }) }
app.http(adapter) { useMetrics(registry) } // GET /metrics, and measures every requestOpen http://localhost:8080/metrics and you will see plain text like:
http_requests_total{method="GET",route="/users/{id}",status="200"} 1423
http_request_duration_seconds_bucket{method="GET",route="/users/{id}",le="0.05"} 1390
jvm_memory_used_bytes{area="heap"} 183500000The three kinds of metric
| Kind | Real-life picture | Goes | Example |
|---|---|---|---|
| Counter | a car's odometer | only up | requests served, orders placed, errors |
| Gauge | a fuel gauge or thermometer | up and down | requests in flight right now, queue length, open connections |
| Histogram | a tally of how many fell into each range | each value is dropped in a bucket | how long requests took, order values |
You do not look at a counter's raw value (it only grows). You look at its rate: "requests per second over the last 5 minutes". A histogram lets you ask for percentiles: "95% of requests took less than 120 ms" (the p95). Averages hide slow requests; percentiles show them.
What is measured for you
| Metric | Labels |
|---|---|
http_requests_total | method, route, status |
http_request_duration_seconds (histogram) | method, route |
http_requests_in_flight | |
jvm_memory_used_bytes, jvm_memory_max_bytes | area |
jvm_threads_live, jvm_threads_peak, jvm_classes_loaded | |
jvm_gc_collections_total, jvm_gc_pause_seconds_total | gc |
process_uptime_seconds, process_cpu_usage, system_load_average, system_cpu_count |
route is the path with ids folded to {id} (numbers, UUIDs and long hex strings), so the label stays small however many records you have. Scrapes of /metrics itself are not counted.
Your own
Measure what your business cares about, not just the technology:
@Injectable
class Orders(private val metrics: MetricsRegistry) {
private val placed = metrics.counter("orders_placed_total", "Orders placed", "channel")
private val value = metrics.histogram("order_value_dollars", "Order value", doubleArrayOf(10.0, 50.0, 100.0, 500.0))
init { metrics.gauge("orders_open", "Open orders") { openOrders().toDouble() } } // read at each scrape
fun place(o: Order) { placed.inc("web"); value.observe(o.total) }
}counter, gauge (set, inc, dec), histogram (observe, time { }), a callback gauge, and collector for a family computed at scrape time. Asking for the same name twice returns the same metric; a name used for a different kind is an error, and so is a wrong number of label values.
Method decorators
@Injectable
open class Checkout {
@Timed("checkout_seconds") @Counted("checkout_calls_total") open fun pay(order: Order) { ... }
}@Timed observes the duration into a histogram with the labels class, method, outcome (ok or error); @Counted counts calls with the same labels. Both need an open class and method, see method decorators.
Naming and labels (this is where people go wrong)
- Names:
snake_case, a unit suffix, and_totalon counters:orders_placed_total,checkout_duration_seconds,queue_depth. Use base units (seconds, bytes), never milliseconds. - Labels split one metric into many series.
orders_placed_total{channel="web"}and{channel="app"}are two series, which is good: you can sum or compare them. - Never use an unbounded value as a label: a user id, an email, a full URL, an order id. Each distinct value creates a new series stored forever; a million users make a million series and bring Prometheus down. This is called a cardinality explosion. Labels should have tens of values, not thousands. Put ids in logs and traces instead.
Reading them in Prometheus (PromQL)
| You want | Query |
|---|---|
| requests per second | sum(rate(http_requests_total[5m])) |
| share of failures | sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) |
| p95 latency | histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) |
| busiest routes | topk(5, sum by (route) (rate(http_requests_total[5m]))) |
| heap in use | jvm_memory_used_bytes{area="heap"} |
Getting the numbers into Prometheus
# prometheus.yml
scrape_configs:
- job_name: shop-api
metrics_path: /metrics
scrape_interval: 15s
static_configs: [{ targets: ["shop-api:8080"] }]For a whole ready-made stack (Prometheus, Grafana, Loki, Tempo) see the LGTM stack. For a quick look without any server, use the built-in dashboard. Alert rules are in Production rules.
Testing
Create a MetricsRegistry() in the test, run the code, and assert counter.value("web") or search registry.expose() for the line. 3200 requests from 16 threads are counted exactly in the test suite.