Metrics with Prometheus

Intermediate · 11 min

How Prometheus works from the operator's side: targets expose /metrics as text, Prometheus scrapes them, and PromQL turns counters into rates.

Before thisRunning services with systemdThe Linux server from an operator's seat

Prometheus Monitoring with Julius | PromLabs · 11 min

Metrics with Prometheus

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Prometheus Monitoring with Julius | PromLabsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Prometheus pulls. Each target serves its current metric values as plain text at /metrics, and Prometheus scrapes every target on a fixed interval and stores the samples as time series.
  • A time series is a metric name plus a set of labels. Every distinct label combination is a separate series, so a label like user_id can explode memory use.
  • Counters only go up, so you never graph them raw. rate() turns a counter into a per-second rate and handles restarts that reset it to zero.
  • A histogram exports cumulative bucket counts plus a sum and a count, which lets PromQL compute averages and estimate percentiles across many instances.
  • Exporters, such as node_exporter for Linux hosts, translate systems that don't speak Prometheus into the same text format.

The problem: is it slow, or does it just feel slow?

A user says the site is slow. Without numbers you are guessing. You could SSH in and run top, but that shows one machine at one moment, and the problem may have been ten minutes ago on a different machine. What you need is a record of a few key numbers (request rate, error rate, latency, CPU, memory) for every instance, every few seconds, kept for weeks.

That is a metrics system. The system design lesson on monitoring covers why metrics, logs and traces each exist. This lesson is about running the most common open-source metrics system, Prometheus, a graduated CNCF project. The current release when I checked was v3.16.0.

How Prometheus works

Prometheus is built on a simple, slightly unusual choice: it pulls.

  1. Each target (your app, a database, a Linux host) serves its current metric values as plain text over HTTP, conventionally at /metrics.
  2. The Prometheus server scrapes every target on an interval, often 15 or 30 seconds, and appends the values to its time-series database.
  3. You query the stored series with PromQL, from Prometheus’s own UI, from Grafana, or in alert rules.

Pulling has a useful side effect. Prometheus knows the list of targets, so a target that stops answering is noticed at once. Every scrape writes a synthetic series, up, which is 1 or 0. Short batch jobs that end before a scrape can push to a Pushgateway instead, but that is the exception.

Targets come from configuration or from service discovery: Kubernetes, cloud VM APIs, Consul or DNS, so new instances are found automatically.

Software you can’t change is covered by exporters, small programs that read a system’s own stats and serve them in Prometheus format. node_exporter for Linux hosts is the one nearly everyone runs.

The data model

Every series is a metric name plus labels:

http_requests_total{method="GET",code="500"}

Labels are what make Prometheus powerful. You can sum across all instances, or split by status code. They are also the main way to hurt it, because every distinct label combination is a separate series. A label with a user ID or a full URL path makes the series count grow without limit. This is called a cardinality explosion, and it is the most common reason a Prometheus server runs out of memory.

The four metric types are counter (only goes up), gauge (up and down), histogram (bucketed observations) and summary (client-computed quantiles). How to choose them in code is the backend roadmap’s metrics and instrumentation lesson.

A worked example: a /metrics endpoint and a rate

I didn’t have Prometheus on this machine, so I did its job by hand. I wrote a small Python web app that serves the text format itself: a request counter labelled by status code, an in-flight gauge and a latency histogram. About 5% of requests return 500, and a few are slow on purpose. I sent it 100 requests, scraped /metrics with curl, waited, sent 150 more and scraped again. The second scrape:

$ curl -s localhost:9464/metrics
# HELP http_requests_total Requests handled.
# TYPE http_requests_total counter
http_requests_total{method="GET",code="200"} 244
http_requests_total{method="GET",code="500"} 6
# HELP http_requests_in_flight Requests being served now.
# TYPE http_requests_in_flight gauge
http_requests_in_flight 0
# HELP http_request_duration_seconds Request latency.
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.05"} 193
http_request_duration_seconds_bucket{le="0.1"} 193
http_request_duration_seconds_bucket{le="0.25"} 220
http_request_duration_seconds_bucket{le="0.5"} 220
http_request_duration_seconds_bucket{le="1.0"} 250
http_request_duration_seconds_bucket{le="+Inf"} 250
http_request_duration_seconds_sum 26.070
http_request_duration_seconds_count 250

The buckets are cumulative: le="0.25" counts every request that took 0.25 seconds or less. The first scrape, 33 seconds earlier, showed 97 successes and 3 errors. A short script did the subtraction that PromQL’s rate() and increase() do:

$ python3 rate.py
request rate  4.55/s over 33s
error ratio   2.00%
mean latency  109 ms

The error ratio over the window was 2%, not the 5% I configured. That is just randomness over a small sample of 150 requests. In Prometheus the same three numbers would be:

sum(rate(http_requests_total[5m]))
sum(rate(http_requests_total{code=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))
rate(http_request_duration_seconds_sum[5m]) / rate(http_request_duration_seconds_count[5m])

The real rate() does more than my subtraction. It notices when a counter drops, which means a restart, and treats the drop as a reset rather than negative traffic. It also extrapolates to the edges of the window.

The scrape configuration

To point a real Prometheus at that app, prometheus.yml needs a scrape job. This is from the Prometheus configuration docs. I did not run it, because Prometheus is not installed here:

global:
  scrape_interval: 15s
scrape_configs:
  - job_name: shop-web
    static_configs:
      - targets: ["10.20.48.10:9464", "10.20.64.10:9464"]

Prometheus adds job and instance labels to every series it scrapes, which is how you later tell instances apart.

About the video

“Introduction to the Prometheus Monitoring System | Key Concepts and Features” is from PromLabs, the channel of Prometheus co-founder Julius Volz, published December 2022, 10 minutes 37 seconds. Its chapters cover the system architecture, the dimensional data model, the text-based transfer format, PromQL, integrated alerting and service discovery, which matches this lesson closely. It predates Prometheus 3.0, so the UI shown will look older. English is judged from the title, description and channel. The same channel’s metric-types video and TechWorld with Nana’s architecture explainer are linked below.

Where this fits

Prometheus stores the numbers. To look at them you need dashboards: dashboards with Grafana.

Check yourself

  1. 01Why is a raw counter graph rarely useful?

    It only climbs, and it drops to zero on every restart. What you want is how fast it climbs, which is what rate() gives, with resets handled.

  2. 02You add a label with the customer's email address to a request counter. What goes wrong?

    Each distinct email creates a new time series, so the number of series grows with your customer count and Prometheus memory and query cost grow with it.

  3. 03What is the difference between a counter and a gauge?

    A counter only increases, such as requests served. A gauge can go up and down, such as requests in flight or memory in use.

  4. 04How does Prometheus know a target is down?

    The scrape fails, and Prometheus records the synthetic series up for that target as 0. Alerting on up == 0 catches dead targets.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark