Prometheus
medium 28 minPrometheus is an open source monitoring server.
Video lesson · Chapter 1 of 5
When the second ticket counter goes quiet
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
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.
May 2016
The Cloud Native Computing Foundation accepts Prometheus as its second hosted project, after Kubernetes.
July 2016
Version 1.0.0.
November 2017
Version 2.0.0, with a new storage engine.
August 2018
The project graduates in the foundation.
November 2024
Version 3.0: a new web interface, UTF-8 names, an OTLP receiver and Remote Write 2.0.
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.
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.
The reader fetches. The houses only have to show a number.
The idea
What runs where
One server and its neighbours
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
# 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 18job and instance when it scrapes.Metric types
| Type | Moves | Ask with | Example |
|---|---|---|---|
| Counter | Only up, or back to 0 at a restart | rate(), increase() | Requests, errors, bytes sent |
| Gauge | Up and down | The value, avg_over_time() | Queue length, memory, temperature |
| Histogram | Counts of observations in buckets | histogram_quantile() over rates | Request duration, latency |
| Summary | Quantiles that the program itself computes | Read it; never average it | One program, no adding up needed |
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
Collecting
Why pull, and when not
One scrape
What pulling gives
- You know when a target is down:
upis 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.
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"]--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
Storage facts
| Fact | Value |
|---|---|
| Newest data | In memory, secured by a write-ahead log in 128 MB files |
| First block | 2 hours of samples with an index from labels to series |
| Larger blocks | Up to 10% of the retention time or 31 days, whichever is smaller |
| Default retention | 15 days, if neither time nor size is set |
| Size limit advice | At most 80 to 85% of the disk, because compaction needs room |
| Average size | 1 to 2 bytes per sample |
| File system | Local 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
Asking
PromQL that you need
| Question | Query |
|---|---|
| Requests per second, per service | sum by (job) (rate(http_requests_total[5m])) |
| Share of errors | sum(rate(x_total{status=~"5.."}[5m])) divided by sum(rate(x_total[5m])) |
| 95th percentile, classic | histogram_quantile(0.95, sum by (le) (rate(d_bucket[5m]))) |
| 95th percentile, native | histogram_quantile(0.95, sum(rate(d[5m]))) |
| Targets that do not answer | up == 0 |
| Disk full in 4 hours? | predict_linear(free_bytes[1h], 4 * 3600) < 0 |
What rate() does
- 1
Take the window
All samples of the last 5 minutes, per series. Fewer than two samples give no answer.
- 2
Repair resets
If a value is lower than the one before, the program restarted. The counter is continued.
- 3
Extrapolate
The first and last sample rarely sit on the window's edges, so the increase is stretched to the full window.
- 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
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"promtool check rules and test them with promtool test rules.Alertmanager in four words
| Word | Meaning | Default |
|---|---|---|
| Group | Many alerts become one message, for example by cluster and alert name | First message after 30 s (group_wait) |
| Route | A tree decides who gets it | New members of a group after 5 m (group_interval) |
| Silence | Mute by labels for a time | Repeat after 4 h (repeat_interval) |
| Inhibit | The cluster is down, so stay quiet about its servers | None |
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
When one server is not enough
| Problem | Move | Price |
|---|---|---|
| One server may die | Run two with the same configuration | Double the scrapes; small differences between copies |
| Too many series | Split by team, region or job | No query over all of them without more tools |
| One overview of many | Federation of a few summed series | Only what you chose to copy |
| Years of data | Thanos, Mimir or a managed service | More parts to run, or a bill |
| Only collect here | Agent mode: scrape and remote write | No 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
| Watch | Why | With |
|---|---|---|
| Series in memory | The main driver of memory | prometheus_tsdb_head_series |
| Samples per second | Work and disk | rate(prometheus_tsdb_head_samples_appended_total[5m]) |
| Failed scrapes | Blind spots | up == 0 |
| Slow or failing rules | Late alerts | prometheus_rule_evaluation_failures_total |
| The whole chain | A dead server sends no alert | An 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
Neighbours
| Product | Alike | Different |
|---|---|---|
| Grafana | Charts and alerts | Draws data of others; stores no samples |
| Datadog | Metrics, labels called tags, alerts | A paid service: agents push to it |
| TimescaleDB | Time series | SQL and transactions inside PostgreSQL |
| Graphite | Stores numbers, draws them | Dotted 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;
upsays 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
- Prometheus: overview
- Prometheus: storage
- Prometheus: configuration
- Prometheus: metric types
- Prometheus: query functions
- Prometheus: when to use the Pushgateway
- Prometheus: Alertmanager
- Prometheus: long-term support releases
- Prometheus 3.0 announcement
- Native histograms specification
- CNCF project page
- Cloudflare: how we run Prometheus at scale