Users complain in the group chat: "Why does opening a note sometimes take so long?" You check, and notes-api's average response time is 115 ms. Sounds fast. The problem is that not a single request actually took 115 ms. In this lesson you'll see why that average lies.
For that you need numbers that are measured all the time, and the right way to read them. A metric is a number measured again and again and stored with its time. The result is a sequence of points that forms a graph, called a time series. Monitoring means watching those numbers continuously. Picture a car dashboard. The odometer can only go up: the total kilometres since the car was built. The speedometer goes up and down: the speed right now. Then there is a trip summary that groups trips by how long they took: how many under 15 minutes, how many under 30. These three match the three kinds of metric: the odometer is a counter, the speedometer is a gauge, and the trip summary is a histogram.
A log tells the story of one event, and error tracking groups errors. Metrics answer "how many" and "how fast" for every request at once. The cost is small: one number per metric, not one line per request.
Three kinds of metric
| Kind | Behaviour | Example in notes-api |
|---|---|---|
| counter | only goes up, back to 0 when the app restarts | http_requests_total: requests served |
| gauge | goes up and down, what matters is the value now | http_requests_in_flight: requests being handled, memory in use |
| histogram | counts how many values fall in each bucket (a range of values) | http_request_duration_seconds: request durations |
A counter's value on its own is useless: 18,342 requests, but since when? What you read is its speed: the difference between two measurements divided by the time between them. A histogram keeps a count per upper limit, called le (less or equal): how many requests finished in at most 0.05 seconds, in at most 0.1 seconds, and so on. Percentiles are estimated from those counts.
Percentiles: p50, p95, p99
pX (the Xth percentile) is the duration that X% of requests do not exceed. p95 = 75 ms means 95 of 100 requests finish in 75 ms or less. p50 is also called the median: the middle point. This function uses the nearest rank method: sort the values, then take the value at the position X% from the start.
function calculatePercentile(values, percentile) {
const sorted = [...values].sort((a, b) => a - b); // a copy, ascending
const index = Math.ceil((percentile * sorted.length) / 100) - 1;
return sorted[index];
}
| Call | Order | Position | Result |
|---|---|---|---|
calculatePercentile([10, 20, 30, 40, 50], 50) |
10 20 30 40 50 | ceil(2.5) - 1 = 2 | 30 |
calculatePercentile([10, 20, 30, 40, 50], 95) |
10 20 30 40 50 | ceil(4.75) - 1 = 4 | 50 |
calculatePercentile([5, 3, 1, 4, 2], 20) |
1 2 3 4 5 | ceil(1) - 1 = 0 | 1 |
[...values]makes a copy, sosortdoes not reorder the caller's array.(a, b) => a - bis required. Without a comparator (a function that compares two values),sortorders numbers as text:[3, 25, 100].sort()becomes[100, 25, 3].Math.ceilrounds the human position (1st to nth) up, then- 1turns it into an array index, which starts at 0.
Prometheus (covered below) calculates percentiles from histogram buckets with histogram_quantile. Because Prometheus only knows the count per bucket, its result is an estimate, but the meaning is the same.
Why the average lies
These are the Lab's 100 GET /notes requests, before and after 3 of them hit a 2.4-second cold query (a query whose data is not in the cache yet):
| average | p50 | p95 | p99 | |
|---|---|---|---|---|
| no slow requests | 45.0 ms | 43 ms | 68 ms | 80 ms |
| 3 requests at 2,400 ms | 115.55 ms | 43 ms | 75 ms | 2,400 ms |
With 3 slow requests, the average is 115.55 ms, while the p50 stays at 43 ms. Yet not one request took 115 ms: 97 finish under 105 ms, and 3 take 2,400 ms. The average blends those two groups into a number that describes no request at all. The p50 does not move, because the median only looks at the middle value, not at the tail (the slowest requests at the end of the order). The p99 catches that tail: more than 1 in 100 requests takes 2.4 seconds. That is why latency (the time until a request gets its answer) is watched at p95 and p99, alongside the p50.
RED, USE and the four golden signals
So you do not drown in hundreds of metrics, there are three checklists:
- RED, for a service like notes-api: Rate (requests per second), Errors (percent of requests that fail), Duration (p95 and p99).
- USE, for a resource like the CPU, memory and disk of
web-1, or the database connection pool: Utilisation (how busy), Saturation (how much is queueing), Errors. - The four golden signals from Google's Site Reliability Engineering book, a blend of both: latency, traffic, errors, saturation.
Monitoring answers questions you prepared beforehand, for example "is the error rate above 5%?", through dashboards (screens of graphs) and alerts. Observability is the ability to answer new questions you had not thought of, for example "why are only the requests from users in Manchester slow?". You do it by combining metrics, logs and traces (the path of one request through several services). Traces are covered in the OpenTelemetry Fundamentals and Distributed Tracing lessons.
Prometheus: scraping /metrics
notes-api shows all its numbers on one page, /metrics, with the prom-client library:
const client = require("prom-client");
client.collectDefaultMetrics(); // memory, CPU, the Node event loop
const requests = new client.Counter({ name: "http_requests_total", help: "Total HTTP requests", labelNames: ["method", "route", "status_code"] });
const inFlight = new client.Gauge({ name: "http_requests_in_flight", help: "Requests being handled right now" });
const duration = new client.Histogram({ name: "http_request_duration_seconds", help: "Request duration in seconds", labelNames: ["route"], buckets: [0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5] });
app.use((req, res, next) => {
inFlight.inc();
const end = duration.startTimer();
res.on("finish", () => {
const route = req.route ? req.route.path : req.path;
requests.inc({ method: req.method, route, status_code: res.statusCode });
end({ route });
inFlight.dec();
});
next();
});
app.get("/metrics", async (req, res) => {
res.set("Content-Type", client.register.contentType);
res.end(await client.register.metrics());
});
The app.use middleware records every request: the gauge goes up when a request comes in and down when it finishes, the histogram records the duration, and the counter goes up by one. Labels (labelNames) are extra details such as the method, the route and the status code. Every combination of their values becomes its own time series.
Prometheus is a program that collects and stores metrics. It comes and fetches the /metrics page every 15 seconds. This fetch is called a scrape. It is a pull model: the app sends nothing, Prometheus pulls the data. Prometheus runs as another service in the same Compose project, and its config is written in prometheus.yml:
scrape_configs:
- job_name: notes-api
scrape_interval: 15s
static_configs:
- targets: ["app:3000"] # default path: /metrics
This is part of what /metrics returns, before any request is slow:
# TYPE http_requests_total counter
http_requests_total{method="GET",route="/notes",status_code="200"} 18342
# TYPE http_requests_in_flight gauge
http_requests_in_flight 3
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.05",route="/notes"} 72
http_request_duration_seconds_bucket{le="0.1",route="/notes"} 99
http_request_duration_seconds_bucket{le="+Inf",route="/notes"} 100
Each line holds the metric's name, the labels inside { }, then the value. Buckets add up: 72 requests in at most 0.05 seconds, 99 in at most 0.1 seconds (the 72 included), and +Inf (no upper limit) all 100.
15 seconds later the counter is 18,524, so its speed is (18,524 - 18,342) / 15 = 12.1 requests per second. In PromQL (Prometheus's query language), the same calculation is written rate(http_requests_total[1m]): the speed per second from the points of the last minute. Grafana then draws the numbers from Prometheus as dashboards. Prometheus and Grafana are the most common open source pair for this. Setting them up is in the Grafana & Prometheus Setup lesson.
⚠️ Misread numbers and runaway labels
- Watching latency with an average. Three slow requests push the average up about 2.6 times without showing which requests are slow. Use p50, p95, p99.
- Labels with unbounded values.
route: "/notes/812"or auserIdlabel makes one time series per note or per user, until Prometheus has no memory left. Use the route pattern"/notes/:id", which is the same for every note. - Reading a raw counter value. What matters is its speed, through
rate(). One more thing: do not let nginx open/metricsto the internet. - In the exercise:
sort()without a comparator, or forgetting- 1. Without(a, b) => a - b, numbers sort as text. Without- 1, the p95 of five numbers points at index 5, which givesundefined.
TL;DR: A metric is a number measured at intervals and stored with its time (a time series). A counter only goes up (read its speed with rate()), a gauge goes up and down (what matters is its value now), and a histogram counts values per bucket (a range of values) to estimate percentiles. pX (the Xth percentile) is the duration X% of requests do not exceed. To calculate it (nearest rank): sort a copy of the values with (a, b) => a - b, then take index Math.ceil(percentile * n / 100) - 1. The average lies about latency (the time until a request gets its answer): 3 of 100 requests taking 2.4 seconds make the average 115.55 ms while the p50 stays at 43 ms, and only the p99 (2,400 ms) catches the tail (the slowest requests). RED (rate, errors, duration) for services, USE (utilisation, saturation, errors) for resources, and the four golden signals: latency, traffic, errors, saturation. Monitoring checks known problems, observability helps you understand new ones. Prometheus (which collects metrics) scrapes (pulls) the app's /metrics page every 15 seconds, Grafana draws the numbers as dashboards.
⚡ Three kinds of metric
Write:
http_requests_total counter
http_requests_in_flight gauge
http_request_duration_seconds histogram
Meaning: A metric is a number measured at intervals and stored with its time. A counter only goes up, like http_requests_total (requests served), and what you read is its speed. A gauge goes up and down, like http_requests_in_flight (requests being handled), and what matters is its value now. A histogram counts how many request durations fall in each bucket (a range of values), to estimate percentiles (next step).
⚡ Percentiles: p50, p95, p99
Write:
function calculatePercentile(values, percentile) {
const sorted = [...values].sort((a, b) => a - b);
const index = Math.ceil((percentile * sorted.length) / 100) - 1;
return sorted[index];
}
Meaning: pX (the Xth percentile) is the duration that X% of requests do not exceed: p95 = 75 ms means 95 of 100 requests finish in 75 ms or less. This function sorts a copy of the values, then takes the value at the position X% from the start, minus 1 because array indexes start at 0. Without (a, b) => a - b, sort orders numbers as text.
⚡ The average lies
Guess first: 97 requests under 105 ms, 3 at 2,400 ms. The average is 115.55 ms. How many requests actually took 115 ms?
Not one. The average blends two groups into a number that describes no request at all. The p50 stays at 43 ms, and only the p99 (2,400 ms) catches the tail, the 3 slowest requests.
Meaning: That is why latency (the time until a request gets its answer) is watched at p95 and p99, alongside the p50. For a service, check RED: rate (requests per second), errors (percent of requests that fail) and duration (the p95 and p99). Google's four golden signals: latency, traffic, errors, saturation (how much is queueing).
⚡ Prometheus pulls /metrics
Write:
scrape_configs:
- job_name: notes-api
scrape_interval: 15s
static_configs:
- targets: ["app:3000"]
Meaning: Prometheus is a program that collects and stores metrics. The app sends nothing: Prometheus comes and fetches (scrapes) the /metrics page at app:3000 (the notes-api container, port 3000) every 15 seconds. Grafana then draws the numbers as dashboards.