The SRE track taught you to scrape targets and write PromQL. This lesson goes under the hood of prometheus/prometheus: how service discovery and relabeling decide what gets scraped, how the TSDB turns samples into blocks on disk, why cardinality is the number that kills Prometheus servers, and how recording rules, remote write, agent mode and native histograms fit into a setup that monitors AI systems as well as web services.
- Trace a sample from service discovery through relabeling, scrape and the TSDB
- Size disk and memory for a Prometheus server and spot cardinality problems
- Write recording and alerting rules and test them with promtool
- Choose between local storage, remote write and agent mode
- Configure native histograms and explain why they help latency SLOs
Inside the repository: the path of a sample
Prometheus is one Go binary, and its top-level folders read like a pipeline. discovery/ finds targets (Kubernetes, EC2, Consul, file and HTTP service discovery and many more). scrape/ pulls metrics from them on an interval. tsdb/ stores the samples. promql/ evaluates queries. rules/ runs recording and alerting rules on a schedule, and notifier/ sends firing alerts to Alertmanager, which is a separate project. web/ serves the UI and HTTP API, and storage/remote/ implements remote write and read.
Between discovery and scrape sits relabeling, the most powerful and most misunderstood part of the configuration. Service discovery attaches metadata labels that start with __meta_, such as a pod's annotations. relabel_configs rewrite those labels before the scrape, to keep or drop targets and to build the final job, instance and other labels. Labels that still start with __ are discarded afterwards. metric_relabel_configs run after the scrape, on every sample, and are your last chance to drop an expensive series before it is stored.
scrape_configs:
- job_name: kubernetes-pods
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: "true"
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
metric_relabel_configs:
- source_labels: [__name__]
regex: "go_gc_.*"
action: dropThe TSDB: head, WAL, blocks and compaction
New samples land in the head block, which lives in memory and covers the most recent two hours or so. To survive a crash, every write is also appended to the write-ahead log (wal/, 128 MB segment files), which is replayed on restart; this is why a large Prometheus can take minutes to start. Roughly every two hours the head is cut into an immutable block on disk: a directory with chunks/, an index that maps labels to series, a meta.json and tombstones for deletions. Background compaction merges small blocks into larger ones, up to 10% of the retention time or 31 days, whichever is smaller.
- Disk: samples compress to about 1 to 2 bytes each, so disk is roughly retention seconds times samples ingested per second times 2 bytes. Keep size-based retention at 80 to 85% of the volume, because compaction briefly needs room for old and new blocks together.
- Memory: dominated by the number of active series in the head, not by how many samples you store. A series is one unique combination of metric name and label values.
- Storage: use a local disk. NFS, including network file systems such as EFS, is not supported and can corrupt the database.
- Backups: take a snapshot through the admin API rather than copying a live data directory.
Cardinality is the classic outage. One label holding a user ID, request ID or full URL path turns one metric into millions of series, memory explodes, and the server is killed. Check prometheus_tsdb_head_series and run promtool tsdb analyze to find the worst offenders.
Retention is set in the configuration file now: storage.tsdb.retention.time and .size in prometheus.yml. The old command-line flags still work but are deprecated. With no setting, time-based retention defaults to 15 days.
Rules: pre-compute, then alert
Recording rules evaluate an expensive query on a schedule and store the result as a new series, so dashboards and alerts read one cheap series instead of re-aggregating thousands. The naming convention is level:metric:operations. Alerting rules evaluate a condition; when it stays true for the for duration, the alert fires and is sent to Alertmanager, which groups, silences and routes it.
groups:
- name: inference
interval: 30s
rules:
- record: model:request_errors:ratio_rate5m
expr: |
sum by (model) (rate(inference_requests_total{status="error"}[5m]))
/
sum by (model) (rate(inference_requests_total[5m]))
- alert: InferenceErrorRatioHigh
expr: model:request_errors:ratio_rate5m > 0.05
for: 10m
labels:
severity: page
annotations:
summary: "{{ $labels.model }} error ratio above 5% for 10 minutes"Treat rules like code: promtool check rules validates syntax, and promtool test rules runs unit tests that feed synthetic series into your rules and assert which alerts fire and when. Put both in CI next to the rule files.
Beyond one server: remote write, agent mode, OTLP
Local storage is a single-node database: not clustered, not replicated. For long retention, a global view across clusters, or high availability, Prometheus remote writes samples to a system built for that, such as Thanos, Cortex, Mimir or a managed service. Remote write streams from the WAL, so a short outage of the receiver does not lose data while the WAL still holds it.
- Agent mode (
--agent) keeps service discovery, relabeling and scraping, but disables local querying, rules and alerting and uses a slim WAL. Run it in each cluster as a collector that only forwards. - Receiving:
--web.enable-remote-write-receiverlets another Prometheus or agent push to this one, and--web.enable-otlp-receiveraccepts OTLP metrics directly from OpenTelemetry SDKs or Collectors. - Federation (
/federate) still exists for pulling a few aggregated series upward, but remote write is the usual answer for scale.
Native histograms for latency
A classic histogram stores one series per bucket boundary you chose in advance, plus _sum and _count. Pick the wrong buckets and your p99 is a guess; add more buckets and cardinality grows. A native histogram stores the whole distribution as one series with exponential buckets chosen automatically, at much higher resolution for less cost, and you can aggregate them across instances correctly.
scrape_configs:
- job_name: llm-gateway
scrape_native_histograms: true
static_configs:
- targets: ["gateway.ai.svc:9090"]Query them with the same functions: histogram_quantile(0.99, sum(rate(request_duration_seconds[5m]))), without a _bucket suffix or le label. For LLM serving, where time to first token and time per output token span orders of magnitude, this resolution is what makes a latency SLO trustworthy.