How does Kubernetes cost allocation work in OpenCost and Kubecost?
Kubernetes cost allocation assigns cluster infrastructure spend to the workloads, namespaces and labels that consume it. OpenCost and Kubecost use the same core model. For each pod over a time window, CPU and memory cost is roughly max(request, usage) × per-resource price. The per-resource prices come from splitting each node's price across its CPU and RAM. Persistent volume cost is added, and network cost is included where the environment exposes it.
Taking the maximum is why requests drive most allocated cost. The scheduler reserves requested capacity whether or not the pod uses it, so a team that requests 4 cores and uses 0.5 pays for 4. That incentive is intended, but it cuts both ways. Teams trying to shrink their number may under-request, which leads to CPU throttling, evictions under memory pressure and worse scheduling decisions.
Illustrative estimate (assumed numbers, not a benchmark): assume derived prices of $0.03 per vCPU-hour and $0.004 per GiB-hour. A pod requests 2 vCPU and 4 GiB but uses 0.5 vCPU and 5 GiB. Its cost is (max(2, 0.5) × 0.03) + (max(4, 5) × 0.004) = $0.08/hour.
The result is a modeled figure, not a metered one. On shared nodes, bin-packing gaps, DaemonSets, burstable usage and system overhead all have to be attributed by rule.
OpenCost is the CNCF-hosted open specification and engine that grew out of Kubecost's core. Kubecost builds on it with a UI, multi-cluster aggregation, reports, alerts, budgets and governance controls. Some of these features depend on the edition, so check the current tiers yourself.
OpenCost engine (CNCF open spec, grew out of Kubecost's core)
+--------------------------------------------------------------------+
| +--------------------+ +-----------------------------+ |
| | Node price | | Pod CPU/RAM requests and | |
| | (per node, per hr) | | usage over time window | |
| +---------+----------+ +--------------+--------------+ |
| | | |
| v v |
| +--------------------+ +-----------------------------+ |
| | Split into +--------->| max(request, usage) | |
| | $/vCPU-hr, $/GiB-hr| | x per-resource price | |
| +--------------------+ +--------------+--------------+ |
| +--------------------+ | |
| | PV storage cost +----------------+ | |
| +--------------------+ v v |
| +--------------------+ +-----------------------------+ |
| | Network cost +--------->| Modeled pod cost (not | |
| | (where exposed) | | metered): bin-packing gaps, | |
| +--------------------+ | burstable use, DaemonSets, | |
| | overhead allocated by rule | |
| +--------------+--------------+ |
| v |
| Allocation by namespace / label / team |
+-------------------------------------------------+------------------+
v
+--------------------------------------------------------------------+
| Kubecost layer: UI, multi-cluster aggregation, reports, alerts, |
| budgets, governance controls (some features edition-dependent) |
+--------------------------------------------------------------------+
The shared OpenCost/Kubecost allocation model: node prices are split into per-resource rates, each pod is charged max(request, usage) at those rates plus storage and network, the modeled result is rolled up by namespace, label or team, and Kubecost adds its UI and governance layer on top.
Why is per-team cost allocation a labeling and policy problem first?
Both tools can only attribute spend to an owner the cluster can identify. A pod with no ownership signal still costs money, but it ends up in an unallocated bucket that nobody owns and everybody disputes. Decide the ownership model before you compare dashboards.
| Model | How ownership is resolved | Works well when | Breaks down when |
|---|---|---|---|
| Namespace per team | Namespace name or a label on the namespace | Teams deploy into their own namespaces | Several teams share a namespace, or a team owns many namespaces |
Required workload label (team or cost-center) |
Label on the pod template | Namespaces are shared, or ownership changes per workload | Labels are missing, misspelled or renamed |
Many organizations combine the two. The namespace label acts as the default, and a workload label overrides it inside shared namespaces such as platform or data. Kubernetes does not copy namespace labels onto pods, so confirm how your tool resolves this before you rely on it.
Label hygiene is the main failure mode. If one team writes payments, another writes Payments, and a third writes team-payments, your reports show three owners. A rename partway through a quarter splits the history, and month-over-month reports stop lining up. Treat label values as stable identifiers rather than display names, and keep a single list of allowed values.
To enforce this, add an admission policy, either Kubernetes' validating admission policies or a policy engine. The policy should reject workloads whose pod template lacks a valid team label. Exempt system namespaces. Start in audit or warn mode so teams can fix existing manifests before deploys start failing, and write error messages that name the missing label and list the allowed values.
This adds friction: deploys fail on a field that has nothing to do with the service itself. That cost is small and paid once. Without enforcement, the cost comes back every month as someone reconciling unallocated spend by hand and arbitrating disputes over who owns it.
# Require a valid `team` label on workload pod templates (Kubernetes 1.30+).
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: require-team-label
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["apps"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["deployments", "statefulsets", "daemonsets"]
validations:
# Check the pod template, because pod labels are what cost tools read.
# Allowed values are stable identifiers, not display names.
- expression: >-
has(object.spec.template.metadata.labels) &&
'team' in object.spec.template.metadata.labels &&
object.spec.template.metadata.labels['team'] in ['payments', 'search', 'platform', 'data']
message: "spec.template.metadata.labels.team is missing or invalid. Allowed values: payments, search, platform, data"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: require-team-label
spec:
policyName: require-team-label
# Start with Warn + Audit so teams can fix manifests. Switch to [Deny] once violations reach zero.
validationActions: ["Warn", "Audit"]
matchResources:
namespaceSelector:
matchExpressions:
# Exempt system namespaces.
- key: kubernetes.io/metadata.name
operator: NotIn
values: ["kube-system", "kube-public", "kube-node-lease"]
A ValidatingAdmissionPolicy and binding, running in warn-and-audit mode, that flag Deployments, StatefulSets and DaemonSets outside system namespaces whose pod template lacks a team label from the allowed list.
How do you set up OpenCost for per-team allocation?
OpenCost runs as a single deployment that reads usage from Prometheus and multiplies it by node, disk, and network prices. The setup is short. Most of what you need to plan is what OpenCost leaves to you.
Install and point it at Prometheus
Add the OpenCost Helm repository and run helm install into its own namespace. Then set the chart value that tells OpenCost where your existing Prometheus lives. Check the exact value names against the current chart docs, because they have changed over time. Prometheus must already scrape cAdvisor and kube-state-metrics. Without kube-state-metrics, OpenCost cannot connect pods to the labels you enforced earlier.
Configure pricing
By default, OpenCost uses public on-demand list prices for your cloud provider. If you have committed-use discounts, spot instances, or negotiated rates, those defaults will overstate costs. Configure the billing integration so allocations match your actual invoice.
Query by team
The allocation API takes a time window and an aggregation key. Aggregate by namespace or by a label such as team, and verify the parameter syntax in the current docs. The UI shows the same breakdown.
What you inherit
Your Prometheus retention period is the limit of your cost history. When Prometheus has an outage, or drops series because of high-cardinality labels, that period is missing from your cost data and cannot be backfilled. OpenCost does not provide any of the following, so you would build them yourself:
- multi-cluster aggregation
- long-term storage
- scheduled exports
- finance-ready reports
#!/usr/bin/env bash
# Conceptual OpenCost setup against an existing Prometheus.
# Chart value names, ports and API parameters change between releases:
# verify every one of them against the current OpenCost docs before use.
set -euo pipefail
# Repo URL deliberately left as a placeholder; take it from the OpenCost docs.
OPENCOST_REPO_URL="<opencost-helm-repo-url-from-docs>"
helm repo add opencost "$OPENCOST_REPO_URL"
helm repo update
# Install into its own namespace and point it at the Prometheus you already run.
# The --set keys below are illustrative; confirm the exact names in the chart's values.yaml.
helm install opencost opencost/opencost \
--namespace opencost --create-namespace \
--set opencost.prometheus.internal.namespaceName=monitoring \
--set opencost.prometheus.internal.serviceName=prometheus-server \
--set opencost.prometheus.internal.port=80
# Sanity check: kube-state-metrics must be scraped, or pods cannot be tied to team labels.
kubectl get pods -n monitoring | grep kube-state-metrics
# Expose the cost model API locally (port is an assumption; check the service definition).
kubectl -n opencost port-forward service/opencost 9003:9003 &
sleep 3
# Last 7 days of cost, aggregated by namespace.
curl -sG \
--data-urlencode 'window=7d' \
--data-urlencode 'aggregate=namespace'
# Same window, aggregated by the enforced 'team' pod label.
# The window cannot reach back further than your Prometheus retention.
curl -sG \
--data-urlencode 'window=7d' \
--data-urlencode 'aggregate=label:team'
A conceptual install that points OpenCost at an existing Prometheus and queries the allocation API by namespace and by a team label, with chart values, port and query parameters flagged for verification against the current docs.
How do you set up Kubecost, and what does it add for chargeback?
Kubecost covers most of that list out of the box, because it builds on the same allocation engine and adds a product layer on top. Installation is a single Helm chart that deploys the cost model, a UI, and, by default, a bundled Prometheus. The bundled Prometheus is the quickest path, but it duplicates scraping and storage if you already run Prometheus. Pointing Kubecost at your existing instance avoids that duplication. In exchange, you must confirm that the required metrics, including kube-state-metrics and cAdvisor, are scraped at a resolution and retention that Kubecost can use.
The step that matters most for chargeback is cloud billing reconciliation. You connect Kubecost to your provider's billing export so it can replace list prices with what you actually paid, including discounts, commitments, and credits. Without this step, team totals will not sum to the invoice, and finance will reject the numbers. After reconciliation, you save reports that aggregate by your team label or by namespace, so every review uses the same view.
| Chargeback piece | Kubecost | OpenCost |
|---|---|---|
| Multi-cluster rollup | Built in (edition-dependent) | Script it |
| Saved and scheduled reports | Built in | Script exports |
| Budgets and alerts | Built in | Build on your alerting stack |
| Billing reconciliation | Built in | Partial; verify |
| Vendor support | Paid tiers | Community |
These features come with costs: licensing fees, limits on clusters or data retention in lower editions, and dependency on a single vendor's roadmap. Features have moved between editions over time. Check the current tier documentation before you commit, rather than relying on this table.
# Conceptual Kubecost install that reuses an existing Prometheus and reconciles
# against cloud billing. Value keys change between chart versions: confirm them
# with `helm show values` before applying.
helm repo add kubecost "<kubecost-helm-repo-url-from-official-docs>"
helm repo update
helm show values kubecost/cost-analyzer > default-values.yaml # check key names here
# Billing export credentials live in a Secret so they stay out of the values file.
# The file format depends on the provider; follow the docs for your edition.
kubectl create namespace kubecost
kubectl -n kubecost create secret generic cloud-integration \
--from-file=cloud-integration.json=./cloud-integration.json
cat > values-kubecost.yaml <<'EOF'
global:
prometheus:
enabled: false # skip the bundled Prometheus to avoid duplicate scraping and storage
# Existing Prometheus must scrape kube-state-metrics and cAdvisor, with enough retention
fqdn:
kubecostProductConfigs:
clusterName: prod-eu-1
# Reconcile list prices with what you actually paid (discounts, commitments, credits)
cloudIntegrationSecret: cloud-integration
EOF
helm upgrade --install kubecost kubecost/cost-analyzer \
--namespace kubecost -f values-kubecost.yaml
# Spot-check the chargeback view: last 7 days of cost aggregated by the team label.
# Save this aggregation as a report in the UI so every review uses the same view.
kubectl -n kubecost port-forward deployment/kubecost-cost-analyzer 9090 &
curl -s ''
A conceptual Kubecost Helm install that points at an existing Prometheus, references a billing-integration Secret for reconciliation, and queries the allocation API aggregated by the team label. Verify value keys against your chart version and edition.
How should you split idle and shared costs between teams?
Every chargeback scheme has a remainder that no team's pods directly requested. It has three parts: idle node capacity, cluster overhead such as kube-system, ingress controllers and monitoring, and shared services that several teams depend on. Both tools can report this remainder separately. Your policy decides who pays it.
| Approach | Who pays the remainder | Effect |
|---|---|---|
| Central absorption | Platform budget | Team bills stay clean, but nobody is pushed to cut over-provisioning |
| Proportional | Each team, by its share of allocated cost | Large teams pay most, and waste is visible to everyone |
| Even split | Each team equally | Simple, but small teams subsidize large ones |
Illustrative estimate (assumed numbers, not a benchmark). The assumed inputs are a cluster costing $3,000 per month and pod requests that reserve 40%, 20% and 10% of capacity for teams A, B and C.
- Allocated cost is
cluster cost × request share. That gives A $1,200, B $600 and C $300, for a total of $2,100. - The remainder (idle capacity plus overhead) is $3,000 − $2,100 = $900.
- Under proportional handling, each team pays
allocated + remainder × (team allocated / total allocated). That gives A $1,714, B $857 and C $429. - Under central handling, the teams pay $1,200, $600 and $300, and the platform budget carries the $900.
- Under an even split, the teams pay $1,500, $900 and $600.
Team C's bill doubles between central and even handling, and its own workloads have not changed. The formula decides which teams come out ahead and which come out behind. Get the teams to agree on it before anyone sees a published number.
When should you avoid treating in-cluster allocation as chargeback?
Both tools price resources from a pricing model, typically on-demand list prices or a custom price sheet. Your actual invoice rarely matches. Reserved capacity, savings plans, spot instances, negotiated enterprise discounts and credits all change what a node really cost. If you bill teams from unreconciled estimates, the numbers will look precise and still be wrong, and finance will notice when the totals don't add up to the invoice.
Coverage has gaps too. Network egress, cross-cluster and cross-zone traffic need extra configuration and are often only partly attributed. Managed services outside the cluster, such as databases, object storage and load balancers, don't show up in pod-level allocation unless you integrate cloud billing data and tag those resources consistently. A team running a large managed database can therefore look cheap on the cluster report.
Roll out showback first
- Publish per-team reports without billing anyone. Teams see their numbers while nothing is at stake.
- Reconcile against the cloud invoice. Compare monthly totals and track the gap explicitly. Don't hide the gap inside the idle bucket.
- Fix label gaps and request inflation. Unlabeled workloads shrink as owners claim them. Teams also find pods that request four cores and use half of one.
- Move to chargeback once the allocation policy is written down and agreed with finance.
This order saves engineering time as well as money. Over-requesting usually gets fixed during showback, because nobody is defending a charge yet. Right-sizing then happens as normal engineering work, and you avoid budget disputes and emergency tuning after the first bill arrives.
Should you choose OpenCost or Kubecost?
The choice comes down to whether you have more engineering time or more budget, and how much reporting you need on top of the raw numbers.
| Factor | OpenCost | Kubecost |
|---|---|---|
| Licensing | Open source, vendor-neutral | Commercial tiers with a dependency on the vendor |
| Reporting | Bring your own (Grafana, exports) | Ready-made allocation and chargeback reports |
| Multi-cluster rollup | You build the aggregation | Provided |
| Budgets and alerts | You build them on Prometheus | Provided |
| Support | Community | Vendor support available |
Pick OpenCost if you already run Prometheus and Grafana and are willing to build dashboards, CSV or warehouse exports, and alerting yourself. Pick Kubecost if finance needs consolidated multi-cluster reports, budgets and alerts soon, and you accept the commercial dependency.
You have two other options. Cloud billing with tag-based allocation works when teams map cleanly to node pools or accounts, but it can't see pod-level sharing. Homegrown Prometheus queries can work for one cluster, but you end up owning the whole cost model.
Illustrative estimate (assumed numbers, not a benchmark):
Annual cost of building it yourself = (build hours + yearly maintenance hours) × loaded hourly rate
Assume 160 build hours, 80 maintenance hours per year and a $100/hour loaded rate. That gives (160 + 80) × 100 = $24,000 in the first year. Compare that figure with the license quote you receive for your cluster count.
You can start with OpenCost and migrate later because Kubecost uses the same allocation model. Your labels, idle-cost policy and showback history carry over, so a migration mostly changes the reporting layer, not your data.
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 Kubernetes cost allocation, 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.