Education › OSS Deep Dives › Stage 3: Observability for AI systems

Prometheus internals

Scraping, service discovery, the TSDB and its head block, recording and alerting rules, remote write and native histograms.

Intermediate ~35 min read Module 5 of 10

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.

After this module you can
  • 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.

targetspullappendlogcutreadfirestreamDiscovery__meta_* labelsrelabel_configskeep, set labelsScrape loop+ metric relabelHead blockmemory, ~2hWALcrash safetyBlocks2h, compactedRules, PromQLquery, alertAlertmanagerRemote writelong-term store
A sample's path through Prometheus: discovery and relabeling choose the targets, the scrape loop pulls, and the TSDB writes to the WAL and the in-memory head before cutting two-hour blocks to disk.
Scrape only pods that opt in, and label them by namespace and pod
yaml
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: drop

The 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.
Watch out

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.

Record per-model error ratio, then alert on it
yaml
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-receiver lets another Prometheus or agent push to this one, and --web.enable-otlp-receiver accepts 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.

Opt a job into native histograms
yaml
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.

Hands-on practice

Watch the TSDB work and break it on purpose

  1. Run Prometheus in Docker with a volume for /prometheus and a config that scrapes itself every 5 seconds.
  2. Open the UI and query prometheus_tsdb_head_series; note the number.
  3. Run a small exporter (any language) that emits a counter with a label set to a random ID on every request, hit it a few thousand times, and watch head series and memory climb.
  4. Add a metric_relabel_configs rule with action: labeldrop for that label, reload with curl -X POST localhost:9090/-/reload (start with --web.enable-lifecycle), and confirm growth stops.
  5. Write the recording and alerting rules from this lesson for a metric you have, then write a promtool test rules file that proves the alert fires after 10 minutes.
  6. Leave it running for a few hours, then look inside the data volume and find the WAL, chunks_head and your first block directory.
Cheat sheet

Prometheus internals — at a glance

Main things to focus on

  • Discovery adds __meta_* labels; relabel_configs pick targets and labels; metric_relabel_configs filter samples.
  • Memory scales with active series; disk scales with samples per second times retention.
  • Head block plus WAL in memory, two-hour blocks on disk, background compaction.
  • Never put unbounded values (IDs, raw paths, emails) in labels.
  • Recording rules make dashboards and alerts cheap; test rules with promtool.
  • Local TSDB is single-node: use remote write for long-term, global or HA storage.

promtool

promtool check config prometheus.ymlValidate the main config and referenced rule files
promtool check rules rules.ymlValidate rule syntax
promtool test rules tests.ymlUnit-test recording and alerting rules
promtool tsdb analyze /prometheusFind the highest-cardinality metrics and labels
promtool query instant http://localhost:9090 'up'Run a query from the shell

Server flags and config

storage: {tsdb: {retention: {time: 30d}}}Retention in prometheus.yml (flags deprecated); default 15d
--web.enable-lifecycleAllow POST /-/reload and /-/quit
--agentScrape and remote write only: no queries, rules or local TSDB
--web.enable-remote-write-receiverAccept remote write pushes
--web.enable-otlp-receiverAccept OTLP metrics

Relabel actions

action: keep / dropKeep or drop targets (or samples) whose labels match regex
action: replace target_label: XWrite a value built from source_labels into X
action: labeldrop regex: XRemove labels matching regex
action: hashmod modulus: NShard targets across N Prometheus servers

Health queries

prometheus_tsdb_head_seriesActive series in memory
rate(prometheus_tsdb_head_samples_appended_total[5m])Ingestion rate, for disk sizing
topk(10, count by (__name__) ({__name__=~".+"}))Metrics with the most series (expensive: run rarely)
up == 0Targets that failed their last scrape

Common pitfalls

  • Labels with unbounded values such as user IDs or full URLs, which explode cardinality.
  • Putting the data directory on NFS or EFS, which is unsupported and corrupts blocks.
  • Setting size retention equal to the disk size, then running out of space during compaction.
  • Dashboards that aggregate raw high-cardinality metrics on every refresh instead of reading recording rules.
  • Treating one Prometheus as durable long-term storage with no remote write or snapshots.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →