Introduction

PromQL for Kubernetes starts where installation guides stop. The previous lesson, the Kubernetes observability stack with Prometheus, Grafana, Loki and OpenTelemetry, covered getting metrics flowing. This lesson assumes the series exist and answers the question: what to type when latency is up, CPU graphs look calm, and nobody knows which container is lying?

Consider an illustrative composite drawn from common production reviews, not a named incident. An API service shows 40 percent CPU on its dashboard and p99 latency triple the normal value. The on-call engineer checks the graph twice, sees nothing, and starts reading application code. The real signal sits in a counter nobody graphed: the container hits its CPU limit in short bursts inside each 100 millisecond scheduling period, so average CPU stays low while the kernel throttles the process again and again. A second container in the same namespace restarts every twenty minutes, and a third sits Pending because its memory request no longer fits on any node. Three different failures, three different metric families, one query language.

This is lesson 22 of the Kubernetes Roadmap Series, in Module 10 on observability. It covers the queries an SRE reaches for weekly: CPU throttling ratios from cAdvisor, memory working set against limits, restart counts from kube-state-metrics, Pod phase checks for stuck workloads, and the recording rules and alert durations that turn those queries into pages worth answering. The next lesson, on the Horizontal Pod Autoscaler, sits in Module 11 on Kubernetes autoscaling, and it depends on the signals built here, because an autoscaler fed by a bad query scales confidently in the wrong direction.

The 5-minute takeaway

Counters get rate or increase, gauges get compared, and state metrics get counted. Throttling is a ratio of throttled periods to total periods, not a CPU percentage. Memory risk is working set divided by the limit, not RSS alone. Restarts are an increase over a window with a threshold, not a raw counter value. Every alert needs a for duration long enough to outlast a rollout and short enough to matter. Recording rules precompute the expensive ratios so dashboards and alerts read one cheap series. Label sets stay small and bounded, because every extra label value multiplies storage and query cost.


1. PromQL for Kubernetes: rate and increase turn counters into answers

PromQL for Kubernetes treats counters as raw material, not answers. A counter only climbs, so rate gives the per-second speed over a window and increase gives the total climb inside that window. Use rate for CPU and throttling graphs, and increase for restart counts and event totals.

Most Kubernetes series that matter are counters. containercpuusagesecondstotal counts CPU seconds a container has burned since it started. kubepodcontainerstatusrestarts_total counts restarts since kube-state-metrics began watching. Graphing either one raw produces a staircase that climbs forever and tells you nothing about the last ten minutes. The first skill is choosing the right window function for the question you actually asked.

rate answers "how fast right now, smoothed over the window". rate(containercpuusagesecondstotal[5m]) returns cores in use, because CPU seconds per second is cores. A value of 0.75 means the container used three quarters of a core on average across five minutes. rate handles counter resets when a container restarts, extrapolates to the window edges, and smooths over missing scrapes. That smoothing is why rate suits graphs and alerts: one bad scrape does not move the line much.

increase answers "how many in this window". increase(kubepodcontainerstatusrestarts_total[1h]) returns restarts in the last hour, which is the unit a human reasons in. Nobody pages on 0.0008 restarts per second. They page on more than three restarts in an hour. increase is rate multiplied by the window length under the hood, with the same reset handling, so pick the function that matches the unit in your alert text.

Window length is a trade between noise and delay. A 1 minute window reacts fast and jumps around; a 15 minute window is calm and slow to show a fresh problem. A practical default is 5 minutes for graphs and alert expressions, with the alert for duration doing the noise filtering. irate exists for graphs where you want the sharpest recent movement, but it reads only the last two samples, so a single missed scrape bends it. Keep irate out of alerts.

One rule prevents most beginner errors: never apply rate to a gauge. containermemoryworkingsetbytes goes up and down, so rate on it produces nonsense with a plausible shape. Gauges get compared, averaged with avgovertime, or checked with maxovertime when you want the worst value inside a window. Counters get rate or increase. If you do not know which type a metric is, check the metric help text in the Prometheus UI before you build an alert on it.

promql
# CPU cores per container, smoothed over 5 minutes
sum by (namespace, pod, container) (
  rate(container_cpu_usage_seconds_total{container!="", pod!=""}[5m])
)

# Restarts per container in the last hour
increase(kube_pod_container_status_restarts_total[1h]) > 0

2. PromQL for Kubernetes: CPU usage against requests and limits

PromQL for Kubernetes CPU queries divide usage by the request or the limit, and the two ratios answer different questions. Usage over request tells you whether scheduling assumptions hold. Usage over limit tells you how close the container sits to throttling. Report both, because each one hides what the other shows.

The request is what the scheduler reserved. If a container requests 500m and steadily uses 900m, the node is overcommitted relative to the plan, and neighbours feel it during contention. The limit is the ceiling the kernel enforces through CFS bandwidth control. A container can sit at 95 percent of its limit with a request ratio that looks healthy, or blow past its request while staying far from a generous limit. One number cannot carry both meanings.

kube-state-metrics exposes the request and limit side. Current versions publish kubepodcontainerresourcerequests and kubepodcontainerresourcelimits with a resource label such as cpu or memory. Older versions split them into names ending in cpucores and memorybytes. Check your own Prometheus for which form exists before copying any query, because a query against a missing metric returns an empty result, and an empty result looks exactly like a healthy cluster.

Vector matching is the part that bites. The usage side aggregates by namespace, pod and container. The request side must aggregate to the same label set, or PromQL returns nothing. When a division returns empty, suspect label mismatch before you suspect the cluster. Print both sides separately in the graph UI, confirm the labels line up, then divide.

promql
# Usage as a fraction of the CPU request, per container
sum by (namespace, pod, container) (
  rate(container_cpu_usage_seconds_total{container!="", pod!=""}[5m])
)
/
sum by (namespace, pod, container) (
  kube_pod_container_resource_requests{resource="cpu"}
)

# Usage as a fraction of the CPU limit, per container
sum by (namespace, pod, container) (
  rate(container_cpu_usage_seconds_total{container!="", pod!=""}[5m])
)
/
sum by (namespace, pod, container) (
  kube_pod_container_resource_limits{resource="cpu"}
)

Treat the request ratio as a capacity signal and the limit ratio as a latency risk signal. A request ratio persistently above 1 means rightsizing work: raise the request or accept that the scheduler plan is fiction. A limit ratio near 1 means throttling is likely, but likely is not proof. The next section measures throttling directly, because a container can suffer throttling at a modest average limit ratio when its work arrives in bursts.


3. PromQL for Kubernetes: measure CPU throttling as a ratio

PromQL for Kubernetes measures throttling with two cAdvisor counters: throttled periods divided by total periods, or throttled seconds per second. The ratio form answers how often the kernel stopped the container. The seconds form answers how much waiting time accumulated. Use the ratio for alerts and the seconds form for severity.

Linux CFS bandwidth control gives a container a quota of CPU time inside each period, commonly 100 milliseconds. A container with a 500m limit may run 50 milliseconds per period. When it spends that quota early, the kernel parks its threads until the next period starts. The process is not slow because the node is busy. It is slow because its own ceiling arrived mid-request. Average CPU over five minutes can read 30 percent while every request that lands in a busy burst waits.

cAdvisor exposes the bookkeeping. containercpucfsperiodstotal counts periods in which the container used CPU. containercpucfsthrottledperiodstotal counts periods where throttling happened. containercpucfsthrottledsecondstotal accumulates the time spent throttled. The ratio of throttled periods to total periods, computed over the same window, gives the share of periods that hit the ceiling.

promql
# Share of CFS periods that were throttled, per container
sum by (namespace, pod, container) (
  rate(container_cpu_cfs_throttled_periods_total{container!=""}[5m])
)
/
sum by (namespace, pod, container) (
  rate(container_cpu_cfs_periods_total{container!=""}[5m])
)

# Throttled seconds per second, per container
sum by (namespace, pod, container) (
  rate(container_cpu_cfs_throttled_seconds_total{container!=""}[5m])
)

Read the ratio with care. A ratio of 0.25 means a quarter of periods saw throttling, which for a latency-sensitive service is a serious signal even when total throttled time looks small. Multithreaded containers complicate the seconds form: throttled seconds accumulate across threads, so the rate can exceed 1 without anything being wrong with the query. That is why the ratio makes the cleaner alert and the seconds form makes the better severity gauge on a dashboard.

Thresholds are starting points, not laws. Many teams alert when the throttled-period ratio stays above 0.1 to 0.25 for ten minutes on user-facing services, and only ticket on batch work. The right threshold comes from your latency budget: graph the ratio next to p99 latency for a week, find where latency bends, and alert below that point. Also check whether the limit should exist at all. Removing CPU limits and keeping honest requests is a common production choice, because requests still drive scheduling while bursts stop hitting an artificial ceiling. That decision belongs to your capacity model, but throttling data is what makes it an informed decision instead of an argument.


4. PromQL for Kubernetes: working set, RSS and cache are three different numbers

PromQL for Kubernetes memory queries fail when teams treat every memory metric as the same number. Working set estimates memory the kernel cannot reclaim quickly. RSS counts resident pages for the process. Cache counts file-backed pages the kernel can drop under pressure. Alert on working set against the limit, and use the other two to explain it.

containermemoryworkingsetbytes is the number Kubernetes itself watches for eviction decisions. It takes total usage and subtracts inactive file cache, approximating the memory the container would still hold if the node came under pressure. That makes it the right numerator for a headroom alert: working set divided by the memory limit, sustained above roughly 0.9, means the next allocation spike can end in an OOM kill or an eviction.

containermemoryrss counts anonymous and swapped resident pages belonging to the container processes. It excludes most page cache. A workload that reads large files can show modest RSS while cache grows, and a workload with a heap leak shows RSS climbing steadily. RSS answers "what does the process itself hold", which is the right question when you suspect a leak or a mis-sized heap.

containermemorycache counts file-backed cache pages charged to the container. Cache is reclaimable, so high cache alone is not danger. It becomes relevant when working set and usage disagree: containermemoryusage_bytes includes cache, so a usage graph can look alarming while working set stays calm. Teams that alert on usage page on harmless file reads. Teams that alert on working set page on memory the kernel actually needs back.

promql
# Working set as a fraction of the memory limit, per container
sum by (namespace, pod, container) (
  container_memory_working_set_bytes{container!=""}
)
/
sum by (namespace, pod, container) (
  kube_pod_container_resource_limits{resource="memory"}
)

# RSS growth check: highest RSS in the last 6 hours, per container
max by (namespace, pod, container) (
  max_over_time(container_memory_rss{container!=""}[6h])
)

The shape of the graph separates the fixes. Working set flat just under the limit points to a limit set too low for a stable workload. Working set climbing in a straight line for days points to a leak, and a bigger limit only buys time. Working set spiking with traffic peaks points to request sizing and replica count. The OOMKilled troubleshooting guide covers the kill itself; this section covers seeing it coming, which is the difference between a ticket and a page.


5. PromQL for Kubernetes: memory pressure needs a trend, not a snapshot

PromQL for Kubernetes memory pressure alerts work best with a sustained ratio and a trend check together. The ratio says how close the container is to its limit now. A linear prediction over several hours says whether it will cross the limit before the next business day. Pair them so slow leaks page early and brief spikes stay quiet.

A single threshold on working set ratio has a blind spot. A container leaking 20 megabytes an hour sits at 60 percent of its limit all afternoon and crosses 100 percent at 3 a.m. The threshold alert fires correctly and uselessly, at the worst hour. predict_linear fits a line to recent samples and projects the value forward, which turns that 3 a.m. kill into an afternoon ticket.

promql
# Projected working set 4 hours ahead, based on the last 6 hours
predict_linear(
  container_memory_working_set_bytes{container!=""}[6h], 4 * 3600
)
>
on (namespace, pod, container)
kube_pod_container_resource_limits{resource="memory"}

Prediction has limits worth stating plainly. It assumes the recent trend continues, so a workload with daily traffic cycles produces projections that rise every morning and fall every evening. Gate the prediction alert with a current-ratio floor, for example only when the present ratio already exceeds 0.7, and give it a long for duration. The goal is a ticket during work hours, not a page during a traffic peak that would have passed.

Node-level pressure is the second half of the picture. A container can sit comfortably under its own limit while the node runs out of reclaimable memory and the kubelet starts evicting. kube-state-metrics reports node conditions, and kubenodestatus_condition with condition MemoryPressure tells you the kubelet already feels the squeeze. Container headroom and node pressure answer different questions, and an incident review that checks only one will miss half the story.

Also separate request pressure from limit pressure. If working set sits far above the memory request, the scheduler placed the Pod using a number the workload outgrew, and eviction order during node pressure turns against it. Memory requests equal to limits give Guaranteed quality of service and the strongest eviction protection, at the cost of tighter packing. That trade belongs in your platform standards, but the ratio queries in section 4 supply the evidence for it.


6. PromQL for Kubernetes: restart alerts count increases, not totals

PromQL for Kubernetes restart alerts use increase over a window, because the raw restart counter only climbs and means nothing without a time frame. More than three restarts in fifteen minutes signals a crash loop. One restart in an hour usually signals a deploy, a probe blip, or a node event.

kubepodcontainerstatusrestarts_total is a counter per container. Its absolute value mixes history with the present: a container that restarted fifty times last month and never since looks identical to one restarting now. increase over a window fixes that. The window choice sets the alert personality. Fifteen minutes catches fast crash loops. One hour catches slow flapping, such as a container that dies on a bad config reload every forty minutes.

promql
# Containers restarting more than 3 times in 15 minutes
increase(kube_pod_container_status_restarts_total[15m]) > 3

# Slow flap: more than 5 restarts in 6 hours
increase(kube_pod_container_status_restarts_total[6h]) > 5

The count says a container is flapping; the termination reason says why. kubepodcontainerstatuslastterminatedreason carries labels such as OOMKilled, Error and Completed. Joining the two ideas in an investigation saves a trip through kubectl describe for every alert, although describe remains the ground truth during an incident. A restart alert whose annotation links to the runbook for that reason turns a page into a procedure.

Expect restarts during rollouts. A Deployment update replaces Pods, and new containers may restart once while caches warm or migrations settle. Alert design absorbs this with the for duration and with thresholds above the rollout noise floor. If every deploy pages, the team learns to ignore the alert, and the one real crash loop hides inside that learned behaviour. The CrashLoopBackOff troubleshooting guide covers the failure mode itself; the alert here only has to notice it early and stay quiet the rest of the time.

Counter resets deserve one sentence of care. When kube-state-metrics restarts, its counters can reset, and increase compensates for resets inside the window. Subtracting two raw counter values by hand does not compensate and produces negative spikes. Always let increase or rate do the arithmetic.


7. PromQL for Kubernetes: Pod phase queries find stuck work early

PromQL for Kubernetes Pod phase queries count Pods by phase from kube-state-metrics, and the Pending count is the one that saves deployments. A Pod Pending for fifteen minutes usually means requests that fit nowhere, a taint nobody tolerates, or a volume that will not bind. Phase counts catch scheduling failure before users do.

kubepodstatus_phase emits one series per Pod and phase, with value 1 for the current phase and 0 for the others. Summing the Pending series by namespace gives the stuck-work count. The raw count needs a duration guard, because every Pod passes through Pending briefly during creation. The alert for duration provides that guard: Pending above zero for fifteen minutes is a problem; Pending for forty seconds is a rollout.

promql
# Pending Pods per namespace
sum by (namespace) (kube_pod_status_phase{phase="Pending"})

# Failed Pods per namespace
sum by (namespace) (kube_pod_status_phase{phase="Failed"})

# Running share: Pods not Running, per namespace
sum by (namespace) (kube_pod_status_phase{phase!="Running"})

Phase data has a trap: Succeeded Pods from Jobs are not failures, and a namespace full of completed batch Pods inflates any not-Running count. Filter by phase explicitly and think about which workloads you mean. For services, Running is the expectation. For batch namespaces, Failed and long-Pending matter, and Succeeded is the goal.

Phase also connects the earlier sections. A Pod that stays Pending after a memory request increase is a capacity signal, not a scheduling bug. A Pod cycling between Running and restart counts points back to section 6. A Pod evicted under node memory pressure links to section 5. Phase is the map; the resource queries explain the terrain. During an incident, start with phase to find where work is stuck, then move to the resource query that matches the symptom.

Keep the phase alert annotation useful. Include the namespace, the count, and a link to the dashboard filtered to that namespace. The engineer who receives the page should land one click from the Pod list, not at a cluster overview that requires three more minutes of navigation.


8. PromQL for Kubernetes: recording rules make expensive queries cheap

PromQL for Kubernetes recording rules precompute the ratios from earlier sections on a schedule, so dashboards and alerts read one finished series instead of recomputing divisions across thousands of raw series. Record the throttling ratio and the memory headroom ratio once, then reuse them everywhere.

A recording rule evaluates an expression every evaluation interval and stores the result as a new series. The naming convention is level:metric:operations, for example namespacepodcontainer:containercpucfsthrottledratio:rate5m. The colons mark the series as rule output, which keeps recorded series visually separate from scraped ones. Names are documentation that cannot drift from the data, so write them carefully.

yaml
groups:
  - name: kubernetes-resource-ratios
    interval: 30s
    rules:
      - record: namespace_pod_container:cpu_throttled_period_ratio:rate5m
        expr: |
          sum by (namespace, pod, container) (
            rate(container_cpu_cfs_throttled_periods_total{container!=""}[5m])
          )
          /
          sum by (namespace, pod, container) (
            rate(container_cpu_cfs_periods_total{container!=""}[5m])
          )
      - record: namespace_pod_container:memory_working_set_ratio:current
        expr: |
          sum by (namespace, pod, container) (
            container_memory_working_set_bytes{container!=""}
          )
          /
          sum by (namespace, pod, container) (
            kube_pod_container_resource_limits{resource="memory"}
          )

Record re-aggregatable forms. A recorded ratio per container can be averaged or maxed later; a recorded cluster-wide average cannot be broken back down when an incident asks which namespace is responsible. Keep namespace, pod and container labels on the recorded series, and let dashboards aggregate upward. The cost is one series per container, which is bounded by workload count and entirely reasonable.

Rules earn their storage in three situations: the expression feeds an alert, the expression feeds several dashboards, or the raw query scans enough series to feel slow. A query run twice a month by one engineer does not need a rule. Every rule writes samples for the full retention window, so a rule nobody reads is a standing storage bill. Review rule usage the way you review dashboards, and delete rules whose consumers disappeared.

Rules inside one group evaluate in order, so a later rule may build on an earlier one in the same group. Keep each derivation chain inside a single group, in dependency order, and the timing stays predictable. Splitting a chain across groups with different intervals produces values that lag each other by one evaluation, which is a confusing bug to chase during an incident.


9. PromQL for Kubernetes: the for duration decides whether alerts flap

PromQL for Kubernetes alerts pair every expression with a for duration, and that duration is where alert quality lives. The expression detects a condition; for decides how long the condition must hold before anyone gets paged. Short durations page on rollouts. Long durations page after users already noticed.

An alert without for fires the first evaluation where the expression is true. During a rollout, throttling ratios spike, restart counts tick, and Pending counts rise for a minute or two. Without a duration guard, every deploy produces a burst of pages that resolve themselves. Teams respond by muting, and muted alerts stay muted during real incidents. The for duration is the cheapest reliability feature in the whole stack.

yaml
groups:
  - name: kubernetes-sre-alerts
    rules:
      - alert: ContainerCPUThrottlingHigh
        expr: |
          namespace_pod_container:cpu_throttled_period_ratio:rate5m > 0.25
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "Container {{ $labels.container }} in {{ $labels.namespace }}/{{ $labels.pod }} is CPU throttled"
          description: "Throttled period ratio above 0.25 for 10 minutes. Check the CPU limit and recent traffic."
      - alert: ContainerMemoryNearLimit
        expr: |
          namespace_pod_container:memory_working_set_ratio:current > 0.9
        for: 15m
        labels:
          severity: warning
        annotations:
          summary: "Container {{ $labels.container }} in {{ $labels.namespace }}/{{ $labels.pod }} is near its memory limit"
          description: "Working set above 90 percent of the limit for 15 minutes. Check for leaks before raising the limit."
      - alert: ContainerRestartingOften
        expr: |
          increase(kube_pod_container_status_restarts_total[15m]) > 3
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Container {{ $labels.container }} in {{ $labels.namespace }}/{{ $labels.pod }} keeps restarting"
          description: "More than 3 restarts in 15 minutes. Check the last terminated reason and recent changes."

Choose durations from the failure speed. A crash loop harms users within minutes, so five minutes of confirmation is plenty. Memory creep harms over hours, so fifteen minutes filters traffic spikes without losing the signal. Pending Pods block a rollout, and fifteen minutes separates a slow node scale-up from a genuine scheduling failure. Write the reasoning into the rule file as a comment; the next engineer tuning thresholds needs the intent, not just the number.

Severity labels should map to response expectations. Warning means a ticket during work hours. Critical means a page now. If everything is critical, nothing is. Reserve pages for conditions where user impact is present or minutes away, and let Alertmanager grouping collapse a namespace-wide event into one notification instead of forty. The Grafana dashboards and alerting guide covers routing and presentation; the rule design here decides what deserves to arrive.

Test alerts before trusting them. Use promtool to check rule syntax, then run the expression in the graph UI against last week's data and confirm it would have fired when you wanted and stayed silent otherwise. An alert that has never been observed firing is a hypothesis, not a safety net.

bash
promtool check rules kubernetes-sre-alerts.yaml
kubectl -n monitoring get prometheusrules
kubectl -n monitoring port-forward svc/prometheus-operated 9090:9090

10. PromQL for Kubernetes: label cardinality sets the cost ceiling

PromQL for Kubernetes cost is set by label cardinality, because every unique label combination is a separate time series that Prometheus stores, indexes and scans. Namespace, pod and container labels are bounded by workload count. User IDs, request IDs and full URLs are unbounded and belong in logs, not metrics.

Cardinality multiplies. A metric with 10 endpoints, 5 status codes and 4 instances is 200 series. Add a user_id label with a million values and the same metric becomes a memory problem with a query timeout attached. Kubernetes labels are mostly safe because the platform bounds them: namespaces number in the dozens, Pods in the thousands. The danger arrives through application metrics and through recording rules that keep labels nobody queries.

Aggregation is the pressure valve. sum by (namespace) collapses thousands of Pod series into dozens of namespace series for overview dashboards. The discipline is aggregating at the right level for the question: cluster overview by namespace, incident work by pod and container. Aggregating away the container label in an alert destroys the information the responder needs, so alerts keep the labels that identify the failing unit and drop the rest.

Watch the series count of your own rules. A recording rule that keeps namespace, pod, container and image labels writes one series per combination, and image tags change on every deploy, so the combination count grows with release history until old series age out. Drop labels that change often and answer no operational question. The labeldrop relabel action and aggregation without the label both work; the point is deciding on purpose.

Prometheus exposes its own health through metrics such as prometheustsdbhead_series. Graph it. A step change after a deploy usually means a new label value appeared somewhere, and finding it early is far cheaper than finding it during a Prometheus outage. Cardinality discipline is unglamorous and it is the reason the queries in this guide stay fast on a busy cluster.


11. PromQL for Kubernetes: a query table for the first ten minutes

PromQL for Kubernetes incident work benefits from a fixed query order, because the first ten minutes decide whether the response is diagnosis or guessing. Start with Pod phase to locate stuck work, then throttling, then memory headroom, then restarts. The table below is that order, written down.

Question Query shape Source Healthy result
Is work stuck scheduling? sum by (namespace) (kubepodstatus_phase{phase="Pending"}) kube-state-metrics Zero, or brief spikes during rollouts
Is a container throttled? throttled periods rate / total periods rate cAdvisor Ratio under 0.1 for user-facing services
How much waiting accumulated? rate(containercpucfsthrottledseconds_total[5m]) cAdvisor Near zero outside traffic peaks
Is memory close to the limit? working set / memory limit cAdvisor + kube-state-metrics Under 0.8 sustained
Is memory climbing toward trouble? predict_linear over 6h, projected 4h cAdvisor Projection under the limit
Is a container flapping? increase(restarts_total[15m]) kube-state-metrics 3 or fewer
Why did it last die? kubepodcontainerstatuslastterminatedreason kube-state-metrics Completed or empty for services
Are requests honest? CPU usage / CPU request cAdvisor + kube-state-metrics Near or under 1 over days

Run the table top to bottom and stop at the first unhealthy row. Each row points at a section of this guide with the full query and the fix. The order matters: a Pending Pod explains missing capacity that looks like a performance problem, and throttling explains latency that looks like an application bug. Checking application code before these rows is how incidents stretch from twenty minutes to two hours. When the rows point at the monitoring pipeline itself, the production monitoring and alerting troubleshooting guide covers the deeper triage path.

Keep the table honest by testing it. Once a quarter, pick a staging workload, set a tiny CPU limit, and confirm the throttling row moves. Set a memory limit near the working set and confirm the headroom row moves. Kill a container repeatedly and confirm the restart row moves. Queries that have never been seen working fail silently when needed, and the failure looks like a healthy cluster.


12. PromQL for Kubernetes: troubleshooting matrix and production checklist

PromQL for Kubernetes troubleshooting follows a pattern: the symptom names the metric family, the metric family names the query, and the query result names the fix. The matrix below maps the common symptoms to that chain, and the checklist turns the whole guide into a review you can run on any cluster.

Symptom First query Likely cause Fix direction
Latency up, CPU graph calm Throttled period ratio CPU limit too low for bursty work Raise or remove the CPU limit, keep honest requests
OOM kills at night Working set trend + predict_linear Slow leak or limit under peak need Fix the leak, or size the limit from peak data
Usage graph high, no kills Working set vs usage comparison Page cache counted in usage Alert on working set, leave cache alone
Alert fires on every deploy Expression without for duration Rollout noise crossing the threshold Add for, raise threshold above rollout noise
Query returns empty Both sides of the division separately Label mismatch or missing metric name Align label sets, confirm metric exists in the UI
Restart alert silent in a crash loop increase window check Window too short or threshold too high Widen window, lower threshold, check KSM scraping
Prometheus slow after a deploy prometheustsdbhead_series New high-cardinality label Drop the label at scrape or in the rule
Pods Pending after a resize Phase count + request totals Requests exceed node capacity Add capacity or reduce requests from usage data

Production checklist

  • Counters use rate or increase; gauges use comparisons or over_time functions; nothing graphs a raw counter.
  • Throttling alerts use the throttled-period ratio, with thresholds set from latency data rather than copied numbers.
  • Memory alerts use working set over the limit, plus a gated predict_linear ticket for slow leaks.
  • Restart alerts count increase over a window and link to the terminated-reason runbook.
  • Pending Pod alerts carry a for duration that outlasts a normal rollout.
  • Recording rules precompute the ratios, keep namespace, pod and container labels, and follow the level:metric:operations naming convention.
  • Every alert has a severity that maps to a response expectation, and annotations that name the failing container.
  • Label sets stay bounded; no user IDs, request IDs or full URLs in metrics; head series count is graphed.
  • Each alert expression has been run against last week's data and observed firing only when intended.

The through-line of this lesson is that PromQL for Kubernetes rewards precision about units. Cores, ratios, counts per window and headroom fractions each answer one question well and the others badly. Get the units right, give alerts time to be sure, and the same Prometheus that produced calm graphs during the composite incident in the introduction starts naming the failing container within minutes. From here, Module 11 on Kubernetes autoscaling builds on these signals, because autoscaling decisions are only as good as the queries feeding them.

Frequently Asked Questions

What is the best PromQL for Kubernetes CPU throttling alerts?

Use the throttled-period ratio: rate(containercpucfsthrottledperiodstotal[5m]) divided by rate(containercpucfsperiods_total[5m]), grouped by namespace, pod and container. Alert when the ratio stays above roughly 0.1 to 0.25 for ten minutes on user-facing services. The ratio shows how often the kernel stopped the container, which tracks latency impact better than average CPU.

How do I count Pod restarts with PromQL for Kubernetes?

Use increase(kubepodcontainerstatusrestartstotal[15m]) and alert above 3 for a crash loop, or use a 6 hour window above 5 for slow flapping. increase handles counter resets when kube-state-metrics restarts. Follow up with kubepodcontainerstatuslastterminated_reason to learn whether the cause was OOMKilled, an error exit, or a probe failure.

What is the difference between working set and RSS in PromQL for Kubernetes?

Working set estimates memory the kernel cannot reclaim quickly and drives eviction decisions, so it belongs in headroom alerts against the limit. RSS counts resident pages held by the processes themselves and suits leak hunting. Cache counts reclaimable file pages. Alert on working set, explain with RSS and cache.

Should I use rate or increase in PromQL for Kubernetes alerts?

Use rate when the unit is per second, such as CPU cores or throttled seconds per second. Use increase when the unit is a count inside a window, such as restarts in an hour. Both handle counter resets. Never apply either to a gauge such as memory bytes; compare gauges directly or use maxovertime.

How long should the for duration be in PromQL for Kubernetes alerts?

Match the duration to the failure speed. Five minutes suits crash loops, ten minutes suits throttling, and fifteen minutes suits memory headroom and Pending Pods. The duration must outlast rollout noise and stay shorter than the time users tolerate the failure. Test the alert against last week's data before trusting it.

How do recording rules help PromQL for Kubernetes performance?

A recording rule evaluates an expensive expression on a schedule and stores the result as one series, so dashboards and alerts read the finished ratio instead of recomputing divisions across thousands of raw series. Record re-aggregatable per-container ratios with namespace, pod and container labels, and name them with the level:metric:operations convention.

How do I find Pending Pods with PromQL for Kubernetes?

Sum kubepodstatus_phase{phase="Pending"} by namespace, and alert when the count stays above zero for fifteen minutes. Brief Pending spikes during rollouts are normal. Sustained Pending usually means requests that fit on no node, an untolerated taint, or a volume that will not bind.

⚡ KUBERNETES SCENARIO INTERVIEW PREP

Preparing for Senior Platform & SRE Interviews

Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.

Explore Interview Scenarios →