Prometheus: Architecture and TSDB
What Prometheus Is
Prometheus is an open-source monitoring system and time-series database (TSDB) built at SoundCloud in 2012, modelled on Google's internal Borgmon. It joined the CNCF in 2016 and graduated in 2018. In one binary it does five jobs: discovers targets, scrapes them over HTTP, stores the samples, answers queries in PromQL (see PromQL) and evaluates rules that record new series or fire alerts (see Alerting and SLOs). Its data model is the one defined in the Metrics part: a series is a metric name plus a set of label pairs, and a sample is one (timestamp, float64) pair in a series.
It deliberately does not do: long-term storage, clustering, authentication, logs or traces. Those are the jobs of the systems in the Scaling Prometheus part. That narrowness is the design: one node that is simple to run and whose failure modes are local.
The Components
| Component | What it is | Notes |
|---|---|---|
| Server | The prometheus binary: scrape manager, TSDB, PromQL engine, rule manager, web UI and HTTP API | Port 9090. --agent mode runs only scrape + remote_write (no local query, no rules) for edge collectors. |
| Client library | A library (Go, Java, Python, ...) your service links to; it keeps counters, gauges and histograms in memory and serves them on /metrics | Instrumentation inside your process. See Metrics for the metric types. |
| Exporter | A separate process that turns a system you cannot instrument into /metrics | node_exporter (host CPU, disk, network), mysqld_exporter, blackbox_exporter (probes endpoints from outside), kube-state-metrics (Kubernetes object state, from the API server), cAdvisor (container CPU and memory, built into the kubelet) |
| Pushgateway | A small server that holds the last value pushed to it and exposes it for scraping | Only for service-level batch jobs. Traps below. |
| Alertmanager | Separate binary that receives alerts from Prometheus and groups, deduplicates, routes and silences them | The Alerting and SLOs part. |
| Service discovery (SD) | Plug-ins that ask Kubernetes, Consul, EC2, DNS or a file for the current list of targets | The target list changes without a restart. |
The Pull Model
Prometheus scrapes: every scrape_interval it sends GET /metrics to each target, parses the response and appends every sample, stamped with the scrape time, to the TSDB. The target does not know Prometheus exists. Three consequences matter in design interviews:
- Health comes for free. A failed scrape is itself a data point: Prometheus writes a synthetic series
up{job="api",instance="10.0.1.7:8080"}=1if the scrape succeeded,0if not. It also writesscrape_duration_seconds,scrape_samples_scraped,scrape_samples_post_metric_relabelingandscrape_series_addedper target.up == 0is the cheapest, most important alert you can write. - The server controls the load. A target cannot flood Prometheus; it can only be scraped slowly. The price is that Prometheus must be able to reach every target, which is hard across NAT, firewalls and short-lived jobs.
- Sample timestamps are the scrape time, not the event time. The resolution of everything downstream is the scrape interval.
Defaults: scrape_interval 1m, scrape_timeout 10s (the timeout may not exceed the interval). Most teams set 15s or 30s globally.
A real scrape config
Two relabeling phases exist and confusing them is the most common config bug. Relabeling is a pipeline of rules that rewrite a label set. relabel_configs runs on the target, before the scrape: it sees the __meta_* labels from service discovery, __address__ and __metrics_path__, and can keep/drop whole targets or rewrite where to scrape. metric_relabel_configs runs on every scraped series, after the scrape and before storage: it can drop series or labels, and is your last line of defence against cardinality.
prometheus.yml
global:
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s # how often rules run
external_labels: {cluster: prod-eu1, replica: a} # attached on remote_write / alerts, not stored
scrape_configs:
- job_name: kubernetes-pods
kubernetes_sd_configs: [{role: pod}]
sample_limit: 50000 # scrape FAILS (up=0) if more samples survive relabeling
relabel_configs: # ---- phase 1: per TARGET, before the scrape ----
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep # only pods annotated prometheus.io/scrape=true
regex: "true"
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace # rewrite 10.0.1.7:8080 -> 10.0.1.7:9102
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_label_app]
target_label: app
metric_relabel_configs: # ---- phase 2: per SERIES, after the scrape ----
- source_labels: [__name__]
action: drop # never store this metric
regex: "go_gc_duration_seconds.*|apiserver_request_duration_seconds_bucket"
- action: labeldrop # remove a label from every series
regex: "request_id|user_id"Rule of thumb: decide about targets in relabel_configs; decide about series in metric_relabel_configs. Labels beginning __ are discarded after phase 1 except __name__. A sample_limit is evaluated after metric_relabel_configs.
Other discovery mechanisms use the same shape: consul_sd_configs, ec2_sd_configs, dns_sd_configs, and file_sd_configs (a JSON/YAML file you generate; the escape hatch when nothing else fits).
Exposition Format
The exposition format is the text a target returns on /metrics. A histogram is exposed as cumulative _bucket{le=...} counters plus _sum and _count (see Metrics):
# HELP http_requests_total Total HTTP requests handled.
# TYPE http_requests_total counter
http_requests_total{method="GET",route="/cart",status="200"} 128334
http_requests_total{method="GET",route="/cart",status="500"} 17
# HELP http_request_duration_seconds Request latency.
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{route="/cart",le="0.05"} 200
http_request_duration_seconds_bucket{route="/cart",le="0.1"} 600
http_request_duration_seconds_bucket{route="/cart",le="0.25"} 900
http_request_duration_seconds_bucket{route="/cart",le="+Inf"} 1000
http_request_duration_seconds_sum{route="/cart"} 142.7
http_request_duration_seconds_count{route="/cart"} 1000
# HELP process_resident_memory_bytes Resident memory size in bytes.
# TYPE process_resident_memory_bytes gauge
process_resident_memory_bytes 4.1943e+07OpenMetrics is the standardised, stricter superset of this format (it requires a trailing # EOF, adds a _created timestamp and exemplars, see Beyond the three pillars). Prometheus 3 negotiates the format by Content-Type (text 0.0.4/1.0.0, OpenMetrics, or protobuf) and fails the scrape if the header is missing or unrecognised; Prometheus 2 silently assumed text. A target with a broken proxy in front now shows up == 0; fallback_scrape_protocol is the escape hatch.
What Changed in Prometheus 3.x
Prometheus 3.0 shipped 14 Nov 2024; the latest release at time of writing is 3.15.1 (21 Oct 2026). The changes that bite in practice:
| Change | Version | What it means for you |
|---|---|---|
New web UI; old UI behind --enable-feature=old-ui | 3.0 | Cosmetic, but the old UI is a migration bridge only. |
| UTF-8 metric and label names by default | 3.0 | Names like http.server.request.duration are legal; query them as {"http.server.request.duration"}. metric_name_validation_scheme: legacy restores the old rules. |
le/quantile normalised to floats | 3.0 | le="1" is stored as le="1.0". Dashboards and alerts that match le="1" silently return nothing. |
| Range selectors are left-open | 3.0 | [5m] is (t-5m, t]; a sample exactly on the left edge is excluded, so [1m] at 15 s scrape returns exactly 4 samples. Regex . now matches newline. |
Scrape fails without a valid Content-Type | 3.0 | See above. |
holt_winters renamed double_exponential_smoothing (experimental flag) | 3.0 | Old dashboards break. |
| A v3 TSDB can only be read by v2.55 or newer | 3.0 | Upgrade to 2.55 first if you may roll back. |
OTLP receiver: POST /api/v1/otlp/v1/metrics, enabled by --web.enable-otlp-receiver | 3.0, direct-to-TSDB in 3.7 | Details below. |
Native histograms stable but opt-in: scrape_native_histograms: true (and send_native_histograms on remote write) | stable 3.8 (Nov 2025); flag a no-op from 3.9 | Default is still false in v3; the docs say both default to true in v4. |
| Remote write 2.0: metadata, native histograms, start timestamps | receiver tracks 2.0-rc.4 from 3.8 | The storage page still calls the 2.0 spec experimental; 1.0 is the stable one. |
anchored / smoothed range modifiers | 3.7, experimental flag promql-extended-range-selectors | Removes extrapolation guesswork; smoothed needs a sample after the evaluation time, so it under-estimates in rules. |
| XOR2 float chunk encoding | stable 3.15 (Sep 2026) | Select with storage.tsdb.chunk_encoding.floats: xor2. Check that tools reading the TSDB directly (Thanos sidecar) support it first. |
TSDB Internals
The TSDB is Prometheus's own storage engine (a descendant of the Gorilla design from Facebook), written to one local directory. Every design choice follows from one fact: the newest data is hot and mutable, everything older is immutable and written once.
1 · The head block and the WAL
- A sample arrives. The scraper looks the label set up in the in-memory head; a new label set creates a head series (
memSeries) with a numeric series ID, its label set, and an open chunk. - It is first appended to the WAL. The write-ahead log is a sequence of 128 MB segment files (
wal/00000123), written in 32 KB pages, holding Series records (ID, labels) and Samples records (ID, timestamp, value). It exists only for crash recovery; reads never touch it. - It goes into the open chunk. A chunk holds up to 120 samples (30 minutes at 15 s). When full, the chunk is flushed to
chunks_head/and mmapped back (since 2.19), so only a small reference stays on the Go heap; the OS pages it in when queried. - When the head spans 1.5 × 2 h = 3 h, its oldest 2 h are compacted into a persistent block; the WAL is truncated and a checkpoint (
checkpoint.00000122) is written: it keeps the series records of series still alive plus samples newer than the cut, so replay never needs the old segments. Series with no samples left in the head are garbage-collected then.
Consequence: head memory is proportional to series that have received a sample in the last 2-3 hours, not to series that exist "right now". A Kubernetes deploy that renames every pod doubles the head series for the next 2-3 hours (series churn) even though the live count is unchanged.
2 · Blocks
A block is a directory named by a ULID that covers a fixed time range and is never modified:
01H9ZQ…/
meta.json ulid, minTime, maxTime, stats (numSamples, numSeries, numChunks), compaction.level, sources
index symbol table, series (labels + chunk refs), postings, label-value index
chunks/000001 chunks, up to 512 MB per segment file
tombstones (series, time-range) deletions awaiting the next compactionA fresh block covers 2 h. A background compactor merges adjacent blocks (default ranges 2 h, 6 h, 18 h, 54 h, ... ×3 each step) up to a ceiling of min(31 days, 10 % of retention); with the default 15 d retention that ceiling is 36 h, so you end up with 18 h blocks. Compaction exists for query efficiency (fewer index lookups) and to apply tombstones and merge overlapping blocks (needed once out-of-order ingestion is enabled).
Retention is two independent limits, whichever hits first: --storage.tsdb.retention.time (default 15d) and --storage.tsdb.retention.size (default 0 = off). Deletion is by whole block: a block is dropped only once its maxTime is older than the limit, so disk briefly exceeds the size cap; leave 15-20 % headroom. Disk planning formula: retention_seconds × samples_per_second × bytes_per_sample.
3 · The inverted index: how a selector is resolved
The index is a classic search-engine structure. For every label=value pair it stores a postings list: the sorted list of series IDs that carry it. A selector is an AND of such lists.
Equality matchers read one list each. A regex matcher (status=~"5..") must first scan all values of the label, then take the union of the matching lists; a negative matcher (!=, !~) is the complement against the whole label, and a selector made only of negative or regex matchers is the slowest thing you can send. After the intersection, only the surviving series' chunks are read and decoded.
4 · Compression: why a sample costs ~1.4 bytes
Raw, a sample is 16 bytes (int64 timestamp + float64 value). Prometheus chunks use the Gorilla scheme (Pelkonen et al., VLDB 2015):
- Timestamps: delta-of-delta. Scrapes are almost periodic. Store the first timestamp, the first delta, then only the change in delta. At a steady 15 s cadence that change is 0, which costs 1 bit; millisecond jitter costs 16-24 bits.
- Values: XOR with the previous value. Neighbouring floats share sign, exponent and high mantissa bits, so the XOR is mostly zeros: store the position and length of the non-zero run only. An unchanged value (a gauge that did not move) is also 1 bit.
The Gorilla paper measured 1.37 bytes/sample on Facebook's data; the Prometheus docs say "1-2 bytes". Sizing example: 1 M active series at 15 s is 66,667 samples/s; for 15 d (1,296,000 s) that is 86.4 billion samples ≈ 118-130 GB. Counters that grow by large irregular amounts and high-entropy gauges compress worst; histogram buckets compress well (monotonic, mostly unchanged) but there are many of them, which is the real cost.
5 · Memory: what a series costs
Each head series pays for: its label set (strings, interned), the postings entries, the open chunk, mmap references and Go GC overhead. Secondary sources and field reports commonly quote roughly 3-4 KB of RAM per active series for typical label sets; there is no official constant, because label length and churn dominate. Measure yours: process_resident_memory_bytes / prometheus_tsdb_head_series. Budget 2× the head estimate for GC headroom, compaction and queries, and remember mmapped blocks live in the OS page cache, outside the Go heap.
| Active series | Head RAM at ~3.5 KB | Plan for |
|---|---|---|
| 100 k | ~350 MB | 2 GB |
| 1 M | ~3.5 GB | 8 GB |
| 10 M | ~35 GB | 64-80 GB, and think about sharding (see Scaling Prometheus) |
6 · Staleness
A series simply stops receiving samples when a target dies. If PromQL kept returning its last value you would see ghosts, so Prometheus writes a special staleness marker (a NaN with a reserved bit pattern) in two cases: the target disappears from service discovery or its scrape fails (markers for all its series), or a series is missing from a successful scrape. An instant-vector selector looks back at most the lookback delta (5 minutes) for the latest sample, but returns nothing if that sample is a marker. Series ingested with explicit timestamps (e.g. via federation with honor_timestamps) get no markers and linger for 5 minutes.
Pushgateway: Only for Batch Jobs
A short-lived job (nightly backup, cron) may finish before Prometheus scrapes it. The Pushgateway accepts PUT/POST /metrics/job/<name> and re-exposes the last pushed values. Use it for service-level batch results (backup_last_success_timestamp_seconds), nothing else: it never expires data, so a pushed value from a dead instance lives forever; it cannot tell you the job is down (up describes the gateway, not the job); it is a single point of failure and bottleneck; and it must be scraped with honor_labels: true or Prometheus overwrites your job label. Prefer node_exporter's textfile collector for per-host batch metrics, or OTLP/delta handling for event-style data.
Production Traps
The Invariants
- Guarantees: A scrape that completes is stored atomically with one timestamp per target scrape. A crash loses at most what was in the WAL's unflushed tail; replay restores the head. Blocks on disk are immutable. Retention deletes whole blocks only. Every target gets a synthetic
upseries, and a series that stops being exposed is marked stale rather than repeating its last value. - Does not guarantee: Replication or clustering (one disk is the only copy). That a failed or timed-out scrape leaves any partial data. Event-time accuracy (timestamps are scrape times). Memory bounded by anything but your series count: nothing stops a new label from creating millions of series unless you set
sample_limit/label_limit. Fast restarts. Retention exactly equal to the configured size or time (blocks are deleted whole).