Skip to lesson

Basic metrics: response time and error rate

ShopLite is live and a customer says ordering feels slow. Without numbers you can only guess; a few metrics tell you how busy the API is, how often it fails and how long users wait.

The few numbers that matter

RED metrics are three numbers for any API: Rate (requests per second), Errors (the share of requests that fail) and Duration (how long requests take). Count only 5xx answers, the server's fault, as errors.

A metric is a number measured again and again, such as "requests in the last minute". The program below turns one minute of requests into a rate and an error rate.

Example 1 · Rate and error rate from one minute of requests

RedMetricsDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class RedMetricsDemo {    public static void main(String[] args) {        // status codes of all requests in one minute (60 seconds)        List<Integer> statuses = new ArrayList<>();        statuses.addAll(Collections.nCopies(280, 200));        statuses.addAll(Collections.nCopies(6, 201));        statuses.addAll(Collections.nCopies(9, 404));        statuses.addAll(Collections.nCopies(2, 401));        statuses.addAll(Collections.nCopies(3, 500));
        int total = statuses.size();        long serverErrors = statuses.stream().filter(s -> s >= 500).count();        long clientErrors = statuses.stream().filter(s -> s >= 400 && s < 500).count();
        System.out.printf("Requests: %d in 60 s = %.1f per second%n", total, total / 60.0);        System.out.printf("Error rate (5xx): %d of %d = %.1f%%%n", serverErrors, total, 100.0 * serverErrors / total);        System.out.printf("Client errors (4xx): %d = %.1f%%, watched separately%n", clientErrors, 100.0 * clientErrors / total);    }}
Output
Requests: 300 in 60 s = 5.0 per second
Error rate (5xx): 3 of 300 = 1.0%
Client errors (4xx): 11 = 3.7%, watched separately

What this code does

  • Rate is just requests divided by time. The error rate counts only 5xx answers, the ones the server is responsible for.
  • 404s and 401s are kept apart: they are normal in small numbers, and mixing them in would make the error rate look worse than the service really is.

Add two numbers for a Java app with a database: JVM heap used (is it close to the limit?) and connection pool use (are requests waiting for a database connection?).

A 404 for a missing product or a 401 for a missing token is the client's mistake and normal, so it stays out of the error rate. Watch such codes separately, because a sudden jump in 401s can still mean a broken frontend.

Why averages lie: percentiles

p95 is the response time that 95% of requests were as fast as or faster than, so 1 in 20 users waited longer. p50 is the typical request and p99 is 1 in 100. Percentiles show the slow tail that an average hides.

Nineteen fast answers and one 2-second answer still average to a number that looks fine. The program below compares the average with p95 for the same requests.

Example 2 · Average vs p95: why averages lie

PercentileDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class PercentileDemo {    // Nearest-rank percentile: the value below which p% of the sorted list falls    static int percentile(List<Integer> sorted, double p) {        int rank = (int) Math.ceil(p / 100.0 * sorted.size());        return sorted.get(Math.max(rank, 1) - 1);    }
    public static void main(String[] args) {        List<Integer> ms = new ArrayList<>(List.of(                42, 38, 51, 47, 40, 45, 39, 44, 52, 41,                48, 43, 46, 37, 50, 44, 41, 1450, 1920, 49));        double average = ms.stream().mapToInt(Integer::intValue).average().orElse(0);        Collections.sort(ms);
        System.out.printf("Average: %.0f ms%n", average);        System.out.println("p50:     " + percentile(ms, 50) + " ms");        System.out.println("p95:     " + percentile(ms, 95) + " ms");        System.out.println("p99:     " + percentile(ms, 99) + " ms");        System.out.println("Slower than 1 s: " + ms.stream().filter(t -> t > 1000).count() + " of " + ms.size());    }}
Output
Average: 208 ms
p50:     44 ms
p95:     1450 ms
p99:     1920 ms
Slower than 1 s: 2 of 20

What this code does

  • The average of 208 ms describes nobody: most requests took about 44 ms and two took well over a second. The median (p50) shows the typical user, p95 shows the slow tail.
  • percentile uses the nearest-rank method on the sorted list. Monitoring tools estimate percentiles from histograms instead, so their numbers differ slightly, but the meaning is the same.

Users remember the slow requests, and a page that makes several API calls hits the slow tail often. That is why dashboards and alerts use p95 or p99, not the average.

Predict the output

Average or p95?

Read the numbers and pick the answer.

Round 1 of 2

Ten requests, in ms. p95 by nearest rank is the 10th value when sorted.

response times (ms):
40 42 41 39 43 40 44 41 42 2000

Micrometer and http.server.requests

A tag is a label on a metric, such as method, uri, status or outcome, that splits one metric into separate series. Micrometer tags http.server.requests, and the uri tag holds the route pattern, not the real id.

Micrometer is the metrics library inside Spring Boot; Actuator brings it in. For every request it records a timer named http.server.requests. The command below reads it from Actuator.

Example 3 · Reading http.server.requests from Actuator

Runs in: the shoplite-api app with management.endpoints.web.exposure.include=health,info,metrics (temporarily, admins only)

Terminal
curl -s https://api.shoplite.example/actuator/metrics/http.server.requests -H "Authorization: Bearer $ADMIN"curl -s "https://api.shoplite.example/actuator/metrics/http.server.requests?tag=uri:/api/v1/me/orders&tag=outcome:SERVER_ERROR" \  -H "Authorization: Bearer $ADMIN"
Sample output
{"name":"http.server.requests","baseUnit":"seconds","measurements":[{"statistic":"COUNT","value":18342.0},{"statistic":"TOTAL_TIME","value":1022.61},{"statistic":"MAX","value":1.92}],"availableTags":[{"tag":"exception","values":["none","InvalidDataAccessResourceUsageException"]},{"tag":"method","values":["GET","POST","PATCH"]},{"tag":"error","values":["none","InvalidDataAccessResourceUsageException"]},{"tag":"uri","values":["/api/v1/products","/api/v1/products/{id}","/api/v1/me/orders","/api/v1/auth/login","/actuator/health"]},{"tag":"outcome","values":["SUCCESS","CLIENT_ERROR","SERVER_ERROR"]},{"tag":"status","values":["200","201","401","404","500"]}]}
{"name":"http.server.requests","baseUnit":"seconds","measurements":[{"statistic":"COUNT","value":37.0},{"statistic":"TOTAL_TIME","value":7.41},{"statistic":"MAX","value":0.36}],"availableTags":[{"tag":"exception","values":["InvalidDataAccessResourceUsageException"]},{"tag":"method","values":["POST"]},{"tag":"error","values":["InvalidDataAccessResourceUsageException"]},{"tag":"status","values":["500"]}]}

What this code does

  • The first call shows totals since start-up: 18,342 requests, about 56 ms on average (1022.61 s / 18,342), the slowest 1.92 s. The tags list every route pattern, status and outcome seen so far.
  • The second call narrows to one route and outcome: 37 server errors on placing orders, all with the same exception, which matches the log investigation from the previous lesson.
  • These counters only grow; a rate ("per minute") needs two readings over time, which is what Prometheus does for you.

The uri tag holds /api/v1/products/{id}, not /api/v1/products/42, so ten thousand products do not create ten thousand series. Narrow the answer with ?tag=uri:/api/v1/me/orders&tag=outcome:SERVER_ERROR.

Expose metrics only while you look, or only to admins: its tag values reveal your list of URLs.

Prometheus and a dashboard

A scrape is one fetch of a metrics endpoint by Prometheus, repeated every 15 to 60 seconds. Prometheus stores each value with its time, and Grafana draws dashboards from its queries.

Prometheus is a metrics database that fetches ShopLite's numbers on a schedule. The picture below shows who calls whom; the setting and its output follow.

Text
request ──► ShopLite (Micrometer) ──► /actuator/prometheus ◄── scrape every 15 s ── Prometheus ◄── queries ── Grafana dashboard                                                                                     │                                                                             alert rules ──► email / chat

Example 4 · Prometheus endpoint: dependency, settings and the output

Runs in: the shoplite-api Spring Boot project behind Caddy, scraped by Prometheus on the Compose network

YAML
# pom.xml: io.micrometer:micrometer-registry-prometheus (version managed by Spring Boot)# application-prod.ymlmanagement:  endpoints:    web:      exposure:        include: health,info,prometheus  metrics:    tags:      application: shoplite-api    distribution:      percentiles-histogram:        http.server.requests: true# Caddyfile: keep it private# api.shoplite.example {#     respond /actuator/prometheus 404#     reverse_proxy api:8080# }# $ docker compose exec prometheus wget -qO- http://api:8080/actuator/prometheus | grep -E '^(http_server_requests_seconds_count|hikaricp_connections_(active|max)|jvm_memory_used_bytes\{area="heap")'
Sample output
http_server_requests_seconds_count{application="shoplite-api",error="none",exception="none",method="GET",outcome="SUCCESS",status="200",uri="/api/v1/products"} 12873
http_server_requests_seconds_count{application="shoplite-api",error="none",exception="none",method="POST",outcome="SUCCESS",status="201",uri="/api/v1/me/orders"} 412
http_server_requests_seconds_count{application="shoplite-api",error="InvalidDataAccessResourceUsageException",exception="InvalidDataAccessResourceUsageException",method="POST",outcome="SERVER_ERROR",status="500",uri="/api/v1/me/orders"} 37
hikaricp_connections_active{application="shoplite-api",pool="ShopLitePool"} 2
hikaricp_connections_max{application="shoplite-api",pool="ShopLitePool"} 5
jvm_memory_used_bytes{application="shoplite-api",area="heap",id="G1 Eden Space"} 4.194304E7
jvm_memory_used_bytes{application="shoplite-api",area="heap",id="G1 Old Gen"} 9.8566144E7

What this code does

  • Each line is one series: a name, its tags in braces and the current value. Prometheus stores them over time, so queries such as rate(...[5m]) turn counters into per-second numbers.
  • The same endpoint carries the pool (hikaricp_connections_active of max 5) and JVM memory, so one dashboard can show all five numbers from the first section.
  • The histogram setting adds _bucket series, which let Grafana compute p95 for all instances together with histogram_quantile(0.95, ...).

Add the micrometer-registry-prometheus dependency, expose prometheus and, for percentiles across instances, turn on the histogram for http.server.requests.

Keep /actuator/prometheus off the public internet. On ShopLite's VM, Caddy answers 404 for it from outside, and Prometheus scrapes api:8080 on the private Compose network.

Simple alerts that are worth waking up for

An uptime monitor is an outside service that calls your public health URL every minute from another network and emails you when it fails. It catches DNS, certificate and VM problems that your own metrics cannot see.

An alert is a rule that sends a message when a metric crosses a limit for some time. The program below applies "error rate above 5% for 5 minutes" to a run of minutes.

Example 5 · Error rate above 5% for 5 minutes

ErrorRateAlertDemo.javaJava
public class ErrorRateAlertDemo {    public static void main(String[] args) {        int[] requests = {300, 310, 295, 320, 305, 298, 302, 310, 300, 290};        int[] errors5xx = {2, 31, 3, 18, 19, 22, 25, 28, 4, 1};        int needMinutes = 5;        int badStreak = 0;        boolean firing = false;
        for (int minute = 0; minute < requests.length; minute++) {            double rate = 100.0 * errors5xx[minute] / requests[minute];            badStreak = rate > 5.0 ? badStreak + 1 : 0;            String state = "";            if (!firing && badStreak >= needMinutes) {                firing = true;                state = "  <- ALERT: error rate above 5% for 5 minutes";            } else if (firing && badStreak == 0) {                firing = false;                state = "  <- resolved";            }            System.out.printf("min %d: %4.1f%%%s%n", minute + 1, rate, state);        }    }}
Output
min 1:  0.7%
min 2: 10.0%
min 3:  1.0%
min 4:  5.6%
min 5:  6.2%
min 6:  7.4%
min 7:  8.3%
min 8:  9.0%  <- ALERT: error rate above 5% for 5 minutes
min 9:  1.3%  <- resolved
min 10:  0.3%

What this code does

  • Minute 2 has a 10% spike but no alert: one bad minute is noise. From minute 4 the rate stays above 5%, and on the fifth bad minute in a row the alert fires.
  • This is what for: 5m does in a Prometheus alert rule. When the rate drops again the alert resolves, and the streak starts from zero.

Start with three alerts: error rate above 5% for 5 minutes, the health check failing, and an uptime monitor. Every alert should need a human action. An alert that fires daily and is ignored trains everyone to ignore the important one.

Find the bug

Fix the alert rule

Click the line that makes the alert noisy or blind.

Which line fires on a single bad request?

Round 1 of 3

Next step

Check your understanding

12 quick questions