AlgoViz

Prometheus

medium 28 min

Prometheus is an open source monitoring server.

Video lesson · Chapter 1 of 5

When the second ticket counter goes quiet

0:00 / 4:06

Prometheus in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Prometheus collects metrics: numbers that are measured again and again, such as requests served or memory in use. Each program shows its current numbers on a web page, usually /metrics. Prometheus visits that page every few seconds and writes down what it sees. One visit is called a scrape.

Every number belongs to a time series, named by a metric name and a set of labels. http_requests_total{method="GET", status="200"} is one series; the same name with status 500 is another. The query language PromQL filters, adds up and compares series.

The server is one program with its own storage and no other dependencies. Sending alert messages is the job of a second program, Alertmanager. Drawing dashboards is usually left to Grafana.

Why it exists

A team with many short-lived servers cannot log in to each one. It needs to ask "how many errors per second, for this service, in all copies together" and to be woken up when the answer is bad. Labels make such questions easy, because the dimension is data and not part of a long name.

Monitoring must also work when other things are broken. A single server that needs no database, no queue and no cluster has few ways to fail at the same time as your system. The project says it values getting alerts out to people above all else.

A short history

  1. 2012

    Work begins at SoundCloud, started privately by Matt T. Proud and Julius Volz. Google's book on reliability engineering says the result shares many similarities with Google's internal Borgmon.

  2. May 2016

    The Cloud Native Computing Foundation accepts Prometheus as its second hosted project, after Kubernetes.

  3. July 2016

    Version 1.0.0.

  4. November 2017

    Version 2.0.0, with a new storage engine.

  5. August 2018

    The project graduates in the foundation.

  6. November 2024

    Version 3.0: a new web interface, UTF-8 names, an OTLP receiver and Remote Write 2.0.

  7. November 2025

    Version 3.8.0 makes native histograms a stable, optional feature.

Words to know

Target
One address that is scraped, for example one copy of a service.
Scrape
One HTTP GET of a target's metrics page.
Time series
A metric name plus one exact set of labels, with its samples over time.
Sample
One timestamp and one 64-bit floating point value (or a native histogram).
Cardinality
How many series a metric has: the number of different label sets.
Exporter
A small program that translates another system's numbers into the metrics format.
Recording rule
A query that runs on a timer and stores its answer as a new series.
Alertmanager
The program that groups, silences and routes alerts to people.

How it works

Step through the idea, or press Play.

Step 1 of 3

Scrape. GET /metrics from every target on a timer

Understand it

Start here

The gas meter reader

Imagine a reader who walks down a street every 15 seconds and writes down what every gas meter shows. Nobody in the houses has to send a letter.

One round every 15 seconds
A100B48STREET LISTA, BNOTEBOOKA: 1000 sRead what the meter shows

The reader fetches. The houses only have to show a number.

The idea

What runs where

One server and its neighbours

Inside our system, one Prometheus machine scrapes an app server and a node exporter. It sends alerts to Alertmanager. Grafana asks it with PromQL. People on call get charts from Grafana and messages from Alertmanager.
Arrows show who starts the conversation. The scrape arrow points away from Prometheus.
  • Client libraries

    Count and measure inside your program and show the numbers on a page.

  • Exporters

    Translate machines, databases and devices that cannot speak the format.

  • Server

    Discovery, scraping, storage, PromQL and rules in one program.

  • Alertmanager

    Grouping, silences, inhibition and routing.

  • Pushgateway

    Holds the last result of a batch job that is gone before it could be scraped.

  • Grafana

    The usual place for dashboards. It only asks, it stores no samples.

What a monitoring system must do in general is on monitoring basics. Building a metrics platform for many customers is an exercise of its own: metrics monitoring system. This page is about the product.

Data

Names, labels and four metric types

Text
# HELP http_requests_total Requests served.# TYPE http_requests_total counterhttp_requests_total{method="GET",status="200"} 1027http_requests_total{method="GET",status="500"} 3# HELP process_open_fds Open file descriptors.# TYPE process_open_fds gaugeprocess_open_fds 18
What a target shows. Three samples of three series. Prometheus adds the labels job and instance when it scrapes.

Metric types

TypeMovesAsk withExample
CounterOnly up, or back to 0 at a restartrate(), increase()Requests, errors, bytes sent
GaugeUp and downThe value, avg_over_time()Queue length, memory, temperature
HistogramCounts of observations in bucketshistogram_quantile() over ratesRequest duration, latency
SummaryQuantiles that the program itself computesRead it; never average itOne program, no adding up needed
Apart from native histograms, the server stores all types as plain numbers. The type matters for the question you ask.

A classic histogram is many series: one cumulative counter per bucket with the label le (less or equal), plus a sum and a count. A native histogram is one sample with many buckets whose borders need no choosing. It is stable since 3.8.0, but you must turn on scrape_native_histograms. The documentation prefers native ones where your library has them; at present that is Go and Java.

Cardinality is a product

series=5 methods×8 statuses×50 paths×20 instances=40,000\text{series} = 5\ \text{methods} \times 8\ \text{statuses} \times 50\ \text{paths} \times 20\ \text{instances} = 40{,}000
Assumed numbers, worst case. Adding a user id with 100,000 values would make 4 billion. Aim below 10 values per metric, says the project, and look for another way above 100.

Collecting

Why pull, and when not

One scrape

What pulling gives

  • You know when a target is down: up is 0
  • You can open the page in a browser and look
  • A second server or a laptop can scrape the same targets
  • Targets need no address of the monitoring system

Where it is hard

  • Jobs that end before the next scrape
  • Targets behind a firewall or NAT
  • Very short spikes between two scrapes
  • Exact events, such as money

The project itself calls pulling only slightly better and says it should not be the main point. The general choice is on push and pull, and finding targets is on service discovery.

YAML
global:  scrape_interval: 15s        # default 1m  evaluation_interval: 15s    # default 1mstorage:  tsdb:    retention:      time: 30d               # default 15d      size: 400GBrule_files:  - rules/*.ymlalerting:  alertmanagers:    - static_configs:        - targets: ["am-1:9093", "am-2:9093"]scrape_configs:  - job_name: shop    metrics_path: /metrics    sample_limit: 5000        # fail the scrape above this    static_configs:      - targets: ["10.0.0.5:8080", "10.0.0.6:8080"]
Retention now belongs in this file: the flags --storage.tsdb.retention.time and .size are marked deprecated.

The scrape timeout is 10 seconds by default and cannot be longer than the interval. Since 3.0 the server can also receive OpenTelemetry metrics at /api/v1/otlp/v1/metrics when started with --web.enable-otlp-receiver. See OpenTelemetry.

Inside

The time series database

From a sample to a block

A restart replays the log to rebuild the part that was only in memory.

Storage facts

FactValue
Newest dataIn memory, secured by a write-ahead log in 128 MB files
First block2 hours of samples with an index from labels to series
Larger blocksUp to 10% of the retention time or 31 days, whichever is smaller
Default retention15 days, if neither time nor size is set
Size limit adviceAt most 80 to 85% of the disk, because compaction needs room
Average size1 to 2 bytes per sample
File systemLocal and POSIX; NFS is not supported

The log and the sorted blocks resemble an LSM tree. The difference: data arrives nearly in time order, and old data is dropped one whole block at a time.

Disk for one server

1,000,000 series15 s≈66,667 sampless66,667×2 B×1,296,000 s≈173 GB\frac{1{,}000{,}000\ \text{series}}{15\,\text{s}} \approx 66{,}667\ \tfrac{\text{samples}}{\text{s}} \qquad 66{,}667 \times 2\,\text{B} \times 1{,}296{,}000\,\text{s} \approx 173\ \text{GB}
A million series, 15 days (15 times 86,400 seconds), the upper 2 bytes. That fits one disk, so the decision is: no cluster needed for storage yet.

Asking

PromQL that you need

QuestionQuery
Requests per second, per servicesum by (job) (rate(http_requests_total[5m]))
Share of errorssum(rate(x_total{status=~"5.."}[5m])) divided by sum(rate(x_total[5m]))
95th percentile, classichistogram_quantile(0.95, sum by (le) (rate(d_bucket[5m])))
95th percentile, nativehistogram_quantile(0.95, sum(rate(d[5m])))
Targets that do not answerup == 0
Disk full in 4 hours?predict_linear(free_bytes[1h], 4 * 3600) < 0
x_total, d and free_bytes are short stand-ins for real metric names.

What rate() does

  1. 1

    Take the window

    All samples of the last 5 minutes, per series. Fewer than two samples give no answer.

  2. 2

    Repair resets

    If a value is lower than the one before, the program restarted. The counter is continued.

  3. 3

    Extrapolate

    The first and last sample rarely sit on the window's edges, so the increase is stretched to the full window.

  4. 4

    Divide

    By the seconds of the window. So increase() may say 3.2 requests. That is expected.

A series that stops being exposed is marked stale and disappears from results soon after. Otherwise a query looks back at most 5 minutes (--query.lookback-delta). A query is stopped after 2 minutes by default, and at most 20 run at once.

Alerts

Rules and Alertmanager

The life of an alert

YAML
groups:  - name: shop    rules:      - record: job:http_requests:rate5m        expr: sum by (job) (rate(http_requests_total[5m]))      - alert: HighErrorShare        expr: |          sum by (job) (rate(http_requests_total{status=~"5.."}[5m]))            / sum by (job) (rate(http_requests_total[5m])) > 0.05        for: 10m        keep_firing_for: 5m        labels:          severity: page        annotations:          summary: "{{ $labels.job }}: {{ $value | humanizePercentage }} errors"
Check files with promtool check rules and test them with promtool test rules.

Alertmanager in four words

WordMeaningDefault
GroupMany alerts become one message, for example by cluster and alert nameFirst message after 30 s (group_wait)
RouteA tree decides who gets itNew members of a group after 5 m (group_interval)
SilenceMute by labels for a timeRepeat after 4 h (repeat_interval)
InhibitThe cluster is down, so stay quiet about its serversNone

Alert on what users feel, such as errors and latency, and keep causes for the dashboard. See latency spike for an example of using both.

Growing

Two servers, many servers, long memory

Two identical servers

Inside our system, two separate machines, Prometheus A and Prometheus B, scrape the same targets. Both send the same alerts to an Alertmanager cluster and both send copies to a long-term store by remote write.
They do not know each other. Alertmanager removes the duplicate alerts.

When one server is not enough

ProblemMovePrice
One server may dieRun two with the same configurationDouble the scrapes; small differences between copies
Too many seriesSplit by team, region or jobNo query over all of them without more tools
One overview of manyFederation of a few summed seriesOnly what you chose to copy
Years of dataThanos, Mimir or a managed serviceMore parts to run, or a bill
Only collect hereAgent mode: scrape and remote writeNo queries or alerts in that process

Thanos puts a sidecar next to each server that uploads blocks to object storage, and a querier in front of all. Grafana Mimir receives data by remote write and stores it in object storage for many tenants; since version 3.0 the preferred setup has Kafka in the write path. Do not put a load balancer between Prometheus and Alertmanager: every server must know all Alertmanagers.

Operate

Running it safely

WatchWhyWith
Series in memoryThe main driver of memoryprometheus_tsdb_head_series
Samples per secondWork and diskrate(prometheus_tsdb_head_samples_appended_total[5m])
Failed scrapesBlind spotsup == 0
Slow or failing rulesLate alertsprometheus_rule_evaluation_failures_total
The whole chainA dead server sends no alertAn always-firing alert that an outside service must keep receiving

Do not put Prometheus on the public internet: its security model assumes that anyone who reaches the HTTP port may read all series. TLS and basic authentication exist. Reload and admin endpoints are off unless you start it with --web.enable-lifecycle or --web.enable-admin-api. A minor release appears about every six weeks; a long-term support version gets selected fixes for a year.

Decide

When to choose it, and when not

Does it fit?

Choose it when

  • You run services or containers and want metrics and alerts
  • You want an open format that most infrastructure already speaks
  • Alerts must work when the rest is broken
  • A team can run one or two machines

Look elsewhere when

  • You need exact counts for money
  • You want logs or traces: see ELK Stack and Jaeger
  • You need a value for every user
  • Nobody should operate it: see Datadog

Neighbours

ProductAlikeDifferent
GrafanaCharts and alertsDraws data of others; stores no samples
DatadogMetrics, labels called tags, alertsA paid service: agents push to it
TimescaleDBTime seriesSQL and transactions inside PostgreSQL
GraphiteStores numbers, draws themDotted names instead of labels; does not scrape

Summary

The whole topic in one minute.

Prometheus pulls numbers from targets, stores labelled series on one machine and evaluates rules on them. Counters only go up, so you always ask for a rate. Histograms can be added up across machines, summaries cannot. up tells you whether the last scrape worked.

Its cost is the number of series, so never put unbounded values such as user ids into labels. Run two identical servers for availability, send copies to a long-term store when one machine or 15 days is not enough, and let Alertmanager turn many alerts into one message.

  • Targets show numbers, Prometheus fetches them; up says whether that worked.
  • A series is a name plus labels, and the number of series is the cost.
  • Counters need rate(): rate first, then sum.
  • Histograms can be added up, summaries cannot.
  • One node, 15 days by default, 1 to 2 bytes a sample; two servers for availability.
  • Prometheus decides that an alert fires, Alertmanager decides who hears it.

Sources