Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Prometheus: metrics and PromQL

40 min read
Improve this page

This module is the heart of the lab: Prometheus collects and stores the metrics that Grafana will display and on which the alerts will rest. You will install it on the cluster, understand how it collects data, then learn PromQL, its query language.

This module is long, because everything else depends on it: without PromQL, you will be able to write neither the queries of the Grafana dashboards nor the alerting rules of Alertmanager.

What you will learn

By the end of this module, you will be able to:

  1. Explain how Prometheus collects and stores metrics (pull architecture)
  2. Install Prometheus on Kubernetes with Helm
  3. Configure the scraping of pods and services
  4. Tell the 4 metric types apart (counter, gauge, histogram, summary)
  5. Write basic to intermediate PromQL queries
  6. Create recording rules to improve performance
  7. Diagnose common problems (targets down, high cardinality)

Prerequisites for this module

Before continuing, check that you have completed the previous modules:

  1. The Minikube cluster is running

    Open a terminal and type:

    Terminal window
    minikube status

    What you should see:

    minikube
    type: Control Plane
    host: Running
    kubelet: Running
    apiserver: Running
    kubeconfig: Configured

    If it is not the case, start Minikube:

    Terminal window
    minikube start --memory=10240 --cpus=4
  2. The OpenTelemetry Demo application is deployed

    Terminal window
    kubectl get pods -n otel-demo

    What you should see: many pods (~25) with the Running status.

    If it is not the case, go back to module 01 (in French).

  3. The observability namespace exists

    Terminal window
    kubectl get ns observability

    If the namespace does not exist:

    Terminal window
    kubectl create namespace observability
  4. The prometheus-community Helm repo has been added

    Terminal window
    helm repo list | grep prometheus

    What you should see: a line containing prometheus-community.

    If it is not the case:

    Terminal window
    helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
    helm repo update

Understand Prometheus before installing it

Before installing anything, let us understand why Prometheus works the way it does. This understanding will spare you a lot of confusion later.

The "pull" model, a fundamental difference

Most traditional monitoring systems, Graphite, StatsD or InfluxDB, work in push mode: your applications send their metrics to the server.

Prometheus does the opposite. It works in pull mode: Prometheus goes and gets the metrics from your applications.

Why this choice?

Push (traditional)Pull (Prometheus)
The application must know the server addressThe application just exposes an endpoint, it knows nothing about Prometheus
If the server is down, the metrics are lostIf Prometheus is down, it resumes scraping on restart
Hard to test locallyEasy to test: curl http://localhost:8080/metrics
Needs configuration on the application sideCentralized configuration in Prometheus

The /metrics endpoint, what Prometheus collects

Every application that Prometheus monitors must expose an HTTP /metrics endpoint that returns text in a specific format.

Let us look at a concrete example. Prometheus itself exposes its own metrics. Once it is installed, you will be able to read them:

Terminal window
# Port-forward to Prometheus
kubectl port-forward svc/prometheus-server 9090:80 -n observability

In another terminal:

Terminal window
curl http://localhost:9090/metrics 2>/dev/null | head -30

What you should see, something like:

# HELP prometheus_engine_query_duration_seconds Query timings
# TYPE prometheus_engine_query_duration_seconds summary
prometheus_engine_query_duration_seconds{slice="inner_eval",quantile="0.5"} 0.000012
prometheus_engine_query_duration_seconds{slice="inner_eval",quantile="0.9"} 0.000025
# HELP prometheus_tsdb_head_chunks Total number of chunks in the head block.
# TYPE prometheus_tsdb_head_chunks gauge
prometheus_tsdb_head_chunks 1234

Let us break down this format:

ElementMeaning
# HELP ...Human-readable documentation of the metric
# TYPE ...Metric type (counter, gauge, histogram, summary)
prometheus_tsdb_head_chunksMetric name
{slice="inner_eval",...}Labels (dimensions)
1234Current value

The OpenTelemetry Demo application does not expose a /metrics endpoint. It pushes its metrics over OTLP, not in the Prometheus format. This lab therefore relies on the system metrics (node_*, container_*, kube_*) to learn PromQL.

Close the port-forward (Ctrl+C) before continuing.

Complete Prometheus architecture

Now that you understand the pull model and the metrics format, here is the complete architecture:

Prometheus architecture: the scraper reads /metrics over HTTP on the targets (Node Exporter, application exporter, others) and writes into the TSDB, stored on local disk or through remote write; PromQL feeds Grafana, the alerting rules feed Alertmanager, which notifies Slack, email or PagerDuty.Prometheus ServerHTTP /metricsStorageLocal diskRemote WriteTargetsNode ExporterApp ExporterOther exportersScraperTSDBPromQLAlerting RulesGrafanaAlertmanagerSlack, email, PagerDuty
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The components explained:

ComponentWhat it does
RetrievalGoes and gets the metrics from each target at a fixed interval: every minute by default in this chart, every 15 seconds for the lab's otel-collector job
Service DiscoveryAutomatically discovers new pods/services in Kubernetes
TSDBStores the time series efficiently on disk
HTTP ServerLets you query the data through the web interface and the API
Rule EvaluationEvaluates the alerting rules and the recording rules

Install Prometheus on Kubernetes

Now that you understand how Prometheus works, let us install it.

  1. Move to the lab directory

    Terminal window
    cd ~/lab-observability
  2. Look at the Helm configuration

    Before installing, let us look at what we are going to deploy:

    Terminal window
    cat 02-prometheus/helm-values/prometheus-minimal.yaml

    What you see, an excerpt with the important points (the comments on the right of the lines are added here for reading):

    server:
    persistentVolume:
    enabled: true
    size: 8Gi # 8 GB of storage
    retention: "7d" # Keep the data for 7 days
    service:
    type: NodePort
    nodePort: 30090 # Reachable on this port
    # Scrape the OpenTelemetry Collector (installed in otel-demo in module 01)
    extraScrapeConfigs: |
    - job_name: 'otel-collector'
    static_configs:
    - targets: ['otel-collector.otel-demo.svc.cluster.local:8889']
    metrics_path: /metrics
    scrape_interval: 15s
    alertmanager:
    enabled: false # Enabled in module 04
    prometheus-pushgateway:
    enabled: false # Not used in this lab
    prometheus-node-exporter:
    enabled: true # System metrics of the nodes
    kube-state-metrics:
    enabled: true # Metrics on the state of the K8s objects

    This configuration does four things, the last of which is specific to this lab:

    • installs Prometheus with 7 days of retention
    • enables Node Exporter, for the CPU, RAM and disk metrics of the nodes
    • enables kube-state-metrics, for pods and deployments
    • scrapes the OpenTelemetry Collector of the otel-demo namespace, where the application's otel_* metrics come from

    It also disables two components that the chart deploys by default: Alertmanager, which will be enabled in module 04, and the Pushgateway, which this lab does not need. The prometheus-pushgateway.enabled: false key turns it off, so no pushgateway pod runs. The prometheus-pushgateway, prometheus-node-exporter and kube-state-metrics keys carry the exact name of the subchart they control. The old spellings kubeStateMetrics, nodeExporter and pushgateway match nothing in this chart anymore: Helm ignores them without printing an error, and the subchart stays in its default state.

  3. Install Prometheus

    Terminal window
    helm upgrade --install prometheus prometheus-community/prometheus \
    --version 31.0.0 \
    -n observability \
    -f 02-prometheus/helm-values/prometheus-minimal.yaml \
    --wait

    What you should see:

    Release "prometheus" does not exist. Installing it now.
    NAME: prometheus
    LAST DEPLOYED: ...
    NAMESPACE: observability
    STATUS: deployed
    ...

    The --wait option makes Helm wait until all the pods are ready before giving control back. This can take 1-2 minutes.

  4. Check that everything is running

    Terminal window
    kubectl get pods -n observability | grep -E 'prometheus-server|kube-state-metrics|node-exporter'

    What you should see:

    prometheus-kube-state-metrics-xxx 1/1 Running 0 2m
    prometheus-prometheus-node-exporter-xxx 1/1 Running 0 2m
    prometheus-server-xxxxxxxxxx-xxxxx 2/2 Running 0 2m

    All the pods must be Running.

    If the pod is not ready after 3 minutes, check the logs:

    Terminal window
    kubectl logs -n observability -l app.kubernetes.io/name=prometheus -c prometheus-server --tail=50
  5. Open the Prometheus interface

    There are two methods:

    Method 1, NodePort (recommended for Minikube):

    Terminal window
    minikube service prometheus-server -n observability --url

    Copy the URL displayed and open it in your browser.

    Method 2, Port-forward:

    Terminal window
    kubectl port-forward svc/prometheus-server 9090:80 -n observability

    Then open http://localhost:9090

You should now see the Prometheus web interface, a page with a query field at the top and several tabs (Graph, Alerts, Status...).

Explore the Prometheus interface

Before writing queries, let us tour the interface to understand what Prometheus shows us.

Prometheus interface

Status → Targets tab

Click Status in the top menu, then Targets.

This page is above all for troubleshooting. It shows every target Prometheus scrapes, with its state.

What you should see:

JobTargetsExpected state
kubernetes-api-servers1UP
kubernetes-nodes1 (Minikube has only one node)UP
kubernetes-nodes-cadvisor1UP
kubernetes-service-endpointsVariableUP (most of them)
prometheus1UP
otel-collector1UP

The chart declares other jobs: kubernetes-pods, kubernetes-pods-slow, kubernetes-service-endpoints-slow, kubernetes-services and prometheus-pushgateway. Each one only keeps the pods or services that carry its annotations: with no annotated pod or service, such a job has no target, and that is not a failure. The Pushgateway is disabled, so prometheus-pushgateway has nothing to scrape.

How to read this page:

  • UP (green): Prometheus scrapes successfully
  • DOWN (red): The scraping fails
  • Last Scrape: When the last scrape took place
  • Scrape Duration: How long the scrape took
  • Error: If DOWN, the error message

Status → Configuration tab

Click Status → Configuration.

You see the complete YAML configuration of Prometheus. It is useful to check that your scrape configs have been applied.

Look for the scrape_configs section and check the jobs present (kubernetes-nodes, kubernetes-service-endpoints, prometheus...).

Graph tab, the query space

Click Graph.

This is where you will spend most of your time. The field at the top lets you write PromQL queries.

First query, test that everything works:

Type in the query field:

up

Click Execute.

What you should see:

A list of lines, each with:

  • Labels between {} (job, instance, namespace...)
  • A value: 1 (UP) or 0 (DOWN)

This special up metric is created automatically by Prometheus for each target. It equals 1 if the last scrape succeeded, 0 otherwise.

Switch to the graph view:

Click the Graph tab (under the query field, not in the menu).

You now see the evolution of the metric over time. As up is generally 1, you will see horizontal lines.

The 4 metric types, understand before querying

Before PromQL, you need to understand the four metric types. Each is used differently, and mixing them up is a common mistake at the beginning.

Counter, it only goes up

A counter is a value that only goes up (or restarts at 0 when the application restarts).

Concrete examples:

  • Total number of HTTP requests received
  • Total number of errors
  • Total number of bytes transferred
  • Total number of connections opened (cumulative)

Classic mistake, using a raw counter:

# ❌ BAD: the raw value cannot be interpreted
http_requests_total
# This query returns, for example, 123456, 123789, 124012...
# These numbers tell you nothing useful!

The right way, using rate():

# ✅ GOOD: request rate per second over the last 5 minutes
rate(http_requests_total[5m])
# This query returns, for example, 12.5, 13.2, 11.8...
# = 12.5 requests per second, much more useful!

Practical exercise, run these queries in Prometheus:

# 1. Raw value (look, it is a number that keeps growing)
prometheus_http_requests_total
# 2. Rate per second (now it is usable)
rate(prometheus_http_requests_total[5m])
# 3. Total increase over the last hour
increase(prometheus_http_requests_total[1h])

Gauge, it goes up and down

A gauge is a value that can go up and down freely.

Concrete examples:

  • Memory currently used
  • Current temperature
  • Number of connections currently open
  • Number of tasks in a queue

Usage, the raw value is directly usable:

# ✅ Memory available on the nodes (in bytes)
node_memory_MemAvailable_bytes
# ✅ Convert to GB for readability
node_memory_MemAvailable_bytes / 1024 / 1024 / 1024
# ✅ Percentage of memory used
(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100

Practical exercise, run these queries:

# 1. Available memory
node_memory_MemAvailable_bytes
# 2. In gigabytes (more readable)
node_memory_MemAvailable_bytes / 1024 / 1024 / 1024
# 3. Percentage of memory used (the complete calculation)
(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100

What you should see: A percentage between 0 and 100. On Minikube, it is probably between 30% and 70%.

Histogram, for distributions and percentiles

A histogram measures the distribution of a value, typically durations (latency).

Why a histogram rather than a simple average?

Imagine a web service whose average latency is 100 ms. That sounds good. But if 99% of the requests take 10 ms and 1% take 10 seconds, the average hides the problem: that 1% of users get an unusable service.

Histograms let you compute percentiles:

  • P50 (median): 50% of the requests are faster than this value
  • P90: 90% of the requests are faster
  • P99: 99% of the requests are faster (important to detect outliers)

How does it work?

A histogram stores the values in "buckets" (slices):

# Requests with duration <= 5ms: 100
# Requests with duration <= 10ms: 250
# Requests with duration <= 25ms: 400
# Requests with duration <= 50ms: 450
# Requests with duration <= 100ms: 480
# Requests with duration <= +Inf: 500

Prometheus can then compute: "99% of the requests (495) took less than X ms".

Usage, computing a percentile:

# P99 of the latency of Prometheus HTTP requests (99% of the requests are faster than this value)
histogram_quantile(
0.99,
rate(prometheus_http_request_duration_seconds_bucket[5m])
)

Let us break down this query:

The query is read from the inside out, in three steps:

  1. prometheus_http_request_duration_seconds_bucket: the raw data of the histogram
  2. rate(...[5m]): the rate per second, mandatory on a histogram
  3. histogram_quantile(0.99, ...): the 99th percentile computed on these rates

Practical exercise:

# P50 (median): half of the requests are faster
histogram_quantile(
0.50,
rate(prometheus_http_request_duration_seconds_bucket[5m])
)
# P90: 90% of the requests are faster
histogram_quantile(
0.90,
rate(prometheus_http_request_duration_seconds_bucket[5m])
)
# P99: 99% of the requests are faster (detects outliers)
histogram_quantile(
0.99,
rate(prometheus_http_request_duration_seconds_bucket[5m])
)

What you should see: Values in seconds. The P99 should be higher than the P50.

Summary, precomputed percentiles (avoid)

A summary looks like a histogram but the percentiles are computed on the application side, not by Prometheus.

Differences with histograms:

AspectHistogramSummary
Percentile computationBy Prometheus (flexible)By the application (fixed)
Aggregation possibleYesNo (percentiles cannot be added)
Recommendationpreferred over the summaryto avoid if possible

Both are now superseded by native histograms. Stable since Prometheus 3.8 (native histograms specification), they replace the fixed buckets of a classic histogram with a resolution that the server adjusts by itself. The Histograms and summaries page of the official documentation is clear: "If you can, use native histograms and prefer them over both classic histograms and summaries".

Two practical consequences. Native histograms remain aggregatable with each other even when their resolution differs, whereas two classic histograms with different bounds are not. And their collection does not turn itself on: you have to set scrape_native_histograms in the scrape configuration, the old feature flag having become inoperative in 3.9.

Classic histograms and summaries keep their place as long as your instrumentation chain does not produce native histograms, and that is still the case for many exporters: this is why this lab teaches them.

Why avoid summaries?

If 10 pods each compute their own P99, you cannot deduce the global P99 from them. Percentiles cannot be added, and no average of percentiles makes up for it.

With histograms, Prometheus can compute the global P99 from the aggregated buckets.

Example of a summary (just to recognize the format):

http_request_duration_seconds{quantile="0.99"}
http_request_duration_seconds{quantile="0.5"}

PromQL, learning by practice

Now that you understand the metric types, let us learn PromQL by practicing.

Basic syntax, selectors

The basic unit in PromQL is the selector. It lets you retrieve time series.

Simple selector, all the series of a metric:

prometheus_http_requests_total

Run this query. You see all the series with this metric, each with its labels (code, handler, job...).

Filter by label (equality):

prometheus_http_requests_total{code="200"}

Now you only see the requests with a 200 code.

Filter by label (regex):

# Only the handlers that start with /api
prometheus_http_requests_total{handler=~"/api.*"}
# Everything except 200
prometheus_http_requests_total{code!="200"}
# All the 5xx codes (regex)
prometheus_http_requests_total{code=~"5.."}

Combine filters:

prometheus_http_requests_total{handler="/metrics", code="200"}

Summary of the matching operators:

OperatorMeaningExample
=Equalcode="200"
!=Not equalcode!="200"
=~Matches the regexcode=~"5.."
!~Does not match the regexhandler!~"/health.*"

Essential functions

Here are the basic PromQL functions:

rate(), per-second rate of a counter

This is the function that makes a counter usable. rate() computes the average slope of the counter over the given window, automatically handling the resets to zero when the application restarts. It expects a range vector, hence the square brackets [5m]: applied to an instant value, it fails.

# HTTP requests per second (over the last 5 minutes)
rate(prometheus_http_requests_total[5m])

The [5m] is a "range vector". It tells Prometheus to look at the last 5 minutes of data to compute the rate.

Which window to choose? rate() needs at least two samples in the window. The window must therefore cover several scrape intervals: in this lab, the prometheus job is scraped every minute, and [1m] most often holds only one sample, hence no result.

WindowUsage
[1m]Very reactive, only if scraping is frequent (15 s or less)
[5m]Good compromise with a per-minute scrape
[15m]Smoothed, hides short peaks
[1h]Very smoothed view

Exercise, compare the results with different windows:

rate(prometheus_http_requests_total[1m])
rate(prometheus_http_requests_total[5m])
rate(prometheus_http_requests_total[15m])

Switch to the Graph view and observe: the [1m] query returns few or no points, for lack of two samples per window. The [5m] one follows the variations, the [15m] one is smoother.

sum(), aggregate series

Without aggregation, rate() returns one series per label combination. That is often too detailed.

# BEFORE: one series per handler, per code...
rate(prometheus_http_requests_total[5m])
# AFTER: a single value, the total of all the requests
sum(rate(prometheus_http_requests_total[5m]))

Aggregate by certain labels, with by:

# Total per HTTP code
sum by (code) (rate(prometheus_http_requests_total[5m]))
# Total per handler
sum by (handler) (rate(prometheus_http_requests_total[5m]))
# Total per code AND per handler
sum by (code, handler) (rate(prometheus_http_requests_total[5m]))

Exclude certain labels, with without:

# Everything except the "instance" label (useful when you have several pods)
sum without (instance) (rate(prometheus_http_requests_total[5m]))

avg(), max(), min(), other aggregations

These three aggregators follow the same syntax as sum(), but answer different questions: avg() smooths and hides the extremes, max() reveals the worst case, min() the best. On a fleet of nodes, max is often the most telling for an alert, because it is the most loaded node that falls first, not the average. Like sum(), they accept by and without to choose the labels kept.

# Average memory usage per node
avg by (instance) (node_memory_MemAvailable_bytes)
# Maximum of the P99 latency
max(histogram_quantile(0.99, rate(prometheus_http_request_duration_seconds_bucket[5m])))
# Minimum per handler
min by (handler) (rate(prometheus_http_requests_total[5m]))

count(), count series

count() does not care about the values but about the number of series that match. Combined with a comparison, it becomes a monitoring tool: count(up == 1) gives the number of healthy targets, count(up == 0) the number of targets that are down. It is also a first reflex in front of suspicious cardinality, to measure how many series a metric carries.

# How many targets are monitored?
count(up)
# How many targets are UP?
count(up == 1)
# How many pods in the observability namespace?
count(kube_pod_info{namespace="observability"})

topk() and bottomk(), the extremes

When a metric produces dozens of series, a graph becomes unreadable. topk(N, ...) only keeps the N highest series, bottomk(N, ...) the lowest. It is the tool to answer "which are the 5 most requested endpoints?" without drowning the result. On a dashboard, topk also limits the number of curves displayed and lightens the query.

# The 5 handlers with the most requests
topk(5, sum by (handler) (rate(prometheus_http_requests_total[5m])))
# The 3 handlers with the fewest requests
bottomk(3, sum by (handler) (rate(prometheus_http_requests_total[5m])))

Arithmetic and comparison operators

Arithmetic, to compute ratios and percentages:

# Memory used (total - available)
node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes
# Percentage of memory used
(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100
# Error rate as a percentage
sum(rate(prometheus_http_requests_total{code=~"5.."}[5m]))
/
sum(rate(prometheus_http_requests_total[5m]))
* 100

Comparison, to filter the results:

# Only the targets that are DOWN
up == 0
# Handlers with more than 0.1 req/s
sum by (handler) (rate(prometheus_http_requests_total[5m])) > 0.1
# Memory usage > 80%
(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) > 0.8

Guided exercises, put it into practice

These exercises let you check your understanding. Do them in order.

Exercise 1: Count and filter the targets

Goal: Check the health of your infrastructure.

  1. Count all the targets

    count(up)

    What you should see: A number (probably between 10 and 20).

  2. Count the UP targets

    count(up == 1)
  3. Count the DOWN targets

    count(up == 0)

    What you should see: Ideally 0. If it is not 0, note which targets are DOWN.

  4. List the DOWN targets

    up == 0

    This query returns the series with their labels, so you can identify which service has a problem.

Exercise 2: Analyze CPU usage

Goal: Understand how to compute CPU usage.

  1. Display the idle CPU time

    node_cpu_seconds_total{mode="idle"}

    It is a counter: the total number of seconds spent idle.

  2. Compute the idle time rate per second

    rate(node_cpu_seconds_total{mode="idle"}[5m])

    This returns a value close to 1 (1 second of idle per second = 100% idle).

  3. Average over all the cores

    avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
  4. Convert to a usage percentage

    100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

    What you should see: A percentage between 0 and 100. It is the CPU usage of your Minikube node.

Exercise 3: Analyze HTTP requests

Goal: Measure the HTTP traffic of Prometheus.

  1. Total requests per second

    sum(rate(prometheus_http_requests_total[5m]))

    What you should see: A number (e.g. 0.5 = 0.5 requests per second on the Prometheus API).

  2. Requests per handler

    sum by (handler) (rate(prometheus_http_requests_total[5m]))

    Switch to the Graph view. You see which Prometheus endpoints are the most requested.

  3. Requests per HTTP status code

    sum by (code) (rate(prometheus_http_requests_total[5m]))

    Ideally, the majority should be 200.

  4. Error percentage (5xx)

    sum(rate(prometheus_http_requests_total{code=~"5.."}[5m]))
    /
    sum(rate(prometheus_http_requests_total[5m]))
    * 100

    What you should see: A percentage. If it is above 1%, you have a problem.

Exercise 4: Measure latency

Goal: Compute the latency percentiles.

  1. Global P50 (median)

    histogram_quantile(
    0.50,
    sum(rate(prometheus_http_request_duration_seconds_bucket[5m])) by (le)
    )

    Note: by (le) is mandatory because histogram_quantile needs the buckets.

  2. Global P99

    histogram_quantile(
    0.99,
    sum(rate(prometheus_http_request_duration_seconds_bucket[5m])) by (le)
    )
  3. P99 per handler

    histogram_quantile(
    0.99,
    sum by (handler, le) (rate(prometheus_http_request_duration_seconds_bucket[5m]))
    )

    What you should see: A latency in seconds for each handler.

  4. Identify the slowest handler

    topk(1,
    histogram_quantile(
    0.99,
    sum by (handler, le) (rate(prometheus_http_request_duration_seconds_bucket[5m]))
    )
    )

Exercise 5: Combine metrics (SLI)

Goal: Create a simple service level indicator (SLI).

A common SLI: "Percentage of successful requests with an acceptable latency".

  1. Define "acceptable latency" = less than 500ms

    We count the requests in the bucket <= 0.5s:

    sum(rate(prometheus_http_request_duration_seconds_bucket{le="0.5"}[5m]))
  2. Compare with the total requests

    sum(rate(prometheus_http_request_duration_seconds_bucket{le="0.5"}[5m]))
    /
    sum(rate(prometheus_http_request_duration_seconds_count[5m]))
    * 100

    What you should see: A percentage. "X% of the requests have a latency < 500ms".

  3. The "no error" criterion needs another metric

    The prometheus_http_request_duration_seconds histogram only carries the handler and le labels: it has no code label. A code!~"5.." filter applied to it excludes nothing, and the query would return exactly the percentage of step 2. The return code is read on prometheus_http_requests_total, which conversely carries no latency buckets.

    A "successful and fast" SLI therefore requires a metric that carries both dimensions at once, which the OpenTelemetry instrumentation of the application provides (duration and return code on the same series). Keep the lesson before the formulas: check the real labels of a metric before filtering on them, by running it alone in the Graph tab, which lists the labels of each series.

Scraping configuration, how Prometheus discovers targets

You may wonder how Prometheus knows which pods to scrape. That is Kubernetes Service Discovery.

The annotation mechanism

Prometheus can automatically scrape the pods of a Kubernetes cluster thanks to annotations. For this, the chart declares by default the kubernetes-pods job: it only keeps the pods that carry the prometheus.io/scrape: "true" annotation, and reads their port and path from two other annotations. The lab's values file therefore does not have to declare it again. The OTel Demo application does not expose /metrics (see the box below): its metrics therefore do not arrive through this job.

# Principle:
# for each pod with the prometheus.io/scrape: "true" annotation,
# Prometheus will scrape the /metrics endpoint

For a pod to be scraped automatically through annotations, it must have:

apiVersion: v1
kind: Pod
metadata:
name: my-app
annotations:
prometheus.io/scrape: "true" # Enables scraping
prometheus.io/port: "8080" # Port of the /metrics endpoint
prometheus.io/path: "/metrics" # Path (default /metrics)

What Prometheus scrapes in this lab

Before writing queries, you need to know where the data comes from. This table sums up the four sources that Prometheus queries in this lab and their collection mechanism: the "How" column explains why a target may appear missing from the Targets page.

SourceMetricsHow
Node Exporternode_* (CPU, RAM, disk)Through Kubernetes service discovery
kube-state-metricskube_* (pods, deployments)Through Kubernetes service discovery
cAdvisorcontainer_* (containers)Through the kubelet
OTel Collectorotel_* (application metrics)Through the static otel-collector job

Add a custom scraping job

If you want to scrape a service that does not have the annotations, you can add a static job to the extraScrapeConfigs list of the values file.

Edit 02-prometheus/helm-values/prometheus-minimal.yaml and add this job at the end of the value of extraScrapeConfigs, with the same indentation as the jobs already there. Do not add a second extraScrapeConfigs key.

# NEW: custom job for a server outside the cluster
- job_name: 'node-bastion'
static_configs:
- targets: ['10.0.0.25:9100']

Then apply:

Terminal window
helm upgrade prometheus prometheus-community/prometheus \
--version 31.0.0 \
-n observability \
-f 02-prometheus/helm-values/prometheus-minimal.yaml

Wait 1 minute and check in Status → Targets that the new job appears.

Recording rules, improve performance

Recording rules precompute expensive queries. Instead of redoing the calculation each time a dashboard is displayed, Prometheus does it at a regular interval and stores the result as a new metric.

Why recording rules?

A recording rule precomputes the result of a query at a regular interval and stores it as a new metric. The benefit shows mostly on heavy queries displayed in a loop on a dashboard: the calculation is done once per interval, not on every refresh.

Without a recording ruleWith a recording rule
Calculation on every queryPeriodic calculation (e.g. every 30s)
Slow if the query is complexFast (precomputed result)
Uses CPU on every displayUses CPU once

Create a recording rule

Create the file 02-prometheus/recording-rules.yaml:

groups:
- name: http_recording_rules
interval: 30s # Compute every 30 seconds
rules:
# Requests per second per handler
- record: job:http_requests_per_second:rate5m
expr: sum by (handler) (rate(prometheus_http_requests_total[5m]))
# Errors per second per handler
- record: job:http_errors_per_second:rate5m
expr: sum by (handler) (rate(prometheus_http_requests_total{code=~"5.."}[5m]))
# Error rate per handler
- record: job:http_error_rate:ratio
expr: |
job:http_errors_per_second:rate5m
/
job:http_requests_per_second:rate5m
# P99 latency per handler
- record: job:http_latency_p99:seconds
expr: |
histogram_quantile(0.99,
sum by (handler, le) (rate(prometheus_http_request_duration_seconds_bucket[5m]))
)

Naming convention:

  • Format: level:metric:operation
  • level: aggregation level (job, instance, cluster...)
  • metric: what it measures
  • operation: the operation applied (rate5m, ratio, seconds...)

Once the rule is loaded, job:http_error_rate:ratio replaces the complete query: it is more readable and faster.

This file is not loaded as is by the chart: the prometheus chart reads its rules from the serverFiles key of its values, under recording_rules.yml for the recording rules and alerting_rules.yml for the alerts. Module 04 practices this loading with the alerting rules; keep the convention and the principle of precomputation in mind here.

Storage and retention

How long does Prometheus keep the data?

By default in our configuration: 7 days. After that, the data is deleted automatically.

You can change that in the values:

server:
retention: "30d" # Keep 30 days

How much disk space?

Order of magnitude given by the Prometheus storage documentation: 1 to 2 bytes per sample after compression.

Calculation:

Space = nb_series × samples_per_day × days × 2 bytes

Example: 10,000 series, scrape every 15s, 30 days retention:

10000 × (86400 ÷ 15) × 30 × 2 = ~3.5 GB

Check current usage

Before sizing the disk, measure what Prometheus actually stores. These two internal metrics are the most telling: prometheus_tsdb_head_series gives the number of active series in memory, the first factor of the space calculation seen above; prometheus_tsdb_storage_blocks_bytes gives the size already written to disk. A continuous rise in the number of series without new traffic betrays a cardinality problem.

# Number of active series
prometheus_tsdb_head_series
# Storage size
prometheus_tsdb_storage_blocks_bytes

Troubleshooting, solve common problems

Problem: Target DOWN

Symptom: A target is red (DOWN) in Status → Targets.

Step-by-step diagnosis:

  1. Note the error message in the Error column

  2. Check that the pod is running

    Terminal window
    kubectl get pods -n <namespace>
  3. Test the endpoint manually

    Terminal window
    kubectl port-forward pod/<pod-name> 8080:<metrics-port>
    curl http://localhost:8080/metrics

    If it works: the problem is probably the network between Prometheus and the pod.

    If it fails: the pod does not expose its metrics correctly.

  4. Check the annotations

    Terminal window
    kubectl get pod <pod-name> -o yaml | grep -A5 annotations

Problem: High cardinality (slow Prometheus)

Symptom: Prometheus uses a lot of memory, the queries are slow.

Probable cause: Too many time series (high cardinality).

Diagnosis:

# Top 10 metrics by number of series
topk(10, count by (__name__) ({__name__!=""}))

What you should see: If a metric has tens of thousands of series, that is probably the problem.

Frequent causes:

  • user_id or request_id label (one series per user/request!)
  • path label with variable IDs (/users/123, /users/456...)
  • timestamp label (classic mistake)

Solutions:

  1. Fix the instrumentation on the application side (remove the problematic labels)
  2. Use metric_relabel_configs to remove the labels at the Prometheus level

Problem: Prometheus restarts (OOMKilled)

Symptom: The Prometheus pod restarts regularly.

Diagnosis:

Terminal window
kubectl describe pod prometheus-server-xxx -n observability | grep -A10 "Last State"

If you see OOMKilled: Prometheus is out of memory.

Solutions:

  1. Increase the resource limits:
server:
resources:
requests:
memory: "1Gi"
limits:
memory: "2Gi"
  1. Reduce the retention or the number of series

Final validation

Before moving on to the next module, check that everything works.

  1. Prometheus is reachable

    Terminal window
    curl -s http://localhost:9090/api/v1/status/config | jq .status

    Expected result: "success"

  2. The targets are UP

    Terminal window
    curl -s http://localhost:9090/api/v1/targets | jq '.data.activeTargets | map(select(.health=="up")) | length'

    Expected result: A number > 0 (ideally all your targets)

  3. The system metrics are present

    Terminal window
    curl -s 'http://localhost:9090/api/v1/query?query=node_memory_MemAvailable_bytes' | jq '.data.result | length'

    Expected result: A number > 0 (the node_exporter metrics)

  4. You know how to write PromQL queries

    Test this query in the interface:

    topk(3, sum by (handler) (rate(prometheus_http_requests_total[5m])))

    Expected result: The 3 Prometheus handlers with the most requests per second.

Key points

Let us sum up the key concepts of this module:

  1. Pull architecture: Prometheus goes and gets the metrics on the /metrics endpoints
  2. 4 metric types:
    • Counter: always use rate() or increase()
    • Gauge: directly usable value
    • Histogram: for percentiles with histogram_quantile()
    • Summary: to avoid if possible, and native histogram as soon as the instrumentation chain allows it
  3. PromQL:
    • Selectors with labels: {method="GET", status=~"2.."}
    • Functions: rate(), sum(), avg(), histogram_quantile()
    • Aggregation: by (label), without (label)
  4. Service Discovery: Prometheus discovers Kubernetes pods automatically
  5. Recording rules: precomputation for better performance
  6. Diagnosis: a DOWN target is read in Status → Targets, excessive cardinality with topk(10, count by (__name__) ({__name__!=""}))