Skip to Content

Kubernetes Field Guide · Chapter 14 of 16

Observability: Prometheus, Grafana and alerts

A deploy is only done when you can see it working. Learn what to measure, how Prometheus collects it, how to query it, and how to alert so that a page means a real problem, without letting the monitoring bill outgrow the thing it monitors.

  • 40 min
  • Advanced
  • Hands-on
  • Free

By , founding engineer running Kubernetes in production. Updated .

podpodpod/metricsPrometheusscrapes every 30sGrafanadashboardsAlertmanagerp95 > 500ms, 5mon-callyou
The chapter in one pictureMetrics flow from pods to Prometheus, then to dashboards for humans and alerts for on-call.

By the end you can

0 of 5

Metrics, logs and traces

SignalAnswersTypical tools
MetricsIs something wrong, and how much? Cheap numbers over time.Prometheus, CloudWatch metrics
LogsWhat exactly happened in this request or this crash?Loki, CloudWatch Logs, Elasticsearch
TracesWhere did the time go across services?OpenTelemetry with Tempo or Jaeger

For every user-facing service, start with the four golden signals: latency (how long requests take, as p95 or p99, not averages), traffic (requests per second), errors (the share that fail) and saturation (how full the most constrained resource is).

Prometheus and PromQL

Prometheus pulls metrics: every 15–30 seconds it scrapes an HTTP /metrics endpoint on each target and stores the numbers as time series. In Kubernetes it gets three kinds of data:

  • Your apps, which expose metrics through a client library, discovered with a ServiceMonitor.
  • kube-state-metrics: the state of objects (desired vs available replicas, restarts, pod phases).
  • The kubelet and node-exporter: container and node CPU, memory, disk and network.
QuestionPromQL
Requests per secondsum(rate(http_requests_total[5m]))
Error ratiosum(rate(http_requests_total{code=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))
p95 latencyhistogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))
CPU used vs requested, per podsum by (pod) (rate(container_cpu_usage_seconds_total[5m]))
Pods restartingincrease(kube_pod_container_status_restarts_total[15m]) > 3

Dashboards

Grafana turns queries into dashboards. Make one per service with the golden signals at the top, then saturation and dependencies below. A good dashboard answers "is it us, and since when?" in ten seconds. Mark deploys on it, because the most common cause of an incident is the last change.

Alerts that matter

Every page should be real, urgent and actionable. If people learn that alerts are usually noise, they stop reading them, and then miss the real one. Tune this alert until it pages once:

Interactive

Tune an alert: p95 latency, last 60 minutes

Two short blips around minutes 8 and 33, and one real incident from minute 44.

As a Prometheus rule, with the for duration that filtered the blips:

prometheusrule.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: shop-api
  labels:
    release: kps
spec:
  groups:
    - name: shop-api
      rules:
        - alert: ShopApiHighLatency
          expr: |
            histogram_quantile(0.95,
              sum by (le) (rate(http_request_duration_seconds_bucket{service="shop-api"}[5m]))
            ) > 0.5
          for: 5m
          labels:
            severity: page
          annotations:
            summary: "shop-api p95 latency above 500ms for 5 minutes"
            runbook: "https://wiki.example.com/runbooks/shop-api-latency"
The kube-prometheus-stack only loads rules carrying its release label by default.
Must stay true for 5 minutes before it fires.
Alertmanager routes by labels: page someone, or post to a channel.
Every paging alert links to what to do.

Step through it

From a slow request to a message in Slack

  1. App/metrics
  2. Prometheusscrape + rules
  3. Alertmanagerroute, group
  4. Slack#alerts
  5. On callyou

Step 0 of 6

Press Play, or step through with Next.

The cost of observability

Monitoring can quietly become one of the largest lines on a cloud bill. The usual causes:

  • Cardinality. Every distinct set of label values is a separate time series. A label with user IDs, request IDs or full URLs creates millions. Keep labels bounded; put per-request detail in logs or traces.
  • Log volume. Managed log services bill per GB ingested and stored. Debug logging left on in production, and logging every health check, cost real money. Set retention per log group instead of keeping everything forever.
  • Retention. Keep high-resolution metrics for days or weeks; downsample or drop after that.
  • Traces. Sample: keep every error and slow trace, and a small percentage of the rest.

Cardinality is the one that surprises people, because it multiplies. Add labels to one ordinary metric:

Interactive · Cost

One metric, http_requests_total. How many series?

The worst case: every combination seen at least once. Real counts are lower, but they grow the same way. Each active series costs memory in Prometheus, and hosted services such as Grafana Cloud or Datadog bill per active series.

Hands-on: install the stack

Live lab · no install

Install the monitoring stack

kind-learn
  1. Tasks0/7
  2. Start with what kubectl already shows

    Usage per pod, before any dashboards.

    kubectl top pods
    kubectl top nodes
  3. Read logs from every replica at once
    kubectl logs -l app=web --prefix --tail=3
  4. Install the monitoring stack

    Prometheus, Alertmanager, Grafana, kube-state-metrics and node-exporter in one chart.

    helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
    helm install kps prometheus-community/kube-prometheus-stack -n monitoring --create-namespace --wait
    kubectl -n monitoring get pods
  5. Get the Grafana password
    kubectl -n monitoring get secret kps-grafana -o jsonpath="{.data.admin-password}" | base64 -d
  6. Open Grafana and Prometheus

    On your laptop these open in a browser at localhost:3000 and localhost:9090.

    kubectl -n monitoring port-forward svc/kps-grafana 3000:80 &
    kubectl -n monitoring port-forward svc/prometheus-operated 9090 &
  7. Break something and find it from events

    Events are the first signal, before any metric moves.

    kubectl set image deployment/web nginx=nginx:1.27-typo
    sleep 5
    kubectl get events --field-selector type=Warning | tail -n 5
  8. Recover
    kubectl rollout undo deployment/web
    kubectl rollout status deployment/web
  9. Lab complete. Keep experimenting, or press Reset to start again.
↑↓ history · Tab complete · Ctrl+C stop
Cluster map live
  • ready
  • starting / not ready
  • failing
  • terminating
Prefer your own machine? The same steps on a local cluster

The kube-prometheus-stack chart installs Prometheus, Alertmanager, Grafana, kube-state-metrics, node-exporter and a set of ready-made dashboards and alerts. Back on the kind cluster:

Terminal
kubectl config use-context kind-learn
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install kps prometheus-community/kube-prometheus-stack -n monitoring --create-namespace --wait
kubectl -n monitoring get pods
kps
Short release name. Resource names start with it, such as kps-grafana.
--wait
Takes a few minutes the first time while images download.
Terminal
kubectl -n monitoring get secret kps-grafana -o jsonpath="{.data.admin-password}" | base64 -d; echo
kubectl -n monitoring port-forward svc/kps-grafana 3000:80 &
kubectl -n monitoring port-forward svc/prometheus-operated 9090 &
admin-password
Log in to Grafana at http://localhost:3000 as admin with this password.
prometheus-operated
Prometheus UI at http://localhost:9090. Try the queries from the table above.

In Grafana, open Dashboards → Kubernetes / Compute Resources / Namespace (Pods) and pick default: CPU and memory per pod, against requests and limits.

Mini mission

Find your waste

In Prometheus, write one query that shows, for each pod in default, its CPU usage divided by its CPU request. Which pods would you right-size, and in which direction?

Reveal one safe solution
PromQL
sum by (pod) (rate(container_cpu_usage_seconds_total{namespace="default", container!=""}[5m]))
/
sum by (pod) (kube_pod_container_resource_requests{namespace="default", resource="cpu"})

Values far below 1 are over-requested: lower their requests and fit more on each node (chapter 9). Values above 1 are using more than they reserved and are first in line when the node gets busy: raise their requests. Look at a week of data before changing production numbers, not five minutes.

Check yourself

Quiz

0 of 4 answered

  1. 1. Which is the best first signal to alert on?
  2. 2. What does for: 5m on an alert rule do?
  3. 3. Why is adding a user_id label to a request metric a bad idea?
  4. 4. Which PromQL gives requests per second over the last 5 minutes from a counter?

Further reading