Sub topic 10
Using rate and aggregation for CPU, memory, and disk
This chapter assumes you can already select series with PromQL label matchers, know the four metric types, and have node_exporter targets showing up == 1 in Prometheus. Here you turn raw counters and gauges into the CPU, memory, and disk numbers you put on dashboards and in alerts.
Why raw values are not enough
Prometheus stores samples exactly as the exporter reports them. Two of the node_exporter metrics you care about most behave in ways that make the raw value hard to read.
node_cpu_seconds_totalis a counter. It counts the seconds each CPU core has spent in each mode since boot. It only ever goes up, so its current value says little about current load.node_memory_MemAvailable_bytesandnode_filesystem_avail_bytesare gauges. They already show a current level, but they are in bytes and come per machine or per mount point.
The usual fix is a two-step pattern. For counters, convert the running total into a per-second rate. For everything, combine many series into the few you want to see, using aggregation.
Instant vectors, range vectors, and rate
PromQL has two kinds of values you need here.
- An instant vector has one sample per series at a single moment. A plain selector such as
node_memory_MemTotal_bytesreturns one. - A range vector has a window of samples per series. You write the window in square brackets:
node_cpu_seconds_total[5m]returns every sample from the last five minutes.
Functions like rate() take a range vector and return an instant vector. rate(x[5m]) is the average per-second increase of a counter over the last five minutes. It also handles counter resets. When a server reboots, the counter drops to zero, and rate() treats the drop as a restart instead of a huge negative change.
rate(node_cpu_seconds_total{mode="idle"}[5m])For a single core, this returns a number between 0 and 1. A value of 0.9 means that core spent 0.9 seconds idle for every second of wall-clock time, so it was 90% idle.
Choosing the range window
The window must contain at least two samples, and in practice you want four or more. With a 15 second scrape interval, [1m] holds about four samples and is the practical minimum. A window of [5m] smooths short spikes and tolerates a missed scrape. A shorter window reacts faster but is noisier.
Pick a window of at least four times the scrape interval. Use the same window in related queries so graphs and alerts agree.
rate, irate, and increase
| Function | Returns | Typical use |
|---|---|---|
| `rate(x[5m])` | Average per-second increase across the window | Dashboards and alerts. The default choice. |
| `irate(x[5m])` | Per-second increase between the last two samples | Zoomed-in graphs of fast-moving counters. Too jumpy for alerts. |
| `increase(x[1h])` | Total increase across the window | Answering "how many in the last hour". |
Use rate() on counters only. Applying it to a gauge produces meaningless output, because a gauge can go down and rate() will interpret every decrease as a counter reset.
Aggregation operators
Aggregation operators collapse many series into fewer. The common ones are sum, avg, min, max, count, and topk. By default an aggregation merges all series into one. Two clauses control which labels survive.
by (label, ...)keeps only the listed labels and merges everything else.without (label, ...)drops the listed labels and keeps the rest.
Take a server with 4 cores. node_cpu_seconds_total has 4 cores times several modes, so the idle selector alone returns 4 series per server, one for each cpu label value. To get one number per server, average over the cores and keep only instance:
avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))The result is a fraction between 0 and 1. Subtract it from 1 and multiply by 100 to get the busy percentage.
100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))Order matters. Apply rate() first, to each individual series, and aggregate afterwards. Writing rate(sum(...)[5m]) is invalid in PromQL, and summing counters before taking a rate would also hide resets that happen on individual series.
CPU utilisation
The query above is the standard CPU measure. Notice what it does.
- The selector
{mode="idle"}picks only the idle counters, one per core per server. rate(...[5m])turns each into an idle fraction.avg by (instance)produces one idle fraction per server.1 - ...converts idle into busy, and100 *turns it into a percentage.
If you want to see where time goes instead, drop the mode filter and aggregate by mode:
sum by (instance, mode) (rate(node_cpu_seconds_total[5m]))For a 4-core server, the values across all modes add up to about 4, because each core contributes up to one second of CPU time per second.
Memory usage
Memory metrics are gauges, so no rate() is needed. The right number to use is MemAvailable, which is the kernel's estimate of how much memory can be given to applications without swapping. It counts reclaimable page cache as available. Using MemFree instead would make a healthy server look full, because Linux deliberately fills spare memory with cache.
100 * (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)Both sides of the division carry the same instance and job labels, so Prometheus matches them one to one automatically. The result has one series per server and no explicit aggregation is needed.
Disk usage
Filesystem metrics are gauges with device, fstype, and mountpoint labels. A server often reports virtual filesystems such as tmpfs and overlay that are not real disks, so you exclude them with a negative regular-expression matcher:
node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"}
/ node_filesystem_size_bytes{fstype!~"tmpfs|overlay"}This returns the fraction of space still available on each real mount. To show used percentage instead, subtract from 1 and multiply by 100.
To find the fullest disk on each server, add an aggregation:
max by (instance) (
1 - node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"}
/ node_filesystem_size_bytes{fstype!~"tmpfs|overlay"}
)To see the three most full filesystems across the whole fleet, use topk:
topk(3, 1 - node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"}
/ node_filesystem_size_bytes{fstype!~"tmpfs|overlay"})Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Query returns "no data" | Window shorter than two scrapes, or the metric name or label is wrong | Widen the range and check the name in the Prometheus expression browser |
| CPU graph shows values above 100 | Percent multiplied twice, or `avg` replaced by `sum` | Use `avg by (instance)` before multiplying by 100 |
| Memory looks almost full on a healthy server | `MemFree` used instead of `MemAvailable` | Switch to `MemAvailable` |
| Each disk appears several times | Same device mounted in several places, or container overlays | Exclude virtual types with `fstype!~` or filter by `mountpoint` |
| "many-to-many matching not allowed" | Division between series with different label sets | Use `on (instance, mountpoint)` or aggregate both sides identically |
| Rate looks flat at zero for a busy server | `rate()` applied to the wrong mode, or a gauge used by mistake | Check the metric type and the `mode` label |
Putting the pieces together
The pattern from this chapter reduces to three habits.
- Counters get
rate()over a window of at least four scrapes. - Aggregation comes after
rate(), withbyorwithoutchosen to keep the labels you want to see. - Gauges are used directly, often as a ratio of two gauges, and filtered so virtual filesystems do not distort the result.
These queries are the building blocks for the next chapters. The same expressions become Grafana panels, recording rules, and alert conditions.
Exercise
A server has 8 cores. You run sum by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) and get 6.0. Is the server busy? Rewrite the query to return CPU busy percent per server.
Show answer
The sum is across 8 cores, so 6.0 means the cores were idle 6 core-seconds per second out of a possible 8. The server is 25% busy. The sum is the wrong aggregation for a percentage. Use avg instead: 100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))). This gives 100 * (1 - 0.75) = 25.
Exercise
Write a query that returns, for each server, the percentage of the fullest real filesystem in use, ignoring tmpfs and overlay. Why use node_filesystem_avail_bytes instead of node_filesystem_free_bytes?
Show answer
100 * max by (instance) (1 - node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"} / node_filesystem_size_bytes{fstype!~"tmpfs|overlay"}). The avail metric excludes blocks reserved for root, so it reflects the space that normal applications can actually use. The free metric would understate how full the disk is for them.
Exercise
Why is rate(node_memory_MemAvailable_bytes[5m]) the wrong way to track memory pressure?
Show answer
MemAvailable is a gauge, not a counter. A gauge can rise and fall, and rate() treats every decrease as a counter reset, so the output is not meaningful. Use the gauge directly, for example as a ratio against MemTotal.