Prometheus: scrape, TSDB, PromQL, and production pitfalls
Updated November 1, 2026
Prometheus is a monitoring server: it polls applications over HTTP, collects numeric metrics, and stores them in a built-in database for about 15 days. You build Grafana graphs and Alertmanager alerts on top. It is the de facto standard in Kubernetes.
Why Prometheus
Before Prometheus, monitoring was push-based: an agent on the host sent metrics to Graphite/Nagios. The problems:
- The agent has to know the server address, and the firewall is open inbound
- If the server goes down, the agent either buffers locally or loses data
- Configuration is duplicated on every host
- Service discovery is a separate headache
Prometheus (2012, SoundCloud, then CNCF) flipped the model: the server itself scrapes (HTTP GET) the targets. Advantages:
- One central config
- Built-in service discovery (k8s, Consul, EC2, file)
- Down detection for free (
up == 0) - You can still pull from an intranet through a push gateway when needed
Today Prometheus plus Grafana is the de facto metrics standard in Kubernetes and cloud-native.
Architecture
┌─────────────┐ scrape (HTTP /metrics)
│ Prometheus │ ◄─────────────┬──────────┐
│ server │ │ │
│ ┌─────────┐ │ ┌──┴──┐ ┌───┴───┐
│ │ TSDB │ │ │ app │ │ node- │
│ │ (15d) │ │ │ /m │ │ exp │
│ └─────────┘ │ └─────┘ └───────┘
│ ┌─────────┐ │
│ │ rules │ ──► alerts ──► Alertmanager ──► PagerDuty/Slack
│ │ engine │ │
│ └─────────┘ │
│ │
│ remote_write│ ──► VictoriaMetrics / Thanos / Mimir (long-term)
└─────────────┘
▲
│ PromQL HTTP
┌─────┴────┐
│ Grafana │ + ad-hoc queries
└──────────┘Key components:
- scrape engine: pulls
/metricsevery 15 to 60s - TSDB: a local time-series DB, blocks of 2 hours
- rules engine: evaluates recording and alerting rules every 15s
- HTTP API:
/api/v1/query,/query_range, for Grafana andpromtool
Pull model: scrape
Each target exports /metrics in a text format (OpenMetrics):
# HELP http_requests_total Number of requests
# TYPE http_requests_total counter
http_requests_total{method="GET",status="200"} 12345
http_requests_total{method="POST",status="500"} 12Scrape config:
scrape_configs:
- job_name: my-app
scrape_interval: 15s
scrape_timeout: 10s
metrics_path: /metrics
static_configs:
- targets: ['app1:8080', 'app2:8080']In practice it is not static but goes through service discovery (k8s endpoints, Consul, file_sd).
TSDB: how data is stored
Time-series identifier: metric_name{label1=val1,label2=val2}. Each unique combination is a separate series.
On disk:
/var/lib/prometheus/
├── 01HABC.../ # 2-hour block
│ ├── chunks/
│ ├── index # postings: label → series IDs
│ ├── tombstones
│ └── meta.json
├── 01HABD.../
└── wal/ # write-ahead log (current 2h window)Compaction: 2h blocks → 16h → 5d → 14d, like an LSM-tree. After retention (default 15d), they are deleted.
Memory is about 3 KB per active series plus the WAL. 1M series is about 3-4 GB of RAM.
PromQL, the query language
Four kinds of queries:
Instant query: a value at a point in time:
up # all 'up' gauges right now
rate(http_requests_total[5m]) # rate over the last 5 minutesRange query: a series over a period (for graphs):
GET /api/v1/query_range?query=up&start=...&end=...&step=15sAggregation with sum, avg, max, min, count, topk:
sum by (job)(up) # how many are up per job
topk(5, rate(http_requests_total[5m])) # top 5 by rate
histogram_quantile(0.99, sum by (le)(rate(req_duration_bucket[5m])))Functions:
rate(counter[5m]): per-second rate, handles resetirate(counter[1m]): instant rate, for volatile seriesincrease(counter[1h]): total over an hour (=rate * window)delta(gauge[1h]): the changepredict_linear(gauge[1h], 4*3600): forecast 4h ahead (for disk-full)
PromQL is vector-based: operations work on labels:
rate(http_requests_total{status="500"}[5m])
/
rate(http_requests_total[5m])
> 0.05 # error rate >5%Recording rules: pre-compute
Expensive queries (especially with histogram_quantile and multi-joins) get cached as recording rules. Prometheus evaluates them every 15s and writes them as ordinary series:
groups:
- name: app_slo
interval: 30s
rules:
- record: app:http_request_rate:5m
expr: sum by (job, status)(rate(http_requests_total[5m]))
- record: app:http_request_duration:p99:5m
expr: histogram_quantile(0.99,
sum by (job, le)(rate(http_request_duration_bucket[5m])))Convention: aggregation_level:metric:window. Used in dashboards and alerting.
Alerting rules
groups:
- name: app
rules:
- alert: HighErrorRate
expr: app:http_error_rate:5m > 0.05
for: 5m # must hold for 5 minutes
labels:
severity: critical
annotations:
summary: "Error rate {{ $value | humanizePercentage }}"
runbook: "https://wiki/runbooks/high-error-rate"If expr returns a non-empty vector for the whole for: 5m, the alert fires in Alertmanager. See alerting-rules-alertmanager.
Retention and remote_write
The local TSDB is short-term storage (default 15d, max about 2 months). For the long term, remote_write to systems built for scale:
| Backend | Storage | Tenancy | Compat |
|---|---|---|---|
| Thanos | object (S3/GCS) | per-tenant | PromQL |
| Cortex / Mimir | object | multi-tenant | PromQL |
| VictoriaMetrics | own LSM | YES (cluster) | PromQL+MetricsQL |
| M3DB | own | multi-tenant | PromQL |
| InfluxDB v3 | own | yes | InfluxQL/Flux |
remote_write:
- url: https://victoria-metrics:8480/api/v1/write
queue_config:
max_samples_per_send: 5000
capacity: 50000Production setup: Prometheus as the scraper and short-term store, a VictoriaMetrics cluster for 1+ year retention and querying.
Federation: a Prometheus hierarchy
A regional Prom scrapes local services. A global Prom scrapes the aggregates from the regional ones through /federate:
scrape_configs:
- job_name: federate
honor_labels: true
metrics_path: /federate
params:
match[]:
- '{__name__=~"job:.*"}' # recording rules only
static_configs:
- targets: ['region-prom-eu:9090', 'region-prom-us:9090']Do not federate raw metrics, only aggregates. Otherwise cardinality multiplies.
When things go wrong
- Prometheus OOM: usually cardinality.
topk(20, count by (__name__)({}))shows the top metrics by series count. See cardinality-explosion. up == 0for a target: the scrape failed. Check the/targetsUI: timeout, DNS, 401, TLS. The Prom logs are more precise.rate()returns NaN: the counter reset between samples (a restart), or there are no samples in the window. Widen the window or check the scrape.- Prom and Grafana disagree: the
stepin the range query. A smaller step means more points and a heavier query. - WAL replay is slow after a restart: 2-3 minutes per 1M series. Fix:
--storage.tsdb.wal-segment-size=128MBor a Thanos sidecar. - High 5xx rate on
/api/v1/query: long queries time out. Use recording rules or raise--query.timeout. out of boundserrors in the logs: clock skew between Prom and the target, or the target returns a sample from the future. Fix NTP (chrony-and-ntp).- Metrics drop to 0 every N minutes: scrape duration exceeds the scrape interval, and the target cannot keep up. Trim the metrics or raise the interval.
Alternatives
| Tool | When to choose |
|---|---|
| Prometheus | the default for k8s, < 10M active series |
| VictoriaMetrics | 10x lighter RAM, clustered, drop-in PromQL |
| Thanos | you want S3 storage without a separate DB stack |
| Mimir | Grafana Labs, multi-tenant, SaaS-like |
| InfluxDB | tagged events, tracing-like queries |
| Datadog | hosted, you do not want to run a Prom stack |
Commands
promtool query instant 'up == 0': Find every scrape target that is currently downpromtool tsdb analyze /var/lib/prometheus/: TSDB analysis: top metrics by cardinality, block sizes, WAL statecurl -X POST localhost:9090/-/reload: Reload configs and rules without a restart (needs --web.enable-lifecycle)curl -s 'localhost:9090/api/v1/query?query=count by (__name__)({}) > 1000': Metrics with >1000 series: the first candidates for cardinality cleanuppromtool check rules /etc/prometheus/rules/*.yml: Validate recording and alerting rules before reload (CI-friendly)promtool query range --start=1h --end=now --step=15s 'rate(http_requests_total[5m])': A one-hour range query with a 15s step, the same thing Grafana fetchescurl -s localhost:9090/api/v1/status/tsdb | jq '.data.headStats': Stats on the in-memory head: active series, chunks, samples, a quick cardinality check