Kubernetes cost management is an allocation problem, not a billing problem. Your cluster costs what it costs; the real question is which namespace, workload, or label owns which slice of the bill, calculated straight from requests, usage, and time out of the Prometheus metrics you already scrape.
make up obsOrientation
Section 1.2 gave you the measurement toolkit. Here we attach dollars to it and close the right-sizing loop: measure real usage, compare it against requests, adjust the numbers, and confirm nothing broke. That loop IS the competency; OpenCost is simply the lens.
For each container over a time window: cost = max(request, usage) × unit_price × hours, summed across CPU, memory, GPU, storage, and network, then rolled up by namespace, label, or controller. Everything in OpenCost is just a different slice of that formula. That's why an idle namespace can still top your cost chart: request won the max().
What actually drives spend, in priority order
- Requests, not live usage. Schedulers and cost tools bill you for what you reserved. A Deployment requesting 4 CPU while burning 200m still locks up and costs 4 CPU. OpenCost expresses that ratio as efficiency, and closing the gap is right-sizing.
- Idle node capacity. You buy nodes whole, so unrequested space on a node is idle spend. OpenCost can either break idle out as its own
__idle__row or distribute it across tenants. Know both options: separating idle holds the platform team accountable for bin-packing, while sharing idle makes tenants feel the real cost of the cluster they share. Neither is wrong; they answer different organizational questions. - Object sprawl. Cloud LoadBalancers, PVs, snapshots, forgotten namespaces, and orphaned PVCs rack up charges even with zero traffic. That's why
team-acapsservices.loadbalancersat 1. - Node sizing and lifecycle. One layer above your pods: right-sized instance families, spot/preemptible pools, node consolidation (Karpenter), and scaling dev environments down to zero overnight. We can't demo cloud billing in kind, but always state the order clearly: right-size the pods first, then right-size the nodes.
See that request-vs-usage gap priced out in real time. Drag the sliders and notice how fast trimming turns risky once usage crowds your request:
Showback shares cost visibility with teams; chargeback actually bills their budget. Allocation splits shared spend along a defensible key (namespace, label, owner). Efficiency is usage ÷ billed allocation. Unit economics ties infrastructure spend to a business unit (cost per tenant or per request). Whenever a prompt asks how to cut costs, start with allocation: you can't optimize spend you can't attribute.
The FinOps loop, mapped to cluster layers
FinOps breaks the cycle into Inform (allocate and surface costs), Optimize (right-size, commit, clean up), and Operate (bake budgets and alerts into daily ops). Map those onto Kubernetes layers and you have a rock-solid answer to any "reduce this cluster's spend" prompt:
| Layer | Waste looks like | Lever | Where to read it |
|---|---|---|---|
| Container | efficiency way below 1 | VPA recommendations: status.recommendation.containerRecommendations[].target (plus lowerBound, upperBound, uncappedTarget); use resourcePolicy.containerPolicies to clamp bounds or set mode: Off per container | kubectl cost ... --show-efficiency, VPA status |
| Namespace | bloated quotas, idle LoadBalancers, retained PVs | quotas as spend caps, services.loadbalancers, per-class storage quota, Job TTLs | aggregate=namespace, kubectl get pvc -A |
| Node | high __idle__, nodes below 50% requested | consolidation (Karpenter WhenEmptyOrUnderutilized, CA scale-down), better instance families, leaner DaemonSets | includeIdle=true, idleByNode=true |
| Purchase | on-demand nodes running interruptible batch work | tainted spot/preemptible pools with PDBs for stateless apps; savings plans for steady baseline | spot pricing in price list; cloud billing export |
Showback covers the Inform phase for app teams; chargeback plugs those numbers into real budgets. Remember section 3.1's maturity model: teams willingly paying for platform capabilities through chargeback is a Scalable-level signal, so a prompt mentioning chargeback often touches organizational maturity as much as OpenCost itself.
How OpenCost works under the hood
OpenCost is a lightweight controller paired with a query API. It pulls pod and node inventory from the API server, joins it against Prometheus usage series (container_cpu_usage_seconds_total, container_memory_working_set_bytes, kube_pod_container_resource_requests, and node capacity), and multiplies by a price sheet (cloud billing rates in production, default on-prem rates in our lab). Don't worry about the lab's synthetic dollar amounts; the ratios and efficiency gaps are completely real.
kube-state-metrics ─┐
cadvisor / kubelet ─┼─▶ Prometheus ─▶ OpenCost ─▶ allocation API ─▶ kubectl cost / UI / Grafana
node inventory ─┘ ▲
price list (cloud rates or defaults)
Two things to keep in mind before running queries. First, OpenCost is only as accurate as its Prometheus scrapes: a broken scrape produces silent zero-dollar rows rather than a loud error, so debugging a missing namespace starts in Prometheus, not OpenCost. Second, pick an appropriate window: a 1-hour lookback over a brand-new workload tells you very little, so default to --window 1d for steadier numbers.
kubectl cost targets Kubecost by default. Pass --opencost so it switches to OpenCost's service name, port, and API path automatically. Leave it off and you'll get a connection error that makes OpenCost look down when you were just knocking on the wrong door.
The right-sizing loop (exam-ready version)
- Measure: pull actual usage from
kubectl top, Prometheus, or VPA recommendations (1.2). - Compare: stack requests against ~p95 usage per container; never hide outliers inside a namespace average.
- Adjust: update via
kubectl set resourcesor Git manifests (size memory around peak plus headroom; set sensible CPU requests with generous or omitted CPU limits). - Verify: confirm zero CPU throttling spikes, zero OOMKills, zero Pending pods, and a visibly higher efficiency score.
Step 4 is where candidates earn full credit. Slashing requests until pods throttle or OOM isn't optimization. Always include verification in your answer.
The allocation API and its parameters
The OpenCost UI, Grafana panels, and kubectl cost all hit the exact same HTTP endpoint on port 9003 (the UI runs as a companion container on port 9090). Knowing the raw query parameters lets you pull answers with curl even when the CLI plugin isn't installed.
GET /allocation
| Parameter | Values | Why it matters |
|---|---|---|
| window | today, yesterday, week, lastweek, month, 30m, 12h, 7d, RFC3339 pair, unix pair | required; make sure the window covers the workload's lifetime; wider windows smooth out short spikes |
| aggregate | cluster, node, namespace, controllerKind, controller, service, pod, container, label:<key>, annotation:<key>; comma lists | groups spend by your chosen key; aggregate=label:team delivers team showback even across shared namespaces |
| step | 1h, 1d, ... | breaks the window into a time series instead of one aggregate bucket |
| resolution | 1m default, 30m | Prometheus query step; coarser runs faster but can miss short-lived pods |
| includeIdle | true/false | adds an __idle__ row for unrequested node capacity |
| shareIdle | true/false | folds idle spend into the remaining rows proportionally per resource |
| idleByNode | true/false | calculates idle per node rather than cluster-wide |
Every returned row carries cpuCost, ramCost, gpuCost, pvCost, networkCost, loadBalancerCost, sharedCost, and totalCost, plus cpuEfficiency, ramEfficiency, and totalEfficiency (usage divided by billed max(request, usage), so anything over 1.0 means the container is under-requested). Under the hood, kubectl cost namespace --opencost expands to --service-port 9003 --service-name opencost --kubecost-namespace opencost --allocation-path /allocation/compute; subcommands like namespace, deployment, controller, label, pod, and node map straight to aggregate; and output defaults to a projected monthly rate unless you pass --historical for the window total.
Where pricing comes from
- Cloud clusters: pulls on-demand list prices from the cloud provider's pricing API using each node's
providerID, instance type, and region; spot nodes get spot pricing when labeled (such as Karpenter'skarpenter.sh/capacity-type: spot). Real negotiated discounts and invoices come in only when you wire up a cloud billing export. - On-prem or kind: nodes without a cloud
providerIDfall back to thecustomprovider anddefault.json(CPU 0.031611/core-hour, RAM 0.004237/GB-hour, GPU 0.95/hour, storage 0.00005479452/GB-hour, spot CPU 0.006655, modeled on GCP us-central1). Override these via the custom pricing ConfigMap or HelmcustomPricingvalues whenever a prompt hands you custom rates; only the currency totals shift, never the relative ratios.
Spec definitions scenarios quote
- Total cluster cost = cluster asset costs (nodes, PVs, attached disks, load balancers, network) + cluster overhead (control plane management fees).
- Workload cost =
max(request, usage)for compute (CPU, GPU, RAM), PVC capacity for storage, and bytes for network, computed per container and rolled up by your aggregation key. - Idle cost = asset cost minus workload cost (idle % = idle ÷ allocation costs). Show it on its own row or spread it evenly, proportionally to spend, or by custom metric.
- Shared costs: platform namespaces like
kube-systemandmonitoring, distributed using the same three options to turn basic showback into fair chargeback. - Pods stuck in
ImagePullBackOffaren't billed even though they hold requests;Pendingpods hold nothing.
If a namespace with healthy running pods prints $0, OpenCost couldn't join its Prometheus metrics. Check PROMETHEUS_SERVER_ENDPOINT on the opencost Deployment, verify kube-state-metrics and cAdvisor targets are UP, and widen your query window. On sharded Prometheus setups, point OpenCost at the global query layer (Thanos Query or Mimir), never a single shard.
Exercises
OpenCost's UI is on the LoadBalancer make urls prints, but the CLI is faster and closer to what the exam asks:
kubectl cost namespace --opencost --show-all-resources
kubectl cost namespace --opencost --historical --window 1doutputcaptured 2026-08-26
$ kubectl cost namespace --opencost --show-all-resources
+-----------------+-------------------------------+--------------------+-----------------+
| CLUSTER | NAMESPACE | MONTHLY RATE (ALL) | COST EFFICIENCY |
+-----------------+-------------------------------+--------------------+-----------------+
| default-cluster | kube-system | 22.934101 | 0.673952 |
| | flux-system | 13.663152 | 0.062010 |
| | kyverno | 10.060340 | 0.111306 |
| | gatekeeper-system | 7.597615 | 0.166510 |
| | vpa | 6.984870 | 0.049210 |
| | kro | 6.205071 | 0.077431 |
| | crossplane-system | 6.078437 | 0.413770 |
| | team-b | 6.060347 | 0.015395 |
| | team-a | 3.981019 | 0.053393 |
| | tracing | 3.032553 | 0.100108 |
| | tekton-pipelines | 2.572672 | 0.469501 |
| | tekton-pipelines-resolvers | 2.572672 | 0.036930 |
| | flux-demo | 1.388055 | 0.101211 |
| | trivy-system | 1.186362 | 1.102488 |
| | opencost | 0.779983 | 0.384823 |
| | monitoring | 0.111300 | 2.162723 |
| | default | 0.018600 | 0.930326 |
| | local-path-storage | 0.000000 | 0.000000 |
| | spire | 0.000000 | 0.000000 |
| | argo-rollouts | 0.000000 | 0.000000 |
| | argocd | 0.000000 | 0.000000 |
| __idle__ | __idle__ | 0.000000 | 0.000000 |
| default-cluster | cnpg-system | 0.000000 | 0.000000 |
| | external-secrets | 0.000000 | 0.000000 |
| | argo | 0.000000 | 0.000000 |
| | opentelemetry-operator-system | 0.000000 | 0.000000 |
+-----------------+-------------------------------+--------------------+-----------------+
| SUMMED | | 95.227148 | |
+-----------------+-------------------------------+--------------------+-----------------+
$ kubectl cost namespace --opencost --historical --window 1d
+-----------------+-------------------------------+------------------+-----------------+
| CLUSTER | NAMESPACE | TOTAL COST (ALL) | COST EFFICIENCY |
+-----------------+-------------------------------+------------------+-----------------+
| default-cluster | kube-system | 0.034410 | 0.673952 |
| | flux-system | 0.020500 | 0.062010 |
| | kyverno | 0.013930 | 0.111306 |
| | gatekeeper-system | 0.010520 | 0.166510 |
| | vpa | 0.010480 | 0.049210 |
| | kro | 0.009310 | 0.077431 |
| | crossplane-system | 0.009120 | 0.413770 |
| | team-b | 0.007690 | 0.015395 |
| | tracing | 0.004560 | 0.099890 |
| | team-a | 0.004130 | 0.053393 |
| | tekton-pipelines | 0.003870 | 0.468298 |
| | tekton-pipelines-resolvers | 0.003870 | 0.036836 |
| | monitoring | 0.003710 | 2.162723 |
| | trivy-system | 0.001780 | 1.102547 |
| | flux-demo | 0.001440 | 0.101211 |
| | opencost | 0.001080 | 0.384823 |
| | default | 0.000620 | 0.930254 |
| | local-path-storage | 0.000000 | 0.000000 |
| | external-secrets | 0.000000 | 0.000000 |
| | argo | 0.000000 | 0.000000 |
| __idle__ | __idle__ | 0.000000 | 0.000000 |
| default-cluster | cnpg-system | 0.000000 | 0.000000 |
| | argocd | 0.000000 | 0.000000 |
| | spire | 0.000000 | 0.000000 |
| | opentelemetry-operator-system | 0.000000 | 0.000000 |
| | argo-rollouts | 0.000000 | 0.000000 |
+-----------------+-------------------------------+------------------+-----------------+
| SUMMED | | 0.141020 | |
+-----------------+-------------------------------+------------------+-----------------+monitoring lands before looking: kube-prometheus-stack is the heaviest thing installed, yet it sets almost no requests, so max(request, usage) prices it near the bottom with an efficiency above 1. The namespaces that dominate are the ones full of idle requests. If the command errors instead, diagnose the path: kubectl-cost talks to the opencost service, which talks to Prometheus; kubectl -n opencost get deploy,svc and the pod logs tell you which hop broke.Two views of the same truth. From cost:
kubectl cost namespace --opencost --show-efficiencyoutputcaptured 2026-08-26
$ kubectl cost namespace --opencost --show-efficiency
+-----------------+-------------------------------+--------------------+-----------------+
| CLUSTER | NAMESPACE | MONTHLY RATE (ALL) | COST EFFICIENCY |
+-----------------+-------------------------------+--------------------+-----------------+
| default-cluster | kube-system | 22.940766 | 0.673763 |
| | flux-system | 13.663152 | 0.062010 |
| | kyverno | 10.060340 | 0.111306 |
| | gatekeeper-system | 7.597615 | 0.166510 |
| | vpa | 6.984870 | 0.049210 |
| | kro | 6.205071 | 0.077431 |
| | crossplane-system | 6.078437 | 0.413770 |
| | team-b | 6.060347 | 0.015396 |
| | team-a | 3.981019 | 0.053393 |
| | tracing | 3.039218 | 0.099890 |
| | tekton-pipelines-resolvers | 2.579337 | 0.036836 |
| | tekton-pipelines | 2.579337 | 0.468298 |
| | flux-demo | 1.388055 | 0.101211 |
| | trivy-system | 1.186362 | 1.102609 |
| | opencost | 0.779983 | 0.384823 |
| | monitoring | 0.111300 | 2.162723 |
| | default | 0.018600 | 0.930178 |
| | argo-rollouts | 0.000000 | 0.000000 |
| __idle__ | __idle__ | 0.000000 | 0.000000 |
| default-cluster | spire | 0.000000 | 0.000000 |
| | opentelemetry-operator-system | 0.000000 | 0.000000 |
| | external-secrets | 0.000000 | 0.000000 |
| | argo | 0.000000 | 0.000000 |
| | local-path-storage | 0.000000 | 0.000000 |
| | argocd | 0.000000 | 0.000000 |
| | cnpg-system | 0.000000 | 0.000000 |
+-----------------+-------------------------------+--------------------+-----------------+
| SUMMED | | 95.253808 | |
+-----------------+-------------------------------+--------------------+-----------------+From raw metrics, CPU requested minus used, per namespace (run in the Prometheus UI from make urls):
sum by (namespace) (kube_pod_container_resource_requests{resource="cpu"})
- sum by (namespace) (rate(container_cpu_usage_seconds_total{container!="",container!="POD"}[10m]))outputcaptured 2026-08-26
$ kubectl -n monitoring port-forward svc/prometheus-operated 9090 & # or open the UI from make urls
$ curl -sG http://localhost:9090/api/v1/query --data-urlencode \
'query=sum by (namespace) (kube_pod_container_resource_requests{resource="cpu"}) - sum by (namespace) (rate(container_cpu_usage_seconds_total{container!="",container!="POD"}[10m]))' \
| jq -r '.data.result[] | [.metric.namespace, .value[1]] | @tsv' | sort -t$'\t' -k2 -rn
flux-system 0.5267671215880919
team-b 0.34988733380995113
kro 0.25387000718459796
kube-system 0.24557372718547377
team-a 0.22489119384540543
crossplane-system 0.185862717786078
gatekeeper-system 0.1480803033971353
vpa 0.146653874778916
tracing 0.09838868995846957
tekton-pipelines-resolvers 0.09818722856439036
tekton-pipelines 0.0866530147060892
flux-demo 0.045067453280133396
trivy-system 0.034891862144704494
opencost 0.017759279317309074
monitoring -0.1752915664261709
kyverno -0.7670737681734979The label filters matter: cadvisor also emits pod-level and node-level aggregate series (empty container) and, on many versions, the pause container as container="POD". Without {container!="",container!="POD"} you count the same CPU two or three times and the gap you compute is wrong.
Deploy the demo app with a deliberate oversize:
kubectl apply -k examples/demo-app/base
kubectl set resources deploy demo --requests=cpu=500m,memory=512Mi --limits=cpu=1,memory=1Gioutputcaptured 2026-08-26
$ kubectl apply -k examples/demo-app/base
service/demo created
deployment.apps/demo created
$ kubectl set resources deploy demo --requests=cpu=500m,memory=512Mi --limits=cpu=1,memory=1Gi
deployment.apps/demo resource requirements updatedWait ten minutes for metrics to accumulate, get the VPA recommendation for it (section 1.2), then apply sane numbers with kubectl set resources again.
kubectl cost namespace --opencost --show-efficiency for default improves between the two states, and the rollout left nothing Pending.Compute the most team-a can cost: its quota hard-caps requests at 2 CPU / 4Gi. That number is a budget expressed in Kubernetes objects. Write the one-sentence explanation of why a platform team sets quotas even when nobody fights over capacity.
The UI is a client of one endpoint. Query it yourself, because the exam question is never "open the dashboard", it is "what does this namespace cost and how much of the cluster is nobody's".
kubectl -n opencost port-forward deploy/opencost 9003:9003 & PF1=$!
sleep 5
curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace -d includeIdle=true | jq '.data[0] | keys'
curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace -d includeIdle=true | jq '.data[0]["__idle__"].totalCost'
kill $PF1outputcaptured 2026-09-12
$ kubectl -n opencost port-forward deploy/opencost 9003:9003 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9003 -> 9003
Forwarding from [::1]:9003 -> 9003
$ curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace -d includeIdle=true | jq '.data[0] | keys'
Handling connection for 9003
[
"__idle__",
"argo",
"argo-rollouts",
"argocd",
"cnpg-system",
"crossplane-system",
"external-secrets",
"flux-demo",
"flux-system",
"gatekeeper-system",
"kro",
"kube-system",
"kyverno",
"local-path-storage",
"monitoring",
"opencost",
"opentelemetry-operator-system",
"payments-dev",
"spire",
"team-a",
"team-b",
"tekton-chains",
"tekton-pipelines",
"tekton-pipelines-resolvers",
"tracing",
"trivy-system",
"vpa"
]
$ curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace -d includeIdle=true | jq '.data[0]["__idle__"].totalCost'
Handling connection for 9003
0
$ kill $PF1__idle__, and on this cluster the __idle__ entry's totalCost is 0. Idle is the cluster capacity no namespace requested, priced from node assets; with the custom price sheet this lab runs there is nothing left over to attribute, so the bucket exists and is empty. How the answer is built is what you are learning, not the number.Namespace is the platform's unit. A label is the product's unit, and the two rarely line up. The same endpoint aggregates by either, and the leftover bucket tells you how much of the cluster is unlabeled.
kubectl -n opencost port-forward deploy/opencost 9003:9003 & PF1=$!
sleep 5
curl -sG localhost:9003/allocation -d window=1d -d aggregate=label:app | jq '.data[0] | keys'
curl -sG localhost:9003/allocation -d window=1d -d aggregate=label:app | jq '.data[0] | map_values(.totalCost)'
kill $PF1outputcaptured 2026-09-12
$ kubectl -n opencost port-forward deploy/opencost 9003:9003 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9003 -> 9003
Forwarding from [::1]:9003 -> 9003
$ curl -sG localhost:9003/allocation -d window=1d -d aggregate=label:app | jq '.data[0] | keys'
Handling connection for 9003
[
"__unallocated__"
]
$ curl -sG localhost:9003/allocation -d window=1d -d aggregate=label:app | jq '.data[0] | map_values(.totalCost)'
Handling connection for 9003
{
"__unallocated__": 0.24568
}
$ kill $PF1__unallocated__ holds everything without the label. If that bucket is the biggest one, your chargeback story is a labeling project, not a cost project.Whether idle is a line item or is spread across tenants is a policy decision with a flag. Run both and watch every tenant's number move.
kubectl -n opencost port-forward deploy/opencost 9003:9003 & PF1=$!
sleep 5
curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace -d includeIdle=true -d shareIdle=false | jq '.data[0] | map_values(.totalCost)'
curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace -d includeIdle=true -d shareIdle=true | jq '.data[0] | map_values(.totalCost)'
kill $PF1outputcaptured 2026-09-12
$ kubectl -n opencost port-forward deploy/opencost 9003:9003 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9003 -> 9003
Forwarding from [::1]:9003 -> 9003
$ curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace -d includeIdle=true -d shareIdle=false | jq '.data[0] | map_values(.totalCost)'
Handling connection for 9003
{
"__idle__": 0,
"argo": 0,
"argo-rollouts": 0,
"argocd": 0,
"cnpg-system": 0,
"crossplane-system": 0.01695,
"external-secrets": 0,
"flux-demo": 0.00002,
"flux-system": 0.0381,
"gatekeeper-system": 0.0212,
"kro": 0.01731,
"kube-system": 0.06396,
"kyverno": 0.02805,
"local-path-storage": 0,
"monitoring": 0.00697,
"opencost": 0.00218,
"opentelemetry-operator-system": 0,
"payments-dev": 0.00741,
"spire": 0,
"team-a": 0.00046,
"team-b": 0.0009,
"tekton-chains": 0,
"tekton-pipelines": 0.00718,
"tekton-pipelines-resolvers": 0.00718,
"tracing": 0.00847,
"trivy-system": 0.00006,
"vpa": 0.01949
}
$ curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace -d includeIdle=true -d shareIdle=true | jq '.data[0] | map_values(.totalCost)'
Handling connection for 9003
{
"argo": 0,
"argo-rollouts": 0,
"argocd": 0,
"cnpg-system": 0,
"crossplane-system": 0.01695,
"external-secrets": 0,
"flux-demo": 0.00002,
"flux-system": 0.0381,
"gatekeeper-system": 0.0212,
"kro": 0.01731,
"kube-system": 0.06396,
"kyverno": 0.02805,
"local-path-storage": 0,
"monitoring": 0.00697,
"opencost": 0.00218,
"opentelemetry-operator-system": 0,
"payments-dev": 0.00741,
"spire": 0,
"team-a": 0.00046,
"team-b": 0.0009,
"tekton-chains": 0,
"tekton-pipelines": 0.00718,
"tekton-pipelines-resolvers": 0.00718,
"tracing": 0.00848,
"trivy-system": 0.00006,
"vpa": 0.01949
}
$ kill $PF1__idle__ key is present under shareIdle=false and gone under shareIdle=true, and every other total is the same to the cent. Idle is zero on this cluster, so there is nothing to spread and the only movement is a sub-cent rounding difference on one namespace. On a cluster with real idle the other totals would rise to absorb it, and the flag would be the whole argument.On-prem there is no cloud bill, so OpenCost costs from a price sheet and a Prometheus endpoint. Both are configuration, and a wrong one makes every number on the page confidently wrong.
kubectl -n opencost get deploy opencost -o jsonpath='{.spec.template.spec.containers[0].env}' | jq '[.[] | {name, value}]'
kubectl -n opencost exec deploy/opencost -- sh -c 'cat /models/default.json 2>/dev/null || ls /models'
kubectl -n opencost get cm -o nameoutputcaptured 2026-09-13
$ kubectl -n opencost get deploy opencost -o jsonpath='{.spec.template.spec.containers[0].env}' | jq '[.[] | {name, value}]'
[
{
"name": "LOG_LEVEL",
"value": "info"
},
{
"name": "CUSTOM_COST_ENABLED",
"value": "false"
},
{
"name": "INSTALL_NAMESPACE",
"value": "opencost"
},
{
"name": "PROMETHEUS_QUERY_RESOLUTION_SECONDS",
"value": "300"
},
{
"name": "API_PORT",
"value": "9003"
},
{
"name": "PROMETHEUS_SERVER_ENDPOINT",
"value": "http://prometheus-kube-prometheus-prometheus.monitoring.svc.cluster.local:9090"
},
{
"name": "INSECURE_SKIP_VERIFY",
"value": "false"
},
{
"name": "CLUSTER_ID",
"value": "default-cluster"
},
{
"name": "RESOLUTION_1D_RETENTION",
"value": "15"
},
{
"name": "RESOLUTION_1H_RETENTION",
"value": "49"
... 38 more lines
$ kubectl -n opencost exec deploy/opencost -- sh -c 'cat /models/default.json 2>/dev/null || ls /models'
Defaulted container "opencost" out of: opencost, opencost-ui
{
"provider": "custom",
"description": "Default prices based on GCP us-central1",
"CPU": "0.031611",
"spotCPU": "0.006655",
"RAM": "0.004237",
"spotRAM": "0.000892",
"GPU": "0.95",
"storage": "0.00005479452",
"zoneNetworkEgress": "0.01",
"regionNetworkEgress": "0.01",
"internetNetworkEgress": "0.12",
"natGatewayEgress": "0.045",
"natGatewayIngress": "0.045"
}
$ kubectl -n opencost get cm -o name
configmap/kube-root-ca.crt
configmap/opencost-ui-nginx-configVPA says what a workload should request. OpenCost says what the gap is costing. Neither is an argument on its own; together they are the right-sizing case you would take to a team. The target, staging-demo in team-a, comes from 2.2's ApplicationSet; before that exists, kubectl apply -k examples/demo-app/overlays/staging creates it.
# make up installs the VPA components but creates no VerticalPodAutoscaler, so there is nothing to read
kubectl apply -f - <<'EOF'
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata: { name: staging-demo, namespace: team-a }
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: staging-demo
updatePolicy: { updateMode: "Off" }
EOF
# the recommender needs a few minutes of history before it will answer
sleep 300
kubectl -n team-a get vpa staging-demo
kubectl -n team-a get vpa staging-demo -o jsonpath='{.status.recommendation.containerRecommendations[0]}' | jq
kubectl -n opencost port-forward deploy/opencost 9003:9003 & PF1=$!
sleep 5
curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace | jq '.data[0]["team-a"] | {cpuCoreRequestAverage, cpuCoreUsageAverage, ramByteRequestAverage, ramByteUsageAverage, totalCost}'
kill $PF1
kubectl -n team-a delete vpa staging-demooutputcaptured 2026-09-13
$ # make up installs the VPA components but creates no VerticalPodAutoscaler, so there is nothing to read
$ kubectl apply -f - <<'EOF'
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata: { name: staging-demo, namespace: team-a }
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: staging-demo
updatePolicy: { updateMode: "Off" }
EOF
verticalpodautoscaler.autoscaling.k8s.io/staging-demo created
$ # the recommender needs a few minutes of history before it will answer
$ sleep 300
$ kubectl -n team-a get vpa staging-demo
NAME MODE CPU MEM PROVIDED AGE
staging-demo Off 15m 100Mi True 5m
$ kubectl -n team-a get vpa staging-demo -o jsonpath='{.status.recommendation.containerRecommendations[0]}' | jq
{
"containerName": "web",
"lowerBound": {
"cpu": "15m",
"memory": "100Mi"
},
"target": {
"cpu": "15m",
"memory": "100Mi"
},
"uncappedTarget": {
"cpu": "15m",
"memory": "100Mi"
},
"upperBound": {
"cpu": "63m",
"memory": "136359041"
}
}
$ kubectl -n opencost port-forward deploy/opencost 9003:9003 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9003 -> 9003
Forwarding from [::1]:9003 -> 9003
$ curl -sG localhost:9003/allocation -d window=1d -d aggregate=namespace | jq '.data[0]["team-a"] | {cpuCoreRequestAverage, cpuCoreUsageAverage, ramByteRequestAverage, ramByteUsageAverage, totalCost}'
Handling connection for 9003
{
"cpuCoreRequestAverage": 0.05253,
"cpuCoreUsageAverage": 0,
"ramByteRequestAverage": 71900157.30178,
"ramByteUsageAverage": 26387597.79358,
"totalCost": 0.04666
}
$ kill $PF1
$ kubectl -n team-a delete vpa staging-demo
verticalpodautoscaler.autoscaling.k8s.io "staging-demo" deleted from team-a namespaceSelf-check
A namespace runs almost no traffic and still tops the cost report. Give the two most likely explanations.
Either oversized requests (since you're billed on reservation, not actual traffic) or pricey attached objects like LoadBalancers, large PVs, or retained snapshots. Check efficiency first: rock-bottom efficiency points straight at requests, while high efficiency paired with high cost points at attached objects.
Why is container!="" in that PromQL query not optional?
cAdvisor emits per-container series alongside pod-level and node-level rollups with an empty container label (and often a pause container labeled container="POD"). Without {container!="",container!="POD"}, your sum double- or triple-counts the exact same CPU.
Should idle cost be spread across tenants or shown separately? Argue both.
Spread across tenants: teams feel the true cost of the cluster they share, discouraging resource hoarding. Shown separately: bin-packing and node choice belong to the platform team, so keeping an explicit __idle__ line drives consolidation. Mature orgs show both: per-tenant request spend plus a platform-owned idle row.
You cut a deployment's CPU request from 500m to 50m and latency degrades. What happened?
CPU requests set the cgroup weight, so under node contention your container suddenly gets a tiny slice of CPU time, and if you tightened the limit alongside it, CFS throttling kicks in hard. Right-sizing targets observed peak usage with headroom, not the flat average. Always validate changes with throttling metrics, not just the cost chart.
Give the four-step right-sizing loop in one breath.
Measure usage → compare against requests → adjust requests → confirm zero degradation (no throttling, OOMs, or Pending pods) and check the new efficiency score. That fourth step is what separates real engineering from blind cost-cutting.
Show cost per team when teams span several namespaces and pods carry a team label. Query?
Hit /allocation?window=7d&aggregate=label:team (or run kubectl cost label --opencost -l team). OpenCost aggregates on any label:<key> or annotation:<key>, and enforcing that label via Kyverno is what keeps your __unallocated__ bucket small.
What does shareIdle=true change in the numbers, and who should want it?
It removes the __idle__ row and redistributes that idle spend across all other rows proportionally to their cost, per resource. Use it when you want tenants to absorb the full cost of the shared cluster; keep includeIdle=true without sharing when the platform team owns bin-packing accountability.
Where do on-prem prices come from, and what is the CPU default?
Nodes without a cloud providerID fall back to the custom provider and OpenCost's default.json: CPU 0.031611/core-hour, RAM 0.004237/GB-hour, GPU 0.95/hour (modeled on GCP us-central1). Override them with a custom pricing ConfigMap or Helm values. Even with notional numbers, the ratios and efficiency scores stay completely valid.
A workload shows totalEfficiency 1.4. Is that good?
No: it means actual usage ran 40% above requests. It looks cheap on paper, but the pod is borrowing headroom from neighbors and sits first in line for OOM eviction under memory pressure. Bump requests closer to observed usage; efficiency near (but just under) 1.0 is the sweet spot.
Docs to know your way around
- opencost.io: the allocation API and the efficiency definition; the "how cost is calculated" page is short and is exactly the formula above.
- github.com/kubecost/kubectl-cost: flag reference; it has more views (controller, deployment, label) than the two used here.
- finops.org: the FinOps framework vocabulary (inform, optimize, operate) if a scenario question uses the words.
- Offline:
kubectl cost --help, and the same Prometheus queries from section 4.1. - opencost.io/docs/integrations/api: the /allocation parameters (window, aggregate, step, resolution, includeIdle, shareIdle, idleByNode) and the response fields; opencost.io/docs/specification for the cost definitions quoted in scenario text.
- github.com/opencost/opencost, configs/default.json: the on-prem default prices; opencost.io/docs/configuration/on-prem for overriding them.
make down-obs