Kubernetes Observability Stack: Prometheus, Grafana, Loki and OpenTelemetry
A Kubernetes observability stack joins Prometheus metrics, Loki logs, OpenTelemetry traces and Grafana queries so an SRE can detect a failure, locate the workload, explain the cause and prove recovery from one evidence trail.
Introduction
A Kubernetes observability stack is the joined system that turns cluster and application signals into incident evidence: Prometheus stores metrics, Loki stores logs, OpenTelemetry standardises traces and collection, and Grafana queries and alerts across them. Built well, it answers what broke, where, why and whether recovery is real.
Consider an illustrative composite, not a named outage. A checkout service starts returning slow responses after a routine deploy. The alert fires, but the dashboard shows normal CPU. Logs are split across three restarted Pods, the trace view has gaps, and nobody can tell whether the delay sits in the database, a downstream API or CPU throttling inside one container. The tools exist. The evidence trail does not.
That failure is common because teams install components before they design signals. Prometheus scrapes whatever it can find, Loki receives labels copied from every Pod field, traces stop at the first service that drops context, and Grafana becomes a wall of panels with no shared keys. During the incident, each tool tells a partial story and the engineer becomes the join engine.
5-minute takeaway. Start with the questions, not the Helm charts. Metrics detect and size the failure, logs explain process behaviour, traces locate the slow or failing hop, and Kubernetes object state shows what the platform did. Keep labels bounded, correlate by service and trace ID, monitor the monitoring path, and price retention before volume prices you.
This is lesson twenty-one in the Kubernetes Roadmap Series. The previous post covered Kubernetes SecurityContext and Pod Security Standards. The next post covers PromQL for Kubernetes SREs, including throttling, memory pressure and restart alerts; both lessons sit in Module 10 of the Kubernetes roadmap.
1. What a Kubernetes observability stack must answer during an incident
A Kubernetes observability stack must answer four incident questions in order: is user impact real, which workload owns it, what changed or saturated, and has recovery held. Prometheus, Loki, OpenTelemetry and Grafana earn their place only when their signals join fast enough to answer those questions under pressure.
Detection comes first. A useful stack notices error rate, latency, saturation or failed rollouts before users report them, and it states the blast radius in service terms. A graph of Pod CPU cannot do that alone. The alert should name the service, the symptom, the current burn or threshold, and the dashboard that proves it. If the first alert says only that a container restarted, the stack is reporting platform noise, not service risk.
Location comes second. Kubernetes gives you layers that fail independently: node, kubelet, Pod, container, Service endpoint, ingress path and application dependency. The stack must move from service symptom to namespace, workload, Pod and node without manual label archaeology. That movement depends on consistent names for cluster, namespace, workload and service across metrics, logs and traces.
Explanation comes third. Metrics show that latency rose; they rarely show which database call, lock, retry storm or throttling period caused it. Logs carry the process explanation, traces carry the request path, and Kubernetes events carry scheduling, image pull, probe and eviction facts. A stack that stores those signals separately but cannot join them still leaves the hardest work to the person on call.
Recovery proof closes the loop. After a rollback, scale-up or limit change, the same evidence trail should show error rate falling, queues draining, restarts stopping and latency returning to baseline. Keep the incident view open until the signal that fired the alert has cleared for a sensible window. Declaring recovery from one green Pod is how teams close incidents twice.
2. Signals in a Kubernetes observability stack: metrics, logs, traces and events
A Kubernetes observability stack works when each signal has one job: metrics measure behaviour over time, logs explain process decisions, traces follow individual requests, and Kubernetes events record platform actions. Grafana joins those signals; it does not replace the stores that hold them.
| Signal | Incident question | Kubernetes sources | Store and query path | Retention posture |
|---|---|---|---|---|
| Metrics | How bad is it, and since when? | kube-state-metrics, kubelet and cAdvisor, node_exporter, application endpoints | Prometheus, queried from Grafana and Alertmanager | Hot detail for days or weeks, recorded aggregates for longer |
| Logs | What did the process say or decide? | Container stdout and stderr, node agents, application structured logs | Loki, queried with LogQL from Grafana | Short hot window, archive only where compliance or audit needs it |
| Traces | Which hop slowed or failed this request? | OpenTelemetry SDKs, auto-instrumentation, proxies and service mesh spans | Trace backend such as Tempo, Jaeger or a cloud trace store, queried from Grafana | Sampled and shorter than metrics, with errors and slow traces favoured |
| Events | What did Kubernetes do to the workload? | API server events for scheduling, probes, pulls, evictions and scaling | Kubernetes API first, exported when history matters | Short by default in Kubernetes, export before the window closes |
Metrics are the detection layer. They are cheap to query over time, good at rates and percentiles, and honest about saturation when the right series exist. Their weakness is explanation: a latency histogram can prove that checkout slowed, but it cannot name the SQL statement or the retry loop. Treat metrics as the map that tells you where to dig.
Logs are the explanation layer. A structured log line can carry the error class, dependency, attempt count and trace ID that a metric label must never carry. Their weakness is volume and search cost. Loki indexes labels, not every word in the line, so label design decides whether a query starts narrow or scans a cluster worth of streams.
Traces are the path layer. One trace shows the request crossing services, queues and databases with timing attached. Their weakness is coverage and sampling: a trace exists only where context propagated and the sampler kept it. OpenTelemetry standardises how spans are created and moved, but a backend still has to store and index them.
Events are the platform memory. Scheduling failures, probe failures, image pull errors, OOM kills and evictions often appear there before a dashboard explains them. Kubernetes events expire, so export the ones you need for post-incident review. The stack is complete when an engineer can move from alert to metric, metric to trace or log, and log to platform event without changing vocabulary.
3. Kubernetes observability stack metrics start with kube-state-metrics and cAdvisor
A Kubernetes observability stack needs two metric views from the start: kube-state-metrics reports what the API says exists, while kubelet and cAdvisor report what containers actually consumed. Confusing those views produces dashboards that look precise and answer the wrong question.
kube-state-metrics watches the Kubernetes API and turns object state into Prometheus series. It exposes desired and available replicas, Pod phase, container restart counts, resource requests and limits, Job completions, PersistentVolumeClaim state and similar facts. It does not measure CPU burn or memory pressure on a node. When a Deployment says three replicas desired and one available, kube-state-metrics is the source that proves the gap.
cAdvisor runs inside the kubelet and measures containers from the node side. It reports CPU usage, CPU throttling periods, memory working set, network and filesystem activity per container. Those series answer whether a Pod is being squeezed by its limits. A container can look healthy in object state while cAdvisor shows repeated throttling or a working set pressed against the memory limit.
The kubelet adds its own operational metrics: Pod startup latency, volume operations, runtime errors and node-level resource summaries. node_exporter covers the host beneath the Pods: CPU modes, memory availability, disk saturation, filesystem pressure and network errors. Application endpoints then add service behaviour that the platform cannot know, such as request rate, error classes and queue depth.
metrics-server sits outside this design. It implements the Metrics API from kubelet data so HPA, VPA and kubectl top can read current CPU and memory. It keeps no useful history for incident review and is not a Prometheus replacement. Keep it for autoscaling, and let Prometheus own retained metrics. The split matters because the next lesson builds PromQL on these sources; queries cannot recover a signal the stack never scraped.
4. Prometheus scrape discovery in a Kubernetes observability stack
Prometheus scrape discovery decides whether a Kubernetes observability stack has data at all: targets must follow Pods, Services and endpoints as they move, and relabeling must keep the labels engineers need without importing every metadata field as a series dimension.
Prometheus uses a pull model. It discovers targets, scrapes an HTTP metrics endpoint on an interval, stamps samples with target labels and writes series such as up for scrape health. In Kubernetes, discovery roles can watch Pods, Services, endpoints, endpoint slices, nodes and ingress objects. Each discovered target carries metadata labels that relabeling can promote, rewrite or drop before scraping begins.
Most production clusters manage this through the Prometheus Operator. A ServiceMonitor selects Services and named ports; a PodMonitor selects Pods directly; a ScrapeConfig covers cases the higher-level resources cannot express. The operator turns those resources into Prometheus configuration, which keeps scrape intent in Git beside the workload. The common failure is mundane: selector labels do not match, the port name is wrong, or the namespace selector excludes the workload.
A minimal ServiceMonitor shows the contract:
Relabeling is a design decision, not decoration. Keep stable join keys such as namespace, service, workload and container. Be careful with Pod name: it helps during an incident, but Pod churn creates series churn, and every extra label multiplies series when combined with other dimensions. Drop metrics nobody queries, cap samples per scrape where the platform supports it, and alert on target count changes after deploys.
Scrape health needs its own view. up == 0, rising scrape duration, rejected samples and targets disappearing after a rollout are stack failures, not application facts. Protect kubelet scraping with the cluster's normal TLS and RBAC path, and give Prometheus only the discovery permissions it needs. An observability stack with broad credentials and silent target loss is a liability wearing a dashboard.
5. Application metrics in a Kubernetes observability stack: RED, USE and bounded labels
Application metrics in a Kubernetes observability stack should describe user-facing behaviour first: request rate, errors and duration for services, plus utilisation, saturation and errors for the resources beneath them. Platform metrics locate the container; application metrics prove whether customers felt it.
The RED method fits request-driven services. Rate shows demand, errors show failure proportion, and duration shows latency distribution. Use counters for requests and errors so rates can be derived over any window. Use histograms for duration so percentiles and bucket analysis survive aggregation. A single average latency gauge hides the tail that users remember.
The USE method fits resources. For CPU, memory, disk, network and queues, ask how busy the resource is, how much work is waiting, and what errors it reports. In Kubernetes, USE questions connect cAdvisor throttling, memory working set, node pressure and application queue depth. RED tells you checkout is slow; USE tells you whether the slowdown rides on saturation or waits on a dependency.
Label discipline decides whether these metrics stay affordable. A Prometheus series is one metric name plus one exact label set, so label values multiply. Use bounded dimensions such as route template, method, status class and dependency name. Never label by raw URL, user ID, order ID, request ID or error message. Those values belong in logs and traces, where one request can be inspected without creating a permanent series.
Exemplars and recording rules complete the layer. Where the instrumentation and backend support them, exemplars attach a trace ID to a metric sample so a latency spike can open the exact request path. Recording rules precompute expensive service-level indicators and burn-rate inputs so dashboards and alerts stay fast. The next lesson writes the PromQL; this lesson fixes the contract those queries depend on: stable names, bounded labels and histograms where latency matters.
6. Loki logs in a Kubernetes observability stack: labels before volume
Loki logs in a Kubernetes observability stack stay useful only when labels describe the source, not the incident: cluster, namespace, service and container select streams, while Pod names, trace IDs and request fields travel as structured metadata or parsed log fields.
Loki groups log entries into streams defined by label sets, then indexes the labels rather than every word in each line. That design keeps ingestion and storage cheaper than full-text indexing, but it makes label choice structural. Every unique label combination creates another stream to index, flush and query. A label that looks harmless in one namespace can multiply streams across every Pod, container and rollout in the cluster.
Choose a small label set and defend it. Cluster, namespace, service or app, container and environment usually select the right stream family. Node can help in node incidents, but it adds another dimension across every stream. Pod name is the tempting trap: Pods churn during deploys and autoscaling, so a Pod label creates short-lived streams exactly when incident volume rises. Keep Pod identity available as structured metadata or a parsed field, and start queries from the workload.
Ship logs from the node with an agent such as Grafana Alloy or an OpenTelemetry Collector filelog receiver running as a DaemonSet. The agent reads container stdout and stderr, attaches Kubernetes metadata, handles multiline stack traces where possible, and forwards to Loki with tenant and rate limits respected. Applications should write structured logs to stdout: timestamp, level, service, message, error class, dependency, trace ID and span ID as fields, not prose that must be guessed apart later.
Query shape follows the same rule. Start with the narrowest label selector, then filter lines, then parse JSON or logfmt fields for the rare high-cardinality value. Broad selectors over long windows are expensive because Loki must open many streams and chunks. Drop or sample health-check noise at the source, redact secrets before ingestion, and alert on log-derived metrics sparingly. Metrics detect; logs explain. Reversing that order makes the log system carry alert load it was not priced for.
7. OpenTelemetry traces in a Kubernetes observability stack
OpenTelemetry traces in a Kubernetes observability stack follow one request across services, queues and databases, while the Collector moves spans safely from Pods to a trace backend. Traces locate the slow hop; metrics and logs still prove impact and cause.
Instrumentation creates spans. SDKs and auto-instrumentation record server, client, database and messaging spans with resource attributes such as service name, namespace, deployment and Pod identity. W3C trace context carries the trace ID across HTTP and messaging boundaries. When one service fails to propagate context, the trace breaks into islands and the slowest hop can hide in the gap.
The Collector is the traffic controller. A node-local DaemonSet collector can receive OTLP from Pods on the same node, add Kubernetes attributes, read logs and kubelet signals, and keep application exporters simple. A gateway Deployment can then batch, redact, tail-sample and export to trace, log and metric backends with shared policy. Small clusters may run one tier; larger clusters split the tiers so sampling and export failures do not multiply per node.
A compact collector shape looks like this:
Sampling is an evidence policy. Head sampling decides early and can discard the failing trace you later need. Tail sampling waits for the trace to complete and can keep errors, slow traces and rare routes, but it needs gateway memory and careful timeouts. Keep a baseline of normal traces so latency comparisons have a control group. The division of labour with Prometheus is covered in OpenTelemetry vs Prometheus; the tracing deep dive is OpenTelemetry Distributed Tracing Guide.
8. Grafana dashboards and alerts in a Kubernetes observability stack
Grafana dashboards and alerts in a Kubernetes observability stack turn stored signals into decisions in practice: dashboards show service impact and resource pressure side by side, while alerts fire on symptoms with a runbook, a dashboard link and a clear owner.
Build dashboards by audience and question. A cluster view answers whether nodes, control plane signals and shared services are healthy. A namespace or workload view answers whether one team's Pods are restarting, throttling or waiting on storage. A service view answers whether users see errors or latency, with RED panels first and resource panels beneath. One giant dashboard that tries to answer everything usually answers nothing at incident speed.
Variables and links carry the investigation. Cluster, namespace, service and workload variables should use the same names as metric labels, Loki labels and trace resource attributes. A latency panel should link to logs for the same service and window; a log line with a trace ID should open the trace; a restart panel should sit near Kubernetes events. Annotations for deploys, config changes and scaling events turn correlation from memory into evidence.
Alerting needs the same discipline. Prometheus and Alertmanager remain the natural home for metric alerts, recording rules and inhibition. Grafana-managed alerts can query multiple data sources where that helps, and Loki ruler rules can alert on log-derived metrics for cases metrics cannot express. Every alert needs severity, owner, summary, runbook and dashboard link. No-data behaviour must be explicit: a missing series can mean a dead exporter, a renamed metric or a service that stopped reporting, and each deserves a different response.
Provision dashboards and alert rules as code. Click-built dashboards drift, disappear in migrations and hide query cost until an incident loads them. Review panel queries like code, cap refresh rates on heavy dashboards, and test notification routes before they matter. The Grafana dashboards and alerting guide goes deeper on dashboard engineering; this stack view keeps Grafana honest as the joining layer, not the storage layer.
9. Correlate a Kubernetes observability stack by service, Pod and trace ID
Correlation in a Kubernetes observability stack depends on shared keys, not shared screens: service, namespace, workload, Pod, container, node and trace ID must mean the same thing in metrics, logs, traces and events before Grafana can join them during an incident.
Start every investigation from the alert's service identity. The alert names the service and symptom; the service dashboard confirms rate, errors and duration; exemplars or trace search open representative slow or failing requests; logs filtered by trace ID explain the process decision; kube-state-metrics and events show restarts, probe failures or rollout state; cAdvisor shows whether the container was throttled or memory pressed. Each step narrows the layer instead of restarting the search.
Naming consistency is the quiet prerequisite. If metrics use service, logs use app, traces use service.name and dashboards guess among them, correlation becomes manual translation. Pick canonical keys and map them at collection time: cluster, namespace, service, workload, container and node for grouping; Pod name for short-lived identity; trace ID and span ID for request identity. Keep request-level values out of metric labels and Loki index labels, but preserve them in trace fields and structured log metadata.
Time is a join key too. Nodes, collectors and backends need sane clock sync, and dashboards should show ingestion delay where the platform exposes it. A log line that arrives two minutes late can make a healthy deploy look guilty. Annotations help here: deploy markers, config reloads, autoscaling events and alert firings on the same timeline separate cause from coincidence.
Derived fields and data links finish the path. Configure Loki fields so a trace ID opens the trace backend. Configure trace views so a span links back to logs for the same service and window. Configure metric panels so a Pod or workload variable carries into the log query. Correlation is a product feature of the stack, and it should be tested with a synthetic failing request before a real incident tests it for you.
10. Retention and cost controls for a Kubernetes observability stack
Retention and cost in a Kubernetes observability stack follow three drivers: active metric series, ingested log volume with stream count, and retained trace spans. Control those drivers first, then set retention tiers that match incident review, compliance and budget over time.
Prometheus cost rises with series count, churn and query load. Every label value combination creates series, and short-lived Pods leave series behind until compaction and retention release them. Control the input: drop unused metrics, remove labels that no dashboard or alert uses, set scrape intervals by criticality, use recording rules for repeated expensive queries, and alert when head series or samples ingested jump after a deploy. Long-term metrics belong in remote storage or a scalable backend when local retention stops being honest.
Loki cost rises with bytes ingested, streams created and query scan width. Structured logs are valuable, but debug logging in production, repeated health-check lines and stack traces printed per retry can dwarf application signal. Sample or drop known noise at the source, keep labels bounded, use structured metadata for request fields, and set per-tenant ingestion and stream limits. Retention should differ by stream value: security and audit logs may need archive, while noisy application debug logs rarely earn long hot storage.
Trace cost rises with spans retained. Instrument the paths that explain user impact, propagate context through queues and proxies, then sample with intent: keep errors, slow traces and rare routes, keep a baseline of normal traces, and drop health checks. Tail sampling at the gateway protects evidence better than blind head sampling, but it must be sized for peak trace volume and failure behaviour.
Set retention by decision window. Metrics need enough hot detail to compare deploys and investigate last week's incident, with aggregates kept longer for capacity and SLO review. Logs need a hot window that covers incident discovery lag, plus archive only where a rule requires it. Traces need the shortest window that still explains recurring latency. Review the bill by namespace and service, and make cardinality a code-review concern. Telemetry without an owner becomes storage without a reader.
11. Operate a Kubernetes observability stack without blind spots
Operating a Kubernetes observability stack means monitoring the monitoring path itself: scrape health, ingestion lag, dropped telemetry, rule evaluation, notification delivery and backend capacity need alerts before an application incident exposes their absence and before users discover the gap during an outage.
Watch Prometheus as a production service. Track target count, scrape failures, scrape duration, samples ingested, head series, rule evaluation errors and TSDB storage pressure. A sudden target drop after a platform change can mean discovery broke, not that the cluster became healthy. High availability usually means paired Prometheus servers with Alertmanager clustering and deduplication downstream, or a managed backend that owns that problem explicitly.
Watch Loki and the collectors with the same suspicion. Log agents should report positions, retries and dropped lines; Loki should expose ingestion errors, stream counts, chunk flush behaviour and query latency; OpenTelemetry Collectors should report refused spans, queue depth, exporter failures and memory limiter drops. A collector that silently discards telemetry under load turns the stack into a fair-weather witness.
Watch Grafana and alert delivery end to end. Data source health, dashboard query errors, alert evaluation state and notification failures belong on a stack health view. Send test alerts through the real route to the real receiver. Keep a dead man's switch or heartbeat alert that fires when the alerting path itself stops reporting. Silence is the worst alert state because it looks like health.
Protect the stack like production infrastructure. Scrape credentials and kubelet access need least privilege, Grafana permissions should separate viewers from alert editors, tenants should not query each other's logs by accident, and secrets or personal data must be redacted before logs and traces are stored. Back up dashboards, rules and collector configuration as code. When the stack itself misbehaves, the production monitoring and alerting troubleshooting guide is the deeper triage path.
12. Kubernetes observability stack troubleshooting matrix and final checklist
Kubernetes observability stack troubleshooting starts by naming the broken layer: discovery, metric source, log stream, trace propagation, query join or alert delivery. The matrix below maps common symptoms to the first check that separates a stack fault from an application fault.
| Symptom | Likely layer | First check |
|---|---|---|
| New service has no metrics | ServiceMonitor selection or port contract | Prometheus targets, Service labels, named port and namespace selector |
Pod runs but up == 0 |
Scrape path, TLS, auth or network policy | Target error text, metrics path from inside the cluster, policy on the scrape path |
| Restarts missing from dashboards | kube-state-metrics health or RBAC | kube-state-metrics Pod, API watch errors and restart series presence |
| Throttling not visible | cAdvisor series dropped or renamed | Kubelet cAdvisor endpoint and metric relabeling rules |
| Logs stop after Pod restart | Node agent lag, positions or ingestion limits | Agent logs, previous container logs and Loki ingestion errors |
| Loki queries are slow | Label cardinality or broad time range | Stream count, selector width and chunk flush reasons |
| Traces break between services | Context propagation or sampling | Trace ID continuity across headers, queues, proxies and sampler policy |
| Prometheus memory keeps rising | Cardinality growth or Pod churn | Top series by metric and label, recent instrumentation changes |
| Alert never arrives | Rule evaluation, no-data state or routing | Alert state, Alertmanager route, silences and receiver test |
A short command set covers the first pass:
Read the output in layer order. Monitoring Pods and ServiceMonitors prove the stack can see. Workload Pods, descriptions and events prove what Kubernetes did. Logs prove what the process said. kubectl top gives current resource use only; retained proof still comes from Prometheus series scraped before the incident.
Final checklist for a stack you can defend:
- kube-state-metrics, kubelet and cAdvisor, node signals and application metrics are scraped and visible.
- ServiceMonitor or PodMonitor selection is tested after every new service and namespace change.
- Metric labels are bounded, with route templates instead of raw URLs and no request IDs as labels.
- Loki labels select streams by source, while Pod names and trace IDs live in structured metadata or fields.
- OpenTelemetry context propagates across HTTP, queues and proxies, and sampling keeps errors and slow traces.
- Grafana dashboards link metric panels to logs and traces with shared service and namespace variables.
- Alerts carry owner, severity, runbook and dashboard links, and notification routes are tested.
- Retention, cardinality, ingestion lag and dropped telemetry have dashboards, limits and owners.
Frequently Asked Questions
What is a Kubernetes observability stack?
A Kubernetes observability stack is the joined system that collects, stores, queries and alerts on cluster and application signals. Prometheus stores metrics, Loki stores logs, OpenTelemetry standardises traces and collection, a trace backend stores spans, and Grafana joins the evidence for incident decisions.
Which metrics should a Kubernetes observability stack collect first?
Start with kube-state-metrics for object state, kubelet and cAdvisor for container CPU, throttling and memory working set, node signals for host pressure, and application RED metrics for request rate, errors and duration. That set separates platform faults from service impact quickly.
How does Prometheus discover targets in a Kubernetes observability stack?
Prometheus watches Kubernetes objects through service discovery roles for Pods, Services, endpoints, endpoint slices, nodes and ingresses. With the Prometheus Operator, ServiceMonitor and PodMonitor resources select targets declaratively, and relabeling promotes stable metadata such as namespace and service into series labels.
Why does Loki label cardinality matter in a Kubernetes observability stack?
Loki labels define log streams, so every unique label combination creates another stream to index and query. Bounded source labels keep streams manageable. Pod names, request IDs, trace IDs and user IDs belong in structured metadata or parsed fields, not index labels.
How do OpenTelemetry traces fit into a Kubernetes observability stack?
OpenTelemetry SDKs and auto-instrumentation create spans, W3C trace context carries the trace ID across services, and the Collector batches, samples, redacts and exports spans to a trace backend. Grafana then links a slow metric panel to the trace and its logs.
How long should a Kubernetes observability stack retain metrics, logs and traces?
Retain by decision window, not habit. Keep hot metric detail long enough for deploy comparison and incident review, keep aggregates longer, keep logs through the discovery lag plus any audit archive rule, and keep sampled traces for the shortest window that explains recurring latency.
What is the difference between metrics-server and Prometheus in a Kubernetes observability stack?
metrics-server serves current CPU and memory through the Metrics API for HPA, VPA and kubectl top; it is not a history store. Prometheus scrapes many sources, retains time series, evaluates recording and alerting rules, and feeds Grafana dashboards for incident review.
Preparing for Senior Platform & SRE Interviews
Practice real-world incident triage, high-cardinality Prometheus debugging, and distributed tracing scenarios in our Observability SRE interview hub.
Explore Interview Scenarios →