What is OpenCost and how does it allocate Kubernetes costs?
OpenCost is an open-source, vendor-neutral cost allocation engine for Kubernetes and a CNCF project. It does not collect metrics itself. It combines two inputs and computes cost from them:
- Resource data from Prometheus. This includes container resource requests and observed usage for CPU, memory, and GPU, plus persistent volume claims and the nodes they run on. These metrics typically come from kube-state-metrics and cAdvisor.
- Prices. These come from a cloud provider's public pricing data or, for on-prem or negotiated rates, a custom price sheet you supply. OpenCost breaks each node's hourly cost into per-unit rates: per vCPU-hour, per GB-hour of RAM, and per GPU-hour. Storage is priced per GB-hour.
OpenCost then attributes those costs to containers. It rolls them up to pods, controllers, and namespaces, which is what makes namespace cost allocation possible.
The max(request, usage) rule
For each resource and time window, a container is charged for whichever is larger: what it requested or what it used. Requests reserve capacity on the node, and the scheduler won't place other pods into that capacity even if it sits unused. Inflated requests therefore show up as real cost, even when the workload is idle.
Illustrative estimate (assumed numbers, not a benchmark): Assume a CPU price of $0.03 per vCPU-hour and a container that requests 2 vCPU while using 0.5 vCPU, over 730 hours.
Cost = max(request, usage) × price × hours = max(2, 0.5) × $0.03 × 730 = $43.80/month
Billed on usage alone, the same container would cost $10.95.
OpenCost reports on one cluster per installation. Comparing costs across clusters means running an instance in each cluster and aggregating the results yourself.
+------------------+ +------------+ +---------------------+
| kube-state- | | cAdvisor | | Pricing source |
| metrics | | | | public cloud prices |
+--------+---------+ +-----+------+ | or custom sheet |
| | +----------+----------+
v v |
+------------------------------------+ |
| Prometheus | |
| requests + usage: CPU, memory, GPU | |
| persistent volume claims, nodes | |
+-----------------+------------------+ |
| |
v v
+--------------------------------------------------------------------+
| OpenCost (one install = one cluster) |
| node $/hr -> $/vCPU-hr, $/GB-hr RAM, $/GPU-hr; storage $/GB-hr |
| charge = max(request, usage) x price x hours |
+---------------------------------+----------------------------------+
|
v
+-------------------------------------------------+
| containers -> pods -> controllers -> namespaces |
+-------------------------------------------------+
OpenCost combines Prometheus resource data with node prices from a cloud pricing source or custom price sheet. It charges each container max(request, usage) and rolls the cost up to namespaces, with one installation per cluster.
Who should use OpenCost, and when should you avoid it?
OpenCost earns its keep on shared, multi-tenant clusters. If a platform team runs one cluster for several product teams, someone eventually asks which team drove last month's bill. Namespace cost allocation gives that question a defensible answer, first as showback (reporting) and later as chargeback (billing teams internally). A practical trigger for adoption is when several teams share a cluster and spend questions keep coming up in planning or incident reviews.
Defer it in three cases:
- Very small clusters. OpenCost depends on Prometheus. On a handful of nodes, running and maintaining that stack can cost more in compute and attention than the visibility is worth.
- Spend that is mostly outside the cluster. Managed databases, load balancers and egress often dominate the bill. Namespace allocation covers only part of it.
- Invoice-exact requirements. OpenCost estimates costs from usage and pricing data. Matching your cloud invoice to the cent requires reconciliation work. If finance won't accept estimates, plan for that work or choose another approach.
| Option | Accuracy | Effort | Multi-cluster |
|---|---|---|---|
| OpenCost | Good estimates for in-cluster costs | Moderate: Prometheus plus OpenCost | One install per cluster; you aggregate the results |
| Kubecost | Similar in-cluster model, with more reconciliation features | Lower if you accept a commercial product | Built-in aggregation in paid tiers |
| Cloud billing export with tags | Invoice-exact, but only as granular as your tags | Tagging discipline across teams | Native across accounts |
| Hand-built Prometheus queries | Only as good as your pricing inputs | High to build and maintain | Whatever you build yourself |
How do you install OpenCost and verify cost data?
OpenCost does not collect metrics itself. It reads them from Prometheus, so Prometheus has to be in place first. You can reuse an existing instance or install one alongside OpenCost. Either way, confirm it scrapes three sources:
- cAdvisor (through the kubelet), for container CPU and memory usage.
- kube-state-metrics, for pod resource requests, ownership, and namespace labels.
- OpenCost's own metrics endpoint, which exposes node and resource pricing.
If any of these is missing, allocations come back as zero or partial. They do not fail with an error, so check the scrape targets before you install.
Storage and retention
Give Prometheus a persistent volume and set retention based on how far back your reports need to look. Prometheus's default retention is 15 days, which is too short for month-over-month comparisons. Storage grows with series count and retention, so size the volume for both.
Install
Install OpenCost with the project's Helm chart. In your values file, set the Prometheus service address, namespace, and port, plus any authentication. Point it directly at the in-cluster service rather than through an ingress, which adds latency and more ways for the connection to fail.
Verify before trusting the numbers
Port-forward the OpenCost service with kubectl port-forward. Then query the allocation API over a short window aggregated by namespace, for example /allocation/compute?window=1h&aggregate=namespace. Check three things:
- Every active namespace appears.
- CPU and memory costs are non-zero.
- Totals roughly match your node count multiplied by node price.
Gaps in history
OpenCost calculates costs from whatever Prometheus still holds. If Prometheus restarts without persistent storage, or data ages out of retention, that cost history is gone and cannot be recomputed later. Treat any gaps in Prometheus data as gaps in your cost reports.
# Assumes the OpenCost chart repo is already added locally as 'opencost'
# and Prometheus runs in the 'monitoring' namespace (placeholder names).
# 1. Confirm Prometheus scrape targets are healthy before installing.
kubectl -n monitoring port-forward svc/prometheus-server 9090:80 &
sleep 3
curl -s localhost:9090/api/v1/targets \
| jq -r '.data.activeTargets[] | "\(.labels.job)\t\(.health)"' | sort -u
# 2. Install OpenCost and point it at the in-cluster Prometheus service,
# not an ingress.
helm install opencost opencost/opencost \
--namespace opencost --create-namespace \
--set opencost.prometheus.internal.enabled=true \
--set opencost.prometheus.internal.serviceName=prometheus-server \
--set opencost.prometheus.internal.namespaceName=monitoring \
--set opencost.prometheus.internal.port=80
kubectl -n opencost rollout status deploy/opencost
# 3. Port-forward the OpenCost API (port 9003) and query a short window.
kubectl -n opencost port-forward svc/opencost 9003:9003 &
sleep 3
# Expect every active namespace, with non-zero CPU and RAM cost.
curl -s 'localhost:9003/allocation/compute?window=1h&aggregate=namespace' \
| jq -r '.data[0] | to_entries[]
| "\(.key)\tcpu=\(.value.cpuCost)\tram=\(.value.ramCost)\ttotal=\(.value.totalCost)"'
# Stop the background port-forwards when done.
kill %1 %2
Checking Prometheus scrape targets, installing OpenCost with Helm against the in-cluster Prometheus service, and confirming per-namespace allocation data over a one-hour window.
How do you build a per-namespace cost report?
Start from the data you trust, then query it. The OpenCost UI is fine for a quick look. For reports you can reproduce, call the allocation API directly: request /allocation/compute with an explicit window such as 7d or a fixed start and end timestamp, and aggregate=namespace. Relative windows like "last week" shift every time someone reruns the report. Fixed timestamps let finance and engineering compare the same numbers.
Each namespace in the response carries separate line items: cpuCost, ramCost, pvCost, gpuCost, and networkCost, along with totalCost. Look at the breakdown, not only the total, because each line item points to a different fix. High CPU cost with low CPU efficiency usually means requests are set too high. A large pvCost often comes from orphaned volumes. A networkCost near zero may mean network cost collection isn't configured, so don't read it as free traffic.
Namespaces rarely map cleanly to teams. One team may own several namespaces, or several teams may share one. In those cases, aggregate by label instead, for example aggregate=label:team or label:cost-center. Workloads without the label land in __unallocated__. If you don't enforce the label, that bucket grows without anyone noticing. Require the label with a validating admission policy or a CI check on manifests, and track the size of __unallocated__ as a metric of its own.
Labels also cost something. kube-state-metrics only exports the pod labels you allowlist. Every allowlisted label with many distinct values multiplies the Prometheus series count. Allowlist a small set of stable values such as team names. Never allowlist per-deploy values like commit SHAs.
#!/usr/bin/env bash
set -euo pipefail
# Reach the OpenCost API locally. Service name and namespace assume a default install.
kubectl -n opencost port-forward service/opencost 9003:9003 >/dev/null 2>&1 &
PF_PID=$!
trap 'kill $PF_PID' EXIT
sleep 3
# Fixed RFC3339 window so reruns return the same numbers for finance and engineering.
WINDOW="2026-11-01T00:00:00Z,2026-11-08T00:00:00Z"
API=""
# Per-namespace breakdown. accumulate=true collapses the window into one set.
# Print line items, not only the total, because each one points to a different fix.
curl -sG "$API" \
--data-urlencode "window=$WINDOW" \
--data-urlencode "aggregate=namespace" \
--data-urlencode "accumulate=true" |
jq -r '.data[0] | to_entries[] | .value |
[.name, .cpuCost, .ramCost, .pvCost, .gpuCost, .networkCost, .totalCost, .cpuEfficiency]
| @tsv' |
column -t -N NAMESPACE,CPU,RAM,PV,GPU,NETWORK,TOTAL,CPU_EFF
# Team view for namespaces that don't map one-to-one to teams.
# Workloads missing the label land in __unallocated__; track its share over time.
curl -sG "$API" \
--data-urlencode "window=$WINDOW" \
--data-urlencode "aggregate=label:team" \
--data-urlencode "accumulate=true" |
jq -r '.data[0] as $s
| ([$s[].totalCost] | add) as $all
| ($s["__unallocated__"].totalCost // 0) as $un
| "unallocated: \($un) of \($all) (\(if $all > 0 then ($un / $all * 100 | floor) else 0 end)%)"'
A bash script that queries the OpenCost allocation API over a fixed time window, prints per-namespace CPU, RAM, PV, GPU and network costs, then aggregates by a team label and reports what share of spend falls into unallocated.
How should you handle idle capacity, shared namespaces, and pricing accuracy?
Those label choices decide which dimensions you can slice by. The policy choices below decide whether the numbers hold up when a team disputes its line item.
Idle capacity
Unallocated node capacity is real spend. Show it as its own line rather than spreading it across tenants. A visible idle line shows the platform team how much it has over-provisioned. Spreading idle cost proportionally hides that waste, and it charges teams for headroom they never requested.
Shared namespaces
Workloads in kube-system, monitoring, and ingress serve every tenant. Split them in proportion to each namespace's share of allocated cost. A flat even split overcharges small teams.
Requests versus usage
| Basis | Behaviour | Trade-off |
|---|---|---|
| Requests (or max of request and usage) | Charges what the scheduler reserved | Matches what drives node count; penalises padded requests |
| Usage only | Charges actual consumption | Bursty workloads look cheap, while their reserved headroom lands in idle |
Requests-based charging rewards right-sizing, which is usually the behaviour you want.
Pricing accuracy
By default, OpenCost prices resources at on-demand list rates. Your actual bill reflects reserved capacity, savings plans, spot discounts, and negotiated rates, so it is often lower. For on-prem or negotiated-rate clusters, supply custom per-unit prices for CPU, memory, GPU, and storage. Treat the report as accurate for relative comparisons between teams. Reconcile it against the cloud billing export monthly, and again before any figure feeds a chargeback invoice.
Write these policies down. Get finance and team leads to agree on them before the first report ships.
How can you automate weekly namespace spend reports?
Once those policies are agreed, encode them in a scheduled job. A Kubernetes CronJob that runs every Monday morning can call the OpenCost allocation API with a seven-day window aggregated by namespace, then write the results to a CSV in object storage or post a summary to a team channel. Run it under a dedicated service account with read-only network access to the OpenCost service.
Report week-over-week change for each namespace alongside the absolute cost. A namespace that costs a lot every week is usually already known and budgeted. A namespace whose spend jumps between weeks usually points to something that just changed, such as a new deployment, a runaway HPA, or a forgotten load test. Sort the summary by percentage change and flag anything above an agreed threshold.
The exports also fix two structural limits. Prometheus retention is often only a few weeks, so the history behind OpenCost's numbers expires. Weekly CSVs keep a durable record that you can query long after the metrics are gone. Each OpenCost instance also sees only its own cluster. If every cluster writes files with the same schema to one bucket and adds a cluster column, you can aggregate them with any SQL engine or spreadsheet.
Illustrative estimate (assumed numbers, not a benchmark): Hours saved per month = (investigations × hours each) − maintenance hours. Assume 4 ad hoc "why did the bill go up?" investigations at 3 hours each, and 1 hour of upkeep for the job: (4 × 3) − 1 = 11 engineer-hours per month.
apiVersion: batch/v1
kind: CronJob
metadata:
name: namespace-spend-report
namespace: opencost
spec:
schedule: "0 7 * * 1" # every Monday 07:00, cluster time zone
concurrencyPolicy: Forbid
jobTemplate:
spec:
template:
spec:
serviceAccountName: spend-reporter # dedicated SA, no RBAC needed
restartPolicy: OnFailure
containers:
- name: report
image: registry.example.com/tools/curl-jq:1.0 # any image with sh, curl, jq, awk
env:
- { name: CLUSTER, value: prod-eu-1 } # same schema across clusters
command: ["/bin/sh", "-c"]
args:
- |
set -eu
cd /reports; NOW=$(date +%Y-%m-%d)
# One accumulated 7-day window, aggregated by namespace
curl -sf "" \
| jq -r --arg c "$CLUSTER" '.data[0] | to_entries[] | "\($c),\(.key),\(.value.totalCost)"' > current.csv
[ -s last.csv ] || cp current.csv last.csv # first run: 0% change
# Join on namespace, add week-over-week %, sort biggest jump first
{ echo "cluster,namespace,cost,wow_pct"
awk -F, 'NR==FNR{p[$2]=$3;next}{d=(p[$2]>0)?($3-p[$2])/p[$2]*100:100
printf "%s,%s,%.2f,%.1f\n",$1,$2,$3,d}' last.csv current.csv | sort -t, -k4 -gr
} > "$CLUSTER-$NOW.csv"
mv current.csv last.csv # baseline for next week
volumeMounts:
- { name: reports, mountPath: /reports }
volumes:
- name: reports
persistentVolumeClaim:
claimName: spend-reports # sync this to object storage separately
A weekly Kubernetes CronJob that queries the OpenCost allocation API for a 7-day namespace window and writes a per-cluster CSV with absolute cost and week-over-week percentage change, sorted by the largest jump.
How do namespace cost reports reduce cloud and development costs?
The time saved on investigations is minor compared with what the report shows about requests. OpenCost charges each workload for the greater of its requested and used CPU and memory. When a namespace requests much more than it uses, it pays for the reserved capacity, and other workloads cannot use it. The size of that request-versus-usage gap tells you where rightsizing will save the most.
Illustrative estimate (assumed numbers, not a benchmark). Assume $0.04 per vCPU-hour, a 730-hour month, and requests rightsized to observed peak usage plus headroom.
Monthly CPU cost = max(requested vCPU, used vCPU) × 730 × $0.04
| Namespace | Requested vCPU | Peak used vCPU | Cost now | Rightsized request | Cost after |
|---|---|---|---|---|---|
checkout |
8 | 2 | $233.60 | 3 | $87.60 |
dev-sandbox |
6 | 0.5 | $175.20 | 1 | $29.20 |
The allocated cost falls by $292 a month. Your cloud bill only falls if the cluster autoscaler can then pack the workloads onto fewer nodes. Otherwise the freed capacity shows up as idle cost.
Development and staging namespaces often have the largest gaps. They copy production requests, run around the clock, and have no owner watching their cost. Once the weekly report shows them, teams have a reason to scale them to zero overnight and set expiry times on preview environments.
The report still misses part of the bill. Egress traffic, load balancers, and managed databases or queues are billed outside the cluster's node costs. Reconcile those against your cloud invoice separately.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to opencost kubernetes, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.