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 always100000(100ms).container_spec_cpu_quota- how many microseconds of CPU time the container is allowed percontainer_spec_cpu_periodwindow, derived fromresources.limits.cpuon 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.5cores
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.)