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:
- Explain how Prometheus collects and stores metrics (pull architecture)
- Install Prometheus on Kubernetes with Helm
- Configure the scraping of pods and services
- Tell the 4 metric types apart (counter, gauge, histogram, summary)
- Write basic to intermediate PromQL queries
- Create recording rules to improve performance
- Diagnose common problems (targets down, high cardinality)
Prerequisites for this module
Before continuing, check that you have completed the previous modules:
-
The Minikube cluster is running
Open a terminal and type:
Terminal window minikube statusWhat you should see:
minikubetype: Control Planehost: Runningkubelet: Runningapiserver: Runningkubeconfig: ConfiguredIf it is not the case, start Minikube:
Terminal window minikube start --memory=10240 --cpus=4 -
The OpenTelemetry Demo application is deployed
Terminal window kubectl get pods -n otel-demoWhat you should see: many pods (~25) with the
Runningstatus.If it is not the case, go back to module 01 (in French).
-
The observability namespace exists
Terminal window kubectl get ns observabilityIf the namespace does not exist:
Terminal window kubectl create namespace observability -
The prometheus-community Helm repo has been added
Terminal window helm repo list | grep prometheusWhat 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-chartshelm 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 address | The application just exposes an endpoint, it knows nothing about Prometheus |
| If the server is down, the metrics are lost | If Prometheus is down, it resumes scraping on restart |
| Hard to test locally | Easy to test: curl http://localhost:8080/metrics |
| Needs configuration on the application side | Centralized 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:
# Port-forward to Prometheuskubectl port-forward svc/prometheus-server 9090:80 -n observabilityIn another terminal:
curl http://localhost:9090/metrics 2>/dev/null | head -30What you should see, something like:
# HELP prometheus_engine_query_duration_seconds Query timings# TYPE prometheus_engine_query_duration_seconds summaryprometheus_engine_query_duration_seconds{slice="inner_eval",quantile="0.5"} 0.000012prometheus_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 gaugeprometheus_tsdb_head_chunks 1234Let us break down this format:
| Element | Meaning |
|---|---|
# HELP ... | Human-readable documentation of the metric |
# TYPE ... | Metric type (counter, gauge, histogram, summary) |
prometheus_tsdb_head_chunks | Metric name |
{slice="inner_eval",...} | Labels (dimensions) |
1234 | Current 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:
The components explained:
| Component | What it does |
|---|---|
| Retrieval | Goes 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 Discovery | Automatically discovers new pods/services in Kubernetes |
| TSDB | Stores the time series efficiently on disk |
| HTTP Server | Lets you query the data through the web interface and the API |
| Rule Evaluation | Evaluates the alerting rules and the recording rules |
Install Prometheus on Kubernetes
Now that you understand how Prometheus works, let us install it.
-
Move to the lab directory
Terminal window cd ~/lab-observability -
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.yamlWhat you see, an excerpt with the important points (the comments on the right of the lines are added here for reading):
server:persistentVolume:enabled: truesize: 8Gi # 8 GB of storageretention: "7d" # Keep the data for 7 daysservice:type: NodePortnodePort: 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: /metricsscrape_interval: 15salertmanager:enabled: false # Enabled in module 04prometheus-pushgateway:enabled: false # Not used in this labprometheus-node-exporter:enabled: true # System metrics of the nodeskube-state-metrics:enabled: true # Metrics on the state of the K8s objectsThis 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-demonamespace, where the application'sotel_*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: falsekey turns it off, so nopushgatewaypod runs. Theprometheus-pushgateway,prometheus-node-exporterandkube-state-metricskeys carry the exact name of the subchart they control. The old spellingskubeStateMetrics,nodeExporterandpushgatewaymatch nothing in this chart anymore: Helm ignores them without printing an error, and the subchart stays in its default state. -
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 \--waitWhat you should see:
Release "prometheus" does not exist. Installing it now.NAME: prometheusLAST DEPLOYED: ...NAMESPACE: observabilitySTATUS: deployed...The
--waitoption makes Helm wait until all the pods are ready before giving control back. This can take 1-2 minutes. -
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 2mprometheus-prometheus-node-exporter-xxx 1/1 Running 0 2mprometheus-server-xxxxxxxxxx-xxxxx 2/2 Running 0 2mAll 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 -
Open the Prometheus interface
There are two methods:
Method 1, NodePort (recommended for Minikube):
Terminal window minikube service prometheus-server -n observability --urlCopy the URL displayed and open it in your browser.
Method 2, Port-forward:
Terminal window kubectl port-forward svc/prometheus-server 9090:80 -n observabilityThen 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.

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:
| Job | Targets | Expected state |
|---|---|---|
kubernetes-api-servers | 1 | UP |
kubernetes-nodes | 1 (Minikube has only one node) | UP |
kubernetes-nodes-cadvisor | 1 | UP |
kubernetes-service-endpoints | Variable | UP (most of them) |
prometheus | 1 | UP |
otel-collector | 1 | UP |
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:
upClick Execute.
What you should see:
A list of lines, each with:
- Labels between
{}(job, instance, namespace...) - A value:
1(UP) or0(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 interpretedhttp_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 minutesrate(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 hourincrease(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 readabilitynode_memory_MemAvailable_bytes / 1024 / 1024 / 1024
# ✅ Percentage of memory used(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100Practical exercise, run these queries:
# 1. Available memorynode_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)) * 100What 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: 500Prometheus 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:
prometheus_http_request_duration_seconds_bucket: the raw data of the histogramrate(...[5m]): the rate per second, mandatory on a histogramhistogram_quantile(0.99, ...): the 99th percentile computed on these rates
Practical exercise:
# P50 (median): half of the requests are fasterhistogram_quantile( 0.50, rate(prometheus_http_request_duration_seconds_bucket[5m]))
# P90: 90% of the requests are fasterhistogram_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:
| Aspect | Histogram | Summary |
|---|---|---|
| Percentile computation | By Prometheus (flexible) | By the application (fixed) |
| Aggregation possible | Yes | No (percentiles cannot be added) |
| Recommendation | preferred over the summary | to 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_totalRun 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 /apiprometheus_http_requests_total{handler=~"/api.*"}
# Everything except 200prometheus_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:
| Operator | Meaning | Example |
|---|---|---|
= | Equal | code="200" |
!= | Not equal | code!="200" |
=~ | Matches the regex | code=~"5.." |
!~ | Does not match the regex | handler!~"/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.
| Window | Usage |
|---|---|
[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 requestssum(rate(prometheus_http_requests_total[5m]))Aggregate by certain labels, with by:
# Total per HTTP codesum by (code) (rate(prometheus_http_requests_total[5m]))
# Total per handlersum by (handler) (rate(prometheus_http_requests_total[5m]))
# Total per code AND per handlersum 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 nodeavg by (instance) (node_memory_MemAvailable_bytes)
# Maximum of the P99 latencymax(histogram_quantile(0.99, rate(prometheus_http_request_duration_seconds_bucket[5m])))
# Minimum per handlermin 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 requeststopk(5, sum by (handler) (rate(prometheus_http_requests_total[5m])))
# The 3 handlers with the fewest requestsbottomk(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 percentagesum(rate(prometheus_http_requests_total{code=~"5.."}[5m]))/sum(rate(prometheus_http_requests_total[5m]))* 100Comparison, to filter the results:
# Only the targets that are DOWNup == 0
# Handlers with more than 0.1 req/ssum by (handler) (rate(prometheus_http_requests_total[5m])) > 0.1
# Memory usage > 80%(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) > 0.8Guided 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.
-
Count all the targets
count(up)What you should see: A number (probably between 10 and 20).
-
Count the UP targets
count(up == 1) -
Count the DOWN targets
count(up == 0)What you should see: Ideally 0. If it is not 0, note which targets are DOWN.
-
List the DOWN targets
up == 0This 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.
-
Display the idle CPU time
node_cpu_seconds_total{mode="idle"}It is a counter: the total number of seconds spent idle.
-
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).
-
Average over all the cores
avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) -
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.
-
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).
-
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.
-
Requests per HTTP status code
sum by (code) (rate(prometheus_http_requests_total[5m]))Ideally, the majority should be 200.
-
Error percentage (5xx)
sum(rate(prometheus_http_requests_total{code=~"5.."}[5m]))/sum(rate(prometheus_http_requests_total[5m]))* 100What you should see: A percentage. If it is above 1%, you have a problem.
Exercise 4: Measure latency
Goal: Compute the latency percentiles.
-
Global P50 (median)
histogram_quantile(0.50,sum(rate(prometheus_http_request_duration_seconds_bucket[5m])) by (le))Note:
by (le)is mandatory becausehistogram_quantileneeds the buckets. -
Global P99
histogram_quantile(0.99,sum(rate(prometheus_http_request_duration_seconds_bucket[5m])) by (le)) -
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.
-
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".
-
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])) -
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]))* 100What you should see: A percentage. "X% of the requests have a latency < 500ms".
-
The "no error" criterion needs another metric
The
prometheus_http_request_duration_secondshistogram only carries thehandlerandlelabels: it has nocodelabel. Acode!~"5.."filter applied to it excludes nothing, and the query would return exactly the percentage of step 2. The return code is read onprometheus_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 endpointFor a pod to be scraped automatically through annotations, it must have:
apiVersion: v1kind: Podmetadata: 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.
| Source | Metrics | How |
|---|---|---|
| Node Exporter | node_* (CPU, RAM, disk) | Through Kubernetes service discovery |
| kube-state-metrics | kube_* (pods, deployments) | Through Kubernetes service discovery |
| cAdvisor | container_* (containers) | Through the kubelet |
| OTel Collector | otel_* (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:
helm upgrade prometheus prometheus-community/prometheus \ --version 31.0.0 \ -n observability \ -f 02-prometheus/helm-values/prometheus-minimal.yamlWait 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 rule | With a recording rule |
|---|---|
| Calculation on every query | Periodic calculation (e.g. every 30s) |
| Slow if the query is complex | Fast (precomputed result) |
| Uses CPU on every display | Uses 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 measuresoperation: 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 daysHow 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 bytesExample: 10,000 series, scrape every 15s, 30 days retention:
10000 × (86400 ÷ 15) × 30 × 2 = ~3.5 GBCheck 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 seriesprometheus_tsdb_head_series
# Storage sizeprometheus_tsdb_storage_blocks_bytesTroubleshooting, solve common problems
Problem: Target DOWN
Symptom: A target is red (DOWN) in Status → Targets.
Step-by-step diagnosis:
-
Note the error message in the Error column
-
Check that the pod is running
Terminal window kubectl get pods -n <namespace> -
Test the endpoint manually
Terminal window kubectl port-forward pod/<pod-name> 8080:<metrics-port>curl http://localhost:8080/metricsIf it works: the problem is probably the network between Prometheus and the pod.
If it fails: the pod does not expose its metrics correctly.
-
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 seriestopk(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_idorrequest_idlabel (one series per user/request!)pathlabel with variable IDs (/users/123,/users/456...)timestamplabel (classic mistake)
Solutions:
- Fix the instrumentation on the application side (remove the problematic labels)
- Use
metric_relabel_configsto remove the labels at the Prometheus level
Problem: Prometheus restarts (OOMKilled)
Symptom: The Prometheus pod restarts regularly.
Diagnosis:
kubectl describe pod prometheus-server-xxx -n observability | grep -A10 "Last State"If you see OOMKilled: Prometheus is out of memory.
Solutions:
- Increase the resource limits:
server: resources: requests: memory: "1Gi" limits: memory: "2Gi"- Reduce the retention or the number of series
Final validation
Before moving on to the next module, check that everything works.
-
Prometheus is reachable
Terminal window curl -s http://localhost:9090/api/v1/status/config | jq .statusExpected result:
"success" -
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)
-
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)
-
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:
- Pull architecture: Prometheus goes and gets the metrics on the
/metricsendpoints - 4 metric types:
- Counter: always use
rate()orincrease() - 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
- Counter: always use
- PromQL:
- Selectors with labels:
{method="GET", status=~"2.."} - Functions:
rate(),sum(),avg(),histogram_quantile() - Aggregation:
by (label),without (label)
- Selectors with labels:
- Service Discovery: Prometheus discovers Kubernetes pods automatically
- Recording rules: precomputation for better performance
- Diagnosis: a DOWN target is read in Status → Targets, excessive
cardinality with
topk(10, count by (__name__) ({__name__!=""}))