Metrics and monitoring

Intermediate · 25 min

The two metrics pipelines in a cluster: metrics-server for autoscaling and kubectl top, and Prometheus scraping components, kube-state-metrics and your apps.

Before thisThe Horizontal Pod AutoscalerThe control plane

That DevOps Guy · 25 min

Metrics and monitoring

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by That DevOps GuyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Kubernetes has two metrics pipelines. The resource metrics API (metrics.k8s.io, usually metrics-server) holds only current CPU and memory for kubectl top and autoscalers. A monitoring system such as Prometheus keeps history for everything else.
  • Every component (API server, scheduler, controller manager, kubelet, etcd) serves Prometheus metrics at /metrics. Stable metrics like apiserver_request_total and apiserver_request_duration_seconds are the API server's golden signals.
  • kubelet's cAdvisor endpoint gives container usage, kube-state-metrics turns object state (replicas wanted versus available, Pod phases, restarts) into metrics, and node-exporter covers the machine.
  • The Prometheus Operator makes scraping declarative: ServiceMonitor and PodMonitor objects select what to scrape, and PrometheusRule holds alerts, all reconciled into Prometheus config.
  • Alert on symptoms users feel (error rate, latency, saturation) and on things that will become outages (crash loops, Pods stuck Pending, nodes NotReady, certificates expiring), not on every metric.
  • Watch cardinality. Every distinct label combination is a separate time series, and labels like user IDs or full URLs can take Prometheus down.

You can’t fix what you can’t see

The previous lessons found problems after someone noticed them. Monitoring is how you notice first: the error rate climbs at 03:00 and a page goes out, a node’s disk fills slowly over a week and a ticket appears, the API server gets slower after a new controller is deployed and the graph shows exactly when. Kubernetes gives you a lot of raw material for this. It also has two separate metrics systems, and confusing them is the usual first mistake.

Pipeline one: resource metrics

The resource metrics API, metrics.k8s.io, holds one thing: the current CPU and memory use of each node and Pod. metrics-server fills it by scraping each kubelet’s resource metrics endpoint (every 15 seconds in its default deployment) and registering with the API server through the aggregation layer. Its consumers are kubectl top, the HPA and the VPA. It keeps no history, and it isn’t meant for dashboards.

Without it, the lab API server answered kubectl top nodes honestly:

Error from server (NotFound): the server could not find the requested resource (get nodes.metrics.k8s.io)

That is the same kind of error the HPA reported in its lesson, before I registered a small stand-in for metrics-server. It’s also the first thing to check when an HPA says <unknown>.

Pipeline two: everything else

For history, alerts and dashboards, clusters run a full monitoring system, most often Prometheus, which scrapes HTTP endpoints in its text format and stores time series. The sources:

  • Control-plane components serve /metrics. The lab API server’s endpoint returned 32,499 lines and 301 metric families.
  • Kubelet serves its own metrics plus /metrics/cadvisor, per-container CPU, memory, network and filesystem usage, and /metrics/probes with probe results.
  • kube-state-metrics watches the API and turns object state into metrics, such as kube_deployment_spec_replicas against kube_deployment_status_replicas_available, kube_pod_status_phase and kube_pod_container_status_restarts_total. Usage tells you how busy things are. State tells you whether they’re what you asked for.
  • node-exporter for the machine: disks, filesystems, network, load.
  • Your applications, instrumented with a Prometheus or OpenTelemetry client.

Reading the API server’s own metrics

A few lines from the lab API server’s /metrics:

apiserver_request_total{code="200",...,resource="pods",scope="resource",verb="GET",version="v1"} 73
apiserver_request_total{code="200",...,resource="pods",scope="resource",verb="DELETE",version="v1"} 39
apiserver_request_total{code="403",...,resource="pods",scope="resource",verb="POST",version="v1"} 35
apiserver_request_total{code="200",...,resource="pods",scope="cluster",verb="LIST",version="v1"} 33
# HELP apiserver_request_duration_seconds [STABLE] Response latency distribution in seconds for each verb, dry run value, group, version, resource, subresource, scope and component.
# TYPE apiserver_request_duration_seconds histogram
apiserver_resource_objects{group="",resource="events"} 298

The 35 403s on Pod creation were quota and Pod Security rejections from earlier experiments on the lab, visible as a rate without reading a single log line. apiserver_request_total by code gives an error rate per resource and verb. apiserver_request_duration_seconds is a histogram for latency percentiles. apiserver_resource_objects counts stored objects per type, an early warning for runaway controllers creating thousands of Events or Secrets.

Note the [STABLE] marker. Kubernetes metrics carry a stability class. Of the 301 families here, 9 were STABLE and 116 ALPHA. Stable metrics keep their names and labels across releases. Alpha ones can change or disappear in any release, so dashboards and alerts built on them break during upgrades.

The Prometheus Operator

Running Prometheus on Kubernetes is usually done with the Prometheus Operator, often through the kube-prometheus-stack Helm chart, which bundles Prometheus, Alertmanager, Grafana, kube-state-metrics, node-exporter and a set of standard dashboards and alerts. The operator adds CRDs, so monitoring config lives next to the app:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: checkout
  namespace: shop
  labels: {release: kube-prometheus-stack}
spec:
  selector:
    matchLabels: {app: checkout}
  endpoints:
  - port: http-metrics
    interval: 30s
---
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: checkout
  namespace: shop
  labels: {release: kube-prometheus-stack}
spec:
  groups:
  - name: checkout
    rules:
    - alert: CheckoutHighErrorRate
      expr: |
        sum(rate(http_requests_total{job="checkout",code=~"5.."}[5m]))
          / sum(rate(http_requests_total{job="checkout"}[5m])) > 0.02
      for: 10m
      labels: {severity: page}

A ServiceMonitor selects Services by label and names the port to scrape. The operator turns every matching one into Prometheus scrape config. The release label matters: Prometheus only picks up monitors matching its own selector, which is the commonest “why isn’t my target showing up” cause. These examples follow the operator’s docs and weren’t run here.

What to alert on

  • User-facing symptoms: error ratio and latency per service, which is what the rule above does.
  • Saturation before failure: node disk and memory pressure, PVCs filling, CPU throttling, API server latency.
  • Kubernetes state that means trouble: Pods in CrashLoopBackOff, Pods Pending for more than a few minutes, Deployments below desired replicas, nodes NotReady, Jobs failing, certificates near expiry.

Alerts on plain CPU percentages mostly create noise. A busy node isn’t a problem until something suffers.

Cardinality

Every unique combination of a metric’s labels is a separate time series that Prometheus holds in memory. Labels with bounded values (status code, route template, namespace) are cheap. Labels with unbounded values (user ID, full URL, Pod IP in long-lived metrics) multiply series until Prometheus runs out of memory. Review new labels like you review database indexes. For long-term storage across clusters, Prometheus-compatible systems such as Thanos, Mimir or a managed service take over.

About the video

The embed is That DevOps Guy’s “Prometheus Operator in Kubernetes Explained”, June 2025, 25 minutes. Its chapters cover the problem, what the Prometheus Operator is, kube-prometheus, configuration options, installation, the operator and ServiceMonitors, Grafana, deploying microservices with a custom Prometheus, and testing in Grafana. It covers the second pipeline and says little about metrics-server. I judged it from chapters and description only, since transcripts couldn’t be fetched. English was judged from its “English (US) original” audio track. KodeKloud’s short video in deeper sketches a full pipeline with long-term storage.

What was run: the kubectl top error and the API server’s /metrics output, with its line, family and stability-class counts, are real, from a local Kubernetes v1.37.3 API server whose nodes run no containers. No Prometheus, metrics-server, kube-state-metrics or exporter ran. Their behaviour and the ServiceMonitor and PrometheusRule examples are from the Kubernetes metrics docs and the Prometheus Operator docs, checked 2026-11-29.

Where this fits

Metrics say something is wrong. Logs say what. Next: logging architecture.

Check yourself

  1. 01kubectl top pods works but there's no graph of last week's CPU. Why?

    kubectl top reads the resource metrics API, which metrics-server fills with only the latest sample from each kubelet. It keeps no history. Graphs need a monitoring system such as Prometheus that scrapes and stores time series.

  2. 02Which metric tells you a Deployment is running fewer replicas than it should, and where does it come from?

    kube-state-metrics' kube_deployment_status_replicas_available compared with kube_deployment_spec_replicas. kube-state-metrics watches the API and exposes object state as metrics. Usage metrics from cAdvisor can't tell you that.

  3. 03Your API server's p99 latency for LIST pods jumped. Which metric shows it, and what might explain it?

    apiserver_request_duration_seconds, a histogram labelled by verb and resource. A sudden rise for LIST often means a client listing large collections without pagination or a resource selector, or etcd itself slowing down (check etcd_request_duration_seconds).

  4. 04Why is adding a request_path label with the full URL to your app's metrics dangerous?

    Each distinct value creates a new time series. URLs with IDs make the series count grow without bound, which inflates Prometheus memory and storage until it falls over. Use route templates, not raw paths.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark