loc bengaluru, ist | local --:-- srijanshukla18@gmail.com →
[post]/tech/cpu-usage-at-pod-level-in-k8s

CPU usage at pod level in k8s

/ 3 min read· infra

How is pod level CPU usage metric calculated in k8s? How is pod level CPU usage metric calculated in k8s? The common PromQL query found on the internet may...

Published: Dec 2019

How is pod-level CPU usage % calculated in k8s?

If you google for a PromQL query to get pod CPU utilization against its limit, you’ll usually find something like this,

sum(rate(container_cpu_usage_seconds_total{name!~".*prometheus.*", image!="", container_name!="POD"}[5m])) by (pod_name, namespace) /
sum(container_spec_cpu_quota{name!~".*prometheus.*", image!="", container_name!="POD"}/container_spec_cpu_period{name!~".*prometheus.*", image!="", container_name!="POD"}) by (pod_name, namespace)

Looks ugly at first glance. There are really just three cAdvisor metrics in there:

  • container_cpu_usage_seconds_total - counter of total CPU seconds consumed by the container since start.
  • container_spec_cpu_period - the CFS (Completely Fair Scheduler) time window in microseconds. Almost always 100000 (100ms).
  • container_spec_cpu_quota - how many microseconds of CPU time the container is allowed per container_spec_cpu_period window, derived from resources.limits.cpu on the pod.

Why divide quota by period in the denominator? Because that gives you the container’s CPU limit in cores.

Say you set limits.cpu: 500m (0.5 cores):

  • container_spec_cpu_period = 100,000 (100ms)
  • container_spec_cpu_quota = 50,000 (50ms)
  • quota / period = 50000 / 100000 = 0.5 cores

And for the numerator: container_cpu_usage_seconds_total is a cumulative counter of CPU seconds used, so rate(container_cpu_usage_seconds_total[5m]) gives you CPU seconds burned per second over the last 5 minutes - which is literally how many cores it’s using right now.

So the whole thing is just:

CPU utilization ratio = (cores currently used) / (cores allowed by limit)
                      = rate(container_cpu_usage_seconds_total[5m]) / (container_spec_cpu_quota / container_spec_cpu_period)

Wrap both sides in sum(...) by (pod) (filtering out the pause container container_name!="POD" and empty image!="" cgroup slices) to aggregate across all containers in the pod:

sum(rate(container_cpu_usage_seconds_total{name!~".*prometheus.*", image!="", container_name!="POD"}[5m])) by (pod)
/
sum(container_spec_cpu_quota{name!~".*prometheus.*", image!="", container_name!="POD"}/container_spec_cpu_period{name!~".*prometheus.*", image!="", container_name!="POD"}) by (pod)

(Side note: on newer kubelet/cAdvisor versions the labels are pod and container instead of pod_name and container_name, and kube-state-metrics exposes kube_pod_container_resource_limits{resource="cpu"} which is way cleaner for the denominator than quota / period.)