# Prometheus and PromQL

How Prometheus pulls metrics from targets, how node_exporter exposes a server, and how to answer real questions with PromQL: rates, averages, percentiles and predictions.

Course: [Monitoring](https://devops.rajeev.pro/courses/monitoring), lesson 2. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/monitoring/02-prometheus-and-promql

## What you will learn

- Explain the pull model and why Prometheus scrapes targets instead of waiting for pushes
- Run Prometheus and node_exporter, and read the Targets page to prove both are up
- Read a /metrics page and name each metric's type from its TYPE line
- Write PromQL with selectors, rate(), sum by, histogram_quantile and predict_linear
- Use a recording rule for a query you run on every dashboard refresh

## Why Prometheus exists

Prometheus is the tool most of this course is built on, so it's worth seeing the problem it was
made to solve, one step at a time.

### Before: checks that only say OK or CRITICAL

In 2012 a typical team with forty Linux servers ran Nagios. Every few minutes a script logged in to
each box, ran `check_disk` or `check_load`, and reported OK, WARNING or CRITICAL. A red square said
the disk was 91% full. It couldn't say since when, how fast it was filling, or whether the other
thirty-nine servers were heading the same way.

> **Figure.** Animated. Six servers in a status grid all show OK, then db-1 turns red: CRITICAL, disk 91%. Three questions appear that a status check cannot answer: since when, how fast is it filling, and are the others next.
>
> A check returns a status, not a history.

### The problem: targets come and go

Then the team moved to containers. Containers start and stop every few minutes, each with a new
name. Every new one had to be added to the check list by hand, and people forgot. The container that
crashed was often the one nobody was watching.

> **Figure.** Animated. Containers appear and disappear: api-7f3c, api-9b21, api-2d8e, worker-51aa. A hand-edited check list still names web-1, web-2 and db-1, last edited 3 months ago. The new container api-2d8e is marked not monitored.
>
> A list typed by hand is out of date before you save it.

### The fix: every target serves its numbers

Prometheus, started at SoundCloud in 2012 and now a CNCF project, flips the model. Each app or
server serves a plain-text page of its current numbers at `/metrics`. Prometheus visits every
target it knows about on a schedule and collects that page. A target that doesn't answer is
recorded as `up = 0`, so a dead server is a number you can alert on, not a silence you have to
notice.

> **Figure.** Animated. Three targets, node_exporter on 9100, the app on 8080 and Prometheus on 9090, each serve /metrics. Prometheus sends GET /metrics to each one every 15 seconds and the numbers come back. A dead target becomes up = 0.
>
> Prometheus pulls from every target it expects.

### How it works: samples become history

Every 15 seconds Prometheus stores each number with its timestamp and keeps them, 15 days by
default. With history you ask better questions in its query language, PromQL: not "is the disk
full?" but "at this rate, will it be full within 4 hours?".

> **Figure.** Animated. Disk-free samples appear one by one on a chart, falling steadily. A PromQL query, predict_linear over the last hour projected 4 hours ahead and compared with 0, appears with its answer: true, the disk will be full within 4 hours.
>
> Kept samples turn a status into a prediction.

In this lesson you'll run Prometheus and node_exporter, read what they collect, and write the
PromQL you'll use in every dashboard and alert after this.

> **Video.** [How Prometheus Monitoring works | Prometheus Architecture explained](https://www.youtube.com/watch?v=h4Sl21AKiDg) (TechWorld with Nana)

## How Prometheus is built

Prometheus is **one server process** that does four jobs. Knowing which part does what tells
you where to look when something breaks.

> **Figure.** Targets on the left expose a /metrics page: node_exporter on port 9100, your app on 8080 and Prometheus itself on 9090. In the middle, the Prometheus server reads targets from config or service discovery, scrapes each one every 15 seconds, records up as 1 or 0, writes samples to its time series database on local disk for about 15 days, runs rules every 15 seconds and answers PromQL queries. On the right, Grafana and people query it, and firing alerts go to Alertmanager on port 9093.
>
> Targets only serve a page of numbers. Scheduling, storage, rules and queries all live inside Prometheus.

1. **Service discovery** works out _what_ to scrape: a fixed list in the config, or a live list
   from Kubernetes, EC2, Consul or a file.
2. **The scraper** sends `GET /metrics` to every target on the `scrape_interval`.
3. **The TSDB** (time series database) writes each sample to local disk. By default it keeps
   **15 days** (`--storage.tsdb.retention.time`). Long-term storage across months is a job for
   add-ons like Thanos or Mimir.
4. **The rule engine** evaluates recording rules and alert rules every `evaluation_interval`, and
   sends firing alerts to **Alertmanager**, a separate program you'll meet in the Alerting stage.

### Why pull and not push

In a push system every server sends its numbers to a central collector. If a server dies, it
simply stops sending, and silence is easy to miss. Prometheus pulls, so it knows the full list of
targets it **expects**. When a scrape fails, it writes `up = 0` for that target. A dead server
becomes a number you can alert on.

Pull has one weak spot: a batch job that runs for 20 seconds may finish between two scrapes. For
those, the job pushes its final numbers to the **Pushgateway** (port 9091) and Prometheus scrapes
the gateway.

## Run Prometheus and node_exporter

Everything in this lesson ran on a lab machine with Prometheus 3.15.1, node_exporter 1.12.1 and
Alertmanager 0.34.2, all as Docker containers on one network. Start with a config file:

```yaml
# prometheus.yml
global:
  scrape_interval: 15s # how often to scrape each target (default is 1m)
  evaluation_interval: 15s # how often to run rules

rule_files:
  - /etc/prometheus/rules.yml

scrape_configs:
  - job_name: prometheus # Prometheus scrapes its own /metrics too
    static_configs:
      - targets: ['localhost:9090']

  - job_name: node
    static_configs:
      - targets: ['node-exporter:9100']
        labels:
          env: lab # extra label added to every series from this target
```

Then start both containers on a shared network, so Prometheus can reach `node-exporter:9100` by
name:

```sh
$ docker network create mon
$ docker run -d --name node-exporter --network mon -p 9100:9100 \
    --pid host -v /:/host:ro prom/node-exporter --path.rootfs=/host
$ docker run -d --name prometheus --network mon -p 9090:9090 \
    -v $PWD/prometheus.yml:/etc/prometheus/prometheus.yml:ro \
    -v $PWD/rules.yml:/etc/prometheus/rules.yml:ro prom/prometheus
```

`--pid host` and the read-only mount of `/` let node_exporter see the host's processes and disks
instead of the container's own. The official guide adds `,rslave` to that mount; on Docker inside
WSL that fails with "not a shared or slave mount", so it's left out here. On a real Linux server,
node_exporter usually runs as a plain systemd service instead of a container.

Before you restart Prometheus after an edit, check the files. `promtool` ships inside the image:

```sh
$ docker exec prometheus promtool check config /etc/prometheus/prometheus.yml
Checking /etc/prometheus/prometheus.yml
  SUCCESS: 1 rule files found
 SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax

Checking /etc/prometheus/rules.yml
  SUCCESS: 4 rules found
```

## Scraping and targets

A **target** is one endpoint Prometheus scrapes, like `node-exporter:9100`. A **job** is a group of
targets that do the same thing, like all your node_exporters. Prometheus adds two labels to every
series it scrapes: `job` (from `job_name`) and `instance` (the target's address).

Open **Status → Target health** (`http://localhost:9090/targets`). It's the first page to check
when a graph is empty.

> **Figure.** Prometheus Target health page with three scrape pools, alertmanager, node and prometheus, each 1 of 1 up. The node target http://node-exporter:9100/metrics has labels env lab, instance node-exporter:9100 and job node, was last scraped 14.999 seconds ago, took 101 milliseconds, and its state is UP.
>
> Every target, its labels, when it was last scraped and how long it took. A DOWN target shows the scrape error here.

For each scrape, Prometheus also writes a few series about the scrape itself:

| Series                    | Tells you                              |
| ------------------------- | -------------------------------------- |
| `up`                      | 1 if the scrape worked, 0 if it failed |
| `scrape_duration_seconds` | How long the scrape took               |
| `scrape_samples_scraped`  | How many samples the target returned   |

```sh
$ docker exec prometheus promtool query instant http://localhost:9090 'up'
up{instance="alertmanager:9093", job="alertmanager"} => 1 @[1793689704.922]
up{instance="localhost:9090", job="prometheus"} => 1 @[1793689704.922]
up{env="lab", instance="node-exporter:9100", job="node"} => 1 @[1793689704.922]
```

Each line is one **series**: a metric name plus a unique set of labels. `=> 1` is its value, and
the number after `@` is the evaluation time as a Unix timestamp.

### Static lists or service discovery

`static_configs` is fine for a lab or a handful of fixed servers. Anywhere servers come and go,
use **service discovery** so Prometheus finds targets itself:

| Config block            | Finds targets from                                  |
| ----------------------- | --------------------------------------------------- |
| `kubernetes_sd_configs` | Pods, services and nodes in a cluster               |
| `ec2_sd_configs`        | Running EC2 instances, filtered by tags             |
| `file_sd_configs`       | A JSON or YAML file that another tool keeps updated |
| `consul_sd_configs`     | Services registered in Consul                       |

Discovery returns a lot of metadata (EC2 tags, pod labels). `relabel_configs` decide which of it
becomes labels, and which targets to drop. A common mistake is keeping too much: every unique
label value creates a new series, and millions of series is how a Prometheus runs out of memory.

## Exporters

Your own app can expose `/metrics` with a Prometheus client library (Go, Python, Java, Node.js
and more). But Linux, MySQL or Nginx don't speak Prometheus. An **exporter** is a small program
that sits next to them, reads their stats in their own format and serves those stats as a
`/metrics` page.

**node_exporter** is the exporter for a Linux machine. It reads `/proc` and `/sys` and turns them
into about 700 series: CPU time, memory, disks, filesystems, network and load.

```sh
$ curl -s localhost:9100/metrics | grep -vc '^#'
726
$ curl -s localhost:9100/metrics | grep -E 'node_cpu_seconds_total\{cpu="0"|MemAvailable|filesystem_avail_bytes.*mountpoint="/"'
# HELP node_cpu_seconds_total Seconds the CPUs spent in each mode.
# TYPE node_cpu_seconds_total counter
node_cpu_seconds_total{cpu="0",mode="idle"} 6849.66
node_cpu_seconds_total{cpu="0",mode="iowait"} 32.06
node_cpu_seconds_total{cpu="0",mode="irq"} 0
node_cpu_seconds_total{cpu="0",mode="nice"} 0
node_cpu_seconds_total{cpu="0",mode="softirq"} 357.32
node_cpu_seconds_total{cpu="0",mode="steal"} 0
node_cpu_seconds_total{cpu="0",mode="system"} 431.5
node_cpu_seconds_total{cpu="0",mode="user"} 408.4
# HELP node_filesystem_avail_bytes Filesystem space available to non-root users in bytes.
# TYPE node_filesystem_avail_bytes gauge
node_filesystem_avail_bytes{device="/dev/sdd",device_error="",fstype="ext4",mountpoint="/"} 9.74034223104e+11
# HELP node_memory_MemAvailable_bytes Memory information field MemAvailable_bytes.
# TYPE node_memory_MemAvailable_bytes gauge
node_memory_MemAvailable_bytes 2.611048448e+09
```

Read it line by line:

- `# HELP` is a human description. `# TYPE` says how to treat the numbers.
- `node_cpu_seconds_total` is a **counter**: total seconds CPU 0 has spent in each mode since boot.
  It only ever goes up, so the raw value is useless on a graph. You'll always wrap it in `rate()`.
- `node_filesystem_avail_bytes` and `node_memory_MemAvailable_bytes` are **gauges**: current values
  that go up and down. `9.74034223104e+11` is about 974 GB free on `/`.
- Names end in their unit (`_seconds`, `_bytes`) and counters end in `_total`. That's the official
  naming convention, and it makes queries readable.

Other exporters you'll meet: `mysqld_exporter`, `postgres_exporter`, `redis_exporter`, the
`blackbox_exporter` (probes URLs from outside, like a user would) and `kube-state-metrics` for
Kubernetes.

> **Don't expose exporters to the internet.** node_exporter has no login. Anyone who can reach port 9100 can read your hostnames, disks and network interfaces. Keep exporter ports on a private network or behind a firewall rule that only allows Prometheus.

## PromQL: asking questions

**PromQL** is how you read data out of Prometheus: in the web UI, in Grafana panels and in alert
rules. Every query returns one of two shapes:

- an **instant vector**: one value per series, at one moment (`up`),
- a **range vector**: a window of values per series (`up[5m]`), which you pass to a function.

You'll build up from simple to useful.

### Select series with labels

```promql
node_filesystem_avail_bytes{mountpoint="/", fstype!="tmpfs"}
```

Label matchers are `=` (equals), `!=` (not equal), `=~` (regex match) and `!~` (regex doesn't
match). `{job=~"node|api"}` picks both jobs.

### Turn counters into rates

```sh
$ promtool query instant http://localhost:9090 'rate(node_network_receive_bytes_total{device="eth0"}[5m])'
{device="eth0", env="lab", instance="node-exporter:9100", job="node"} => 48.08771929824561
```

`rate(x[5m])` takes the last 5 minutes of a counter and returns the average **per-second**
increase: about 48 bytes per second received on eth0. It also handles restarts, when a counter
drops back to 0. `increase(x[1h])` is the same idea as a total ("requests in the last hour").
Use a window at least four times your scrape interval (so `[1m]` or more at 15 s), or the rate
has too few samples and turns jumpy.

### Aggregate with sum, avg and by

Here is CPU use as a percentage, the query behind most "CPU" panels:

```sh
$ promtool query instant http://localhost:9090 '100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))'
{instance="node-exporter:9100"} => 9.919298245614039
```

Inside out: `rate(...{mode="idle"}[5m])` is the share of each second each CPU spent idle. `avg by
(instance)` averages all CPUs of one machine and keeps only the `instance` label. `1 - idle` is
busy, and `100 *` makes it a percentage: this machine was about 10% busy. `sum`, `min`, `max`,
`count` and `topk(3, ...)` work the same way. `by (label)` keeps those labels, `without (label)`
drops them.

> **Figure.** The Prometheus query page with the expression 100 times 1 minus avg by instance of rate node_cpu_seconds_total mode idle over 5 minutes, shown as a graph over 30 minutes. The line starts near 92 percent while the lab started, drops below 30 and then moves between about 25 and 45 percent.
>
> The same CPU query on the Graph tab. The spike on the left is the lab's containers starting up.

### Percentiles from histograms

Averages hide slow requests (lesson 1). Latency is usually a **histogram**: a set of
`_bucket` counters, one per upper bound `le` ("less than or equal"). Prometheus serves its own HTTP
latency this way:

```sh
$ promtool query instant http://localhost:9090 'histogram_quantile(0.95, sum by (le) (rate(prometheus_http_request_duration_seconds_bucket[5m])))'
{} => 0.09499999999999999
```

95% of requests to this Prometheus finished within about 0.095 seconds. The pattern is always the
same: `rate` of the buckets, `sum by (le)` (keep `le`, or the function has nothing to work with),
then `histogram_quantile`. The result is an estimate: it's only as precise as the bucket bounds.

### Match two sides of a division

This query looked right, and returned nothing:

```sh
$ promtool query instant http://localhost:9090 'node_load1 / count by (instance) (node_cpu_seconds_total{mode="idle"})'

$ promtool query instant http://localhost:9090 'node_load1 / on (instance) count by (instance) (node_cpu_seconds_total{mode="idle"})'
{instance="node-exporter:9100"} => 0.625
```

When you divide two vectors, PromQL pairs up series whose labels are **exactly** the same. The left
side has `instance`, `job` and `env`. The right side, after `count by (instance)`, has only
`instance`. No pair matches, so the answer is empty. `on (instance)` says "match on this label
only". The result, load per CPU core, is 0.625: below 1, so work isn't queueing. An empty result
from a division is almost always this.

### Predict the future

```sh
$ promtool query instant http://localhost:9090 'predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[1h], 4*3600) / 1e9'
{device="/dev/sdd", env="lab", fstype="ext4", instance="node-exporter:9100", job="node", mountpoint="/"} => 963.9708872502385
```

`predict_linear` fits a straight line through the last hour and projects it 4 hours ahead: about
964 GB free, so nothing to worry about. When that number goes below 0, the disk fills within 4
hours. That's a far better alert than "disk above 90%", and you'll write it in the Alerting
lesson.

## Recording rules

Some queries are expensive and run constantly: a dashboard with ten panels, refreshed every 30
seconds by twenty people. A **recording rule** runs the query once per evaluation interval and
saves the result as a new series:

```yaml
# rules.yml
groups:
  - name: node
    rules:
      - record: instance:node_cpu_utilisation:rate5m
        expr: 1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
```

```sh
$ promtool query instant http://localhost:9090 'instance:node_cpu_utilisation:rate5m'
instance:node_cpu_utilisation:rate5m{instance="node-exporter:9100"} => 0.09919298245614039
```

The name follows the convention `level:metric:operations`: aggregated to `instance`, from
`node_cpu_utilisation`, using `rate5m`. Dashboards and alerts now read one small series instead of
recomputing the average over every CPU.

> **Video.** [Introduction to the Prometheus Monitoring System | Key Concepts and Features](https://www.youtube.com/watch?v=STVMGrYIlfg) (PromLabs)

> **In production.** Run two identical Prometheus servers scraping the same targets, so losing one loses nothing. Keep label values low-cardinality (job, instance, env, status code: yes; user ID, email, full URL: never). And watch Prometheus itself: `prometheus_tsdb_head_series` is how many series it holds in memory.

## Mission: Answer four questions about your machine with PromQL

With Prometheus and node_exporter running, write one PromQL query for each question, run it, and save the query and its answer: Is every target up? How much memory is available in MB? How busy is the CPU right now in percent? How many bytes per second is the main network interface receiving?

- You need: http://localhost:9090
- You'll have: ~/promql-answers.txt

```sh
$ P='docker exec prometheus promtool query instant http://localhost:9090'
$ $P 'up' >> ~/promql-answers.txt
$ $P 'node_memory_MemAvailable_bytes / 1024 / 1024' >> ~/promql-answers.txt
$ $P '100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))' >> ~/promql-answers.txt
$ $P 'rate(node_network_receive_bytes_total{device="eth0"}[5m])' >> ~/promql-answers.txt
$ cat ~/promql-answers.txt
```

On the lab machine the memory query returned `2495.42578125`, about 2.4 GB available. Your
numbers will differ; what matters is that every query returns a value and you can say what it
means. If a query is empty, check the label values on the Targets page (your interface may be
`ens5` or `enp0s3`, not `eth0`).

## Try it

- Start node_exporter and run `curl -s localhost:9100/metrics | grep -vc '^#'` to count its samples.
- Open `http://localhost:9090/targets` and confirm every target shows UP.
- Query `up` and say what a value of 0 would mean.
- Graph `100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))` over 30 minutes.
- Run `promtool check config prometheus.yml`, then break the file on purpose and read the error.
- Do the mini mission and keep `~/promql-answers.txt`.

## Quiz

1. Prometheus shows `up{job="node"} 0`. What does it mean?
   - The server's CPU is idle
   - **Prometheus tried to scrape the target and failed** (answer)
   - node_exporter has no metrics yet
   Why: Prometheus writes `up` itself after every scrape attempt, 1 for success and 0 for failure. Because Prometheus pulls, a dead target becomes a value you can alert on.

2. Why do you wrap `node_cpu_seconds_total` in `rate()` before graphing it?
   - **It is a counter that only goes up, so the raw value is a running total, not current usage** (answer)
   - rate() converts bytes to percent
   - Without rate() PromQL returns an error
   Why: A counter keeps adding up since the process started. rate(x[5m]) turns it into "per second, averaged over the last 5 minutes", and it handles counter resets on restart.

3. Which query gives the 95th percentile request time from a histogram?
   - avg(http_request_duration_seconds)
   - **histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))** (answer)
   - max(http_request_duration_seconds_bucket)
   Why: Histograms store counts per bucket in `_bucket` series with an `le` label. Take the rate of each bucket, keep `le` when you sum, then histogram_quantile estimates the percentile.

4. `node_load1 / count by (instance) (node_cpu_seconds_total{mode="idle"})` returns nothing. Why?
   - node_load1 is a counter
   - **The two sides have different label sets, so no series match; add on (instance)** (answer)
   - count by is not allowed in a division
   Why: Binary operators match series with exactly the same labels. node_load1 also carries job and env, the right side only has instance. `on (instance)` tells PromQL to match on that label alone.

5. What is the main job of a recording rule?
   - To send alerts to Slack
   - **To store the result of an expensive query as a new series, so dashboards read it cheaply** (answer)
   - To delete old data
   Why: Prometheus evaluates the rule on a schedule and saves the result under a new name such as instance:node_cpu_utilisation:rate5m. Dashboards then query one cheap series.

## Resources

- [Prometheus overview and architecture](https://prometheus.io/docs/introduction/overview/) (Prometheus)
- [Configuration (scrape_configs, rule_files)](https://prometheus.io/docs/prometheus/latest/configuration/configuration/) (Prometheus)
- [Querying basics (PromQL)](https://prometheus.io/docs/prometheus/latest/querying/basics/) (Prometheus)
- [PromQL functions](https://prometheus.io/docs/prometheus/latest/querying/functions/) (Prometheus)
- [Recording rules](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) (Prometheus)
- [Monitoring Linux host metrics with node_exporter](https://prometheus.io/docs/guides/node-exporter/) (Prometheus)
- [Metric and label naming](https://prometheus.io/docs/practices/naming/) (Prometheus)
- [PromLabs PromQL cheat sheet](https://promlabs.com/promql-cheat-sheet/) (PromLabs)
