Observability: metrics pipelines, kube-state-metrics, events, logging, and the alerts that matter

Alert on user-visible symptoms with an owner and a runbook; route causes to tickets. Cardinality is the metric system's own outage risk.

Read the briefing
About 3 min to read 7 drills

What to remember

  1. Page on symptoms, ticket on causes. Disk at 80% is a ticket. Checkout failing is a page.
  2. One unbounded label takes Prometheus down. User ids, request ids, raw paths. Cardinality is memory.
  3. kube-state-metrics is object state; cAdvisor is usage. Two different sources, and you need both to answer most questions.
  4. Fleet averages hide one bad replica. Per-pod views plus percentiles, or the incident is invisible on the dashboard.
  5. Delete alerts nobody acts on. Every ignored page erodes trust in all of them.

The big picture

Observability on Kubernetes is a stack of sources that answer different questions: metrics-server answers "what is this pod using right now" for HPA and kubectl top; Prometheus answers "how has it behaved over time" from kubelet, cAdvisor, kube-state-metrics and application endpoints; events answer "what did the control plane just do"; logs answer "what did the application say". Alerts that page should be about symptoms users feel, not about every component that could be unhappy.

The mental model

Four lenses on one system. Metrics: numeric, cheap, aggregatable, the basis for SLOs and alerts. Events: the API server's short-lived audit of decisions (scheduled, pulled, killed), gone in an hour unless exported. Logs: what the application wrote to stdout, collected per node. Traces: the path of one request across services. The skill interviewers test is choosing the right lens for the question and knowing what each cannot tell you.

In depth

metrics-server versus Prometheus

metrics-server scrapes the kubelet's resource metrics every 15 s and serves the metrics.k8s.io API for kubectl top and the HPA. It keeps no history: it is a live gauge, not a database. Prometheus scrapes /metrics endpoints on a schedule and stores time series: the kubelet's cAdvisor endpoint (container_cpu_usage_seconds_total, container_memory_working_set_bytes, throttling counters), the kubelet's own metrics (volume stats, pod start latency), kube-state-metrics (the state of API objects as metrics: kube_pod_status_phase, kube_deployment_status_replicas_unavailable, restart counts), node-exporter, and your application. HPA on custom metrics needs an adapter that exposes Prometheus queries through the custom metrics API. When someone says "Kubernetes metrics", ask which of these they mean.

Events and logs: what they are and how they disappear

Events are namespaced objects the control plane and kubelet emit: Scheduled, Pulling, Started, BackOff, FailedScheduling, Unhealthy, OOMKilling. They are retained for about an hour by default (--event-ttl) and are not metrics. During an incident kubectl get events --sort-by=.lastTimestamp is the control plane's narrative; for anything longer, export events to your logging system with an event exporter (kubernetes-event-exporter or similar; kube-state-metrics does not export events). Logs are whatever the container writes to stdout/stderr; the container runtime writes them to files on the node, kubectl logs reads those files (with --previous for the last crashed instance), and a node-level agent (Fluent Bit, Vector, Promtail) ships them. Logs from a pod that was deleted are gone from the node; that is why shipping is not optional and why log volume and cardinality (do not put request ids in labels) are cost problems.

Alerts that are worth a page

Page on symptoms: SLO burn rate, error rate, latency, saturation that predicts failure (PVC at 85%, node memory pressure), Pending pods older than a few minutes, Deployments below desired for longer than a rollout, CrashLoopBackOff on production workloads, certificate expiry within days. Ticket on causes: a single restart, a node NotReady for two minutes, one failed probe. Every alert needs a runbook link and an owner; every alert that fires without action for a month is deleted. Kubernetes-specific gotchas: kube_pod_container_status_restarts_total is a counter, use increase(); container_memory_working_set_bytes is what the OOM killer looks at, not RSS; CPU throttling ratio (container_cpu_cfs_throttled_periods_total / container_cpu_cfs_periods_total) predicts latency spikes that CPU utilization hides.

Myths and facts

Myth: kubectl top shows the same data Prometheus stores.

Fact: kubectl top reads metrics-server, a live gauge with no history; Prometheus stores scraped series over time.

Myth: Events are kept forever.

Fact: Default TTL is about one hour; export them if you need history.

Myth: Restart counts are gauges I can alert on directly.

Fact: They are counters; alert on increase() over a window, otherwise you page forever on an old restart.

Myth: Memory RSS is what the OOM killer uses.

Fact: For cgroup limits the kernel looks at the working set (including active page cache); container_memory_working_set_bytes is the metric to watch.

Myth: Alert on every failed liveness probe.

Fact: A single failed probe is noise; alert on restart loops and on user-facing symptoms.

How pros do it

  • Run metrics-server for HPA and kubectl top; run Prometheus (or a managed equivalent) with kube-state-metrics and node-exporter for everything with history.
  • Ship logs and events off the node; keep log labels low-cardinality and put request ids in the log body.
  • Page on symptoms with runbooks: SLO burn, Pending-pod age, unavailable replicas, CrashLoopBackOff in prod, PVC fullness, cert expiry.
  • Alert on CPU throttling ratio and working-set memory near limits; they predict incidents that utilization graphs hide.
  • Review alert hygiene monthly: delete alerts nobody acted on; add a runbook to every remaining one.

Questions people ask

How do I get logs from a pod that already crashed?

kubectl logs <pod> --previous while the pod exists; after deletion, only your log shipper has them.

Why is kubectl top empty or showing ?

metrics-server is not installed or unhealthy, or the pods are too new. Check kubectl -n kube-system get deploy metrics-server and kubectl get apiservice v1beta1.metrics.k8s.io.

What should the first Kubernetes dashboard show?

Per namespace: desired vs available replicas, restarts over 1h, Pending pods, CPU throttling ratio, working-set memory vs limit, PVC usage; plus the four golden signals for each service.

Is an event-driven alert (e.g. on OOMKilling events) reliable?

Only if events are exported and deduplicated; prefer the metric (kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} with restarts) for alerting.

How much should logging cost?

Less than you think if you sample debug logs, keep labels low-cardinality, and set retention by tier; more than you think if every request id becomes a label.

Further reading

Drills · 7

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

An alert rule is kube_pod_container_status_restarts_total > 3. It has been firing for six weeks on a pod that restarted four times during a deploy in July. What is wrong?

  1. The metric is a counter; the rule should alert on increase(kube_pod_container_status_restarts_total[1h]) > 3 so it fires on new restarts, not on history. Counters only go up; thresholds on the raw value describe the past forever.
  2. kube-state-metrics is stale and needs a restart. The value is correct; the interpretation is wrong.
  3. The threshold is too low; use 30. Any raw threshold eventually sticks; the fix is the rate/increase function.
  4. Alerts should never be on restarts. Restart loops are a legitimate symptom; the rule just has to be shaped for a counter.
In short

The restart metric is a counter that only goes up; alert on increase() over a window instead of the raw value.

Why

Counter versus gauge is the most common alert bug on Kubernetes. increase() or rate() over a window turns a cumulative count into "how many recently", which is what a page should mean. Pair it with a for: duration so a single restart during a rollout does not page.

The common mistake

Tuning the threshold. Any raw threshold on a counter sticks forever; only rate() or increase() over a window turns it into 'how many recently'.

Read the docs

2 Answer out loud

You are on-boarding a new latency-sensitive service onto Kubernetes. Define the alerts you would ship with it on day one: for each, the metric, the shape of the rule, and whether it pages or tickets. Five to eight sentences.

In short

A strong answer pages on symptoms like error rate and latency, tickets on causes like restarts and throttling, and uses increase() on counters.

What a strong answer does
  • coverage: SLO burn (multi-window), latency, saturation predictors (throttling ratio, working set vs limit, PVC), availability (replicas unavailable, Pending age), restart loops with increase(), cert expiry; each with page/ticket.
  • correctness: increase()/rate on counters, working set for memory, throttling ratio, for: durations, runbook links.
  • communication: Symptoms first (page), causes second (ticket), one sentence of rationale each.
Why

Staff-level answers separate symptoms from causes, get the metric semantics right (counters, working set, throttling), and treat alert hygiene as part of the design.

The common mistake

Leading with CPU and memory thresholds. Utilisation is not a symptom; a service can breach its SLO at 30% CPU and page nobody.

3 Read the output

What is the most likely cause, and which lens told you?

$ kubectl get events -n shop --sort-by=.lastTimestamp | tail -5
3m   Warning  BackOff     pod/api-6b7f9-x2ll9   Back-off restarting failed container api in pod api-6b7f9-x2ll9
3m   Normal   Pulled      pod/api-6b7f9-x2ll9   Container image "registry.example.com/api:5.1.0" already present on machine
2m   Warning  Unhealthy   pod/api-6b7f9-m8dq2   Readiness probe failed: Get "http://10.244.3.7:8080/ready": dial tcp 10.244.3.7:8080: connect: connection refused
1m   Warning  BackOff     pod/api-6b7f9-x2ll9   Back-off restarting failed container api in pod api-6b7f9-x2ll9
1m   Normal   Killing     pod/api-6b7f9-m8dq2   Container api failed liveness probe, will be restarted
$ kubectl logs -n shop api-6b7f9-x2ll9 --previous | tail -2
FATAL: could not connect to database "shop" at db.shop.svc:5432: connection refused
exiting
  1. The node is out of memory. No OOMKilling event or exit 137 appears; the fatal log names the database.
  2. The image is corrupt; it was 'already present' so no new pull happened. 'Already present' means the pull was skipped because the image is cached; it is normal.
  3. The readiness probe path is wrong. Connection refused means nothing is listening, which the log explains: the process exited.
  4. The database Service is unreachable, so the app exits at startup (CrashLoopBackOff) and the other replica fails probes; the previous-container logs said it, the events showed the pattern. Events give the control-plane narrative (backoff, probe failures); logs from the crashed instance give the application's own reason.
In short

The app cannot reach its database and exits at start; the previous container's log said it and the events showed the restarts.

Why

Events tell you what Kubernetes did (restart, probe failed), logs tell you why the process behaved that way. The habit interviewers score: sort events by time, then read --previous logs, then look at the dependency named there (kubectl get endpoints db -n shop).

Read the docs

4 Scenario: what do you do next?

A customer reports intermittent 502s from the checkout API for the last 40 minutes. Dashboards show CPU at 30%, memory at 50%. No alerts fired. kubectl get pods -n shop shows all 6 checkout pods Running with a total of 19 restarts across them.

Step 1. Where do you look first?

  1. Increase the memory limit because 502s usually mean OOM. Assumption without evidence; the events may say OOMKilling or may not.
  2. The restart pattern: kubectl get pods -o wide restart column and ages, kubectl get events --sort-by=.lastTimestamp, then kubectl logs --previous on a recently restarted pod. 19 restarts with 'Running' status is the evidence that something is cycling; events and previous logs say why.
  3. Restart the ingress controller. Nothing points at ingress yet; the backend pods are restarting.
  4. Scale checkout to 12 replicas. More pods that restart the same way; no diagnosis.

Step 2. Events show Killing ... failed liveness probe every few minutes across pods; previous logs show slow GC pauses of 6–8 s; the liveness probe has timeoutSeconds 1 and failureThreshold 1. What is the mitigation?

  1. Remove the liveness probe permanently. Genuinely hung processes then never recover; the probe needs tuning, not removal.
  2. Add CPU to make GC faster. Maybe later; it does not stop the restarts in the next five minutes.
  3. Relax the liveness probe now (timeoutSeconds 5, failureThreshold 3) to stop the restart storm, then address the GC pauses. The probe is turning a latency problem into an availability problem; loosening it stops the bleeding within one rollout.
  4. Roll back to yesterday's image. Nothing yet indicates the image changed; check the deploy history before rolling back blind.

Step 3. Why did no alert fire, and what do you add?

  1. Alert whenever CPU is above 25%. CPU was not the problem and the alert would be pure noise.
  2. The alerts watched CPU and memory, not symptoms. Add SLO-based alerts (5xx ratio, latency), a restart-rate alert with increase(), and a liveness-failure alert; page on symptoms, ticket on causes. The gap was alerting on resources instead of user-facing symptoms; symptom alerts would have fired in minutes.
  3. Have the customer support team page on-call directly. Humans as monitoring is the failure mode you are trying to leave.
In short

Start with the restart pattern, events and previous logs; then relax the too-strict liveness probe; then add symptom alerts.

Why

Dashboards full of resource graphs can look green while users see errors; restart counts and events are where the story is. Interviewers score reading the evidence in order, the reversible mitigation, and recognizing that the missing alerts were symptom alerts.

Read the docs

5 Find what's broken

On-call complains of constant noise from this rule file and one incident that was missed. Which two lines are wrong?

groups:
  - name: k8s-prod
    rules:
      - alert: PodRestarting
        expr: kube_pod_container_status_restarts_total{namespace="prod"} > 0
        for: 0m
        labels: { severity: page }
        annotations: { summary: "pod restarted" }
      - alert: HighMemory
        expr: container_memory_rss{namespace="prod"} / container_spec_memory_limit_bytes{namespace="prod"} > 0.9
        for: 10m
        labels: { severity: page }
      - alert: PendingPods
        expr: sum(kube_pod_status_phase{namespace="prod", phase="Pending"}) > 0
        for: 5m
        labels: { severity: page }
        annotations: { summary: "pods pending in prod", runbook: "https://runbooks.example.com/pending-pods" }
      - alert: CpuThrottling
        expr: rate(container_cpu_cfs_throttled_periods_total{namespace="prod"}[5m]) / rate(container_cpu_cfs_periods_total{namespace="prod"}[5m]) > 0.25
        for: 15m
        labels: { severity: ticket }
In short

Line 5 alerts on a raw counter with no time window, and line 10 uses RSS instead of working-set memory to predict OOM kills.

What's broken
  • Line 5: A raw counter threshold with for: 0m pages forever after any single historical restart.
  • Line 10: RSS is not what the OOM killer measures; a pod can be OOMKilled with RSS at 60% because page cache counts toward the working set.
Why

Two of the four rules encode the two most common Kubernetes alerting mistakes: counters treated as gauges, and RSS treated as the OOM signal. The Pending-pods rule (with a runbook) and the throttling ratio (as a ticket) are the good examples in the file.

Read the docs

6 Pick the strongest answer

Which component does kubectl top pod read from, and what does that imply?

  1. kube-state-metrics, which tracks pod resource usage. kube-state-metrics exposes object state, not resource usage.
  2. metrics-server, via the metrics.k8s.io API: a live reading of current usage with no history. metrics-server exists for HPA and kubectl top; it does not store time series.
  3. The kubelet directly over SSH. kubectl talks to the API server; metrics-server aggregates kubelet data behind an API.
  4. Prometheus; kubectl top queries the last hour of data. kubectl has no Prometheus integration; historical data is Prometheus' job.
In short

kubectl top reads from metrics-server, which only holds the current value and no history.

Why

Three different sources answer three different questions: metrics-server for now, Prometheus for over time, kube-state-metrics for what the API objects say. Interviewers check that you do not treat them as one thing.

Read the docs

7 Quick recall

The incident was at 03:00; at 09:00 kubectl get events shows nothing about it and nobody exported events. Roughly how long does the API server keep Events by default?

In short

About one hour by default.

Accepted

1 hour · one hour · an hour

Why

About one hour (--event-ttl). Export events if you need them after an incident.

That's the last lesson in mission 10 Pick your next mission
Drill · Observability
0:00

Loading…