How does Kubecost namespace cost allocation work?

Showback means reporting what each team's workloads cost without billing them for it. Kubecost, built on the OpenCost allocation model, computes that cost from the bottom up:

node pricing ─┐
              ├─► cost model ─► allocation (per container) ─► aggregation
metrics ──────┘                                                (namespace, label,
(Prometheus)                                                    controller)

The cost model splits each node's hourly price into per-unit prices for CPU and RAM. Each container is then charged for the resources it held during each interval. Those container costs roll up by namespace, label, or controller.

The charge basis is effectively max(requested, used). A request reserves capacity that the scheduler cannot give to anyone else, so the requester pays for it even when it sits idle. Usage above the request still consumes real node capacity, so it is charged too.

Illustrative estimate (assumed numbers, not a benchmark): cost = max(request, usage) × unit price × hours Assume a container requests 4 vCPU, uses 1 vCPU, and CPU costs $0.03 per vCPU-hour. Over 730 hours it is charged 4 × 0.03 × 730 = $87.60. Without the request floor, it would be charged $21.90.

Over-requesting is sometimes deliberate. Teams reserve headroom to protect tail latency under bursts. JVM services need memory requests sized to the configured heap plus off-heap overhead. Showback should make these choices visible, not penalize them by default.

Accuracy depends on Prometheus scrape fidelity and retention. Pods and jobs that start and finish between scrapes may be under-attributed or missed entirely. The lookback window is also limited by how long Prometheus retains data.

+--------------------+      +--------------------+
| Node pricing       |      | Prometheus metrics |
| hourly $ per node  |      | requests + usage   |
| cloud or custom    |      | sampled per scrape |
+---------+----------+      +---------+----------+
          |                           |
          +-------------+-------------+
                        |
                        v
          +---------------------------+
          | Cost model                |
          | node $/hr split into      |
          | $/vCPU-hr and $/GiB-hr    |
          +-------------+-------------+
                        |
                        v
          +---------------------------+
          | Allocation (per container)|
          | max(request, usage)       |
          |   x unit price x hours    |
          +-------------+-------------+
                        |
                        v
          +---------------------------+
          | Aggregation               |
          | by namespace, label,      |
          | or controller             |
          +---------------------------+

Node prices and scraped Prometheus metrics feed the cost model, which charges each container on max(request, usage) and rolls the results up by namespace, label, or controller.

OpenCost or Kubecost: which should you start with?

OpenCost is the open-source allocation engine and the specification for how Kubernetes cost should be calculated and split. Kubecost is a commercial product built on that same core. It adds features on top, and some of them are gated by tier. Because feature lists change between releases, choose based on your situation rather than on a checklist.

Approach Fits when Main cost
OpenCost Engineers are the audience and approximate numbers are acceptable You own the Prometheus, the dashboards, and the upgrades
Kubecost Finance needs invoice reconciliation, or several clusters need one view Licensing and vendor dependency
Billing export + resource tags Workloads map cleanly to cloud resources, with little bin-packing Cannot split a shared node between namespaces
Spreadsheet allocation A few teams, quarterly reviews Manual work, and the numbers get stale quickly

Three questions settle most of these decisions:

  • Who reads the report? Engineers tolerate estimates. Finance does not.
  • Does the total need to match the invoice? If it does, you need reconciliation against billing data, not just list prices.
  • Who will run the stack? Someone has to be on call for it.

The cost stack also costs money. Prometheus retention and the allocation engine consume CPU, memory, and disk. That spend should go into the shared-cost pool so it gets allocated, rather than quietly widening the idle bucket.

Illustrative estimate (assumed numbers, not a benchmark): overhead % = cost-stack monthly cost ÷ cluster monthly cost

Assume $150 ÷ $6,000 = 2.5%.

Where do the prices come from, and why don't they match the invoice?

Out of the box, Kubecost and OpenCost price each node from the cloud provider's public rates, usually on-demand list prices, or from a custom price sheet you supply for on-prem hardware. That is a reasonable starting point because it requires no billing access. It does not reflect what your organisation actually pays.

Your invoice includes things a public price list cannot know about: negotiated enterprise discounts, reserved capacity or savings commitments, spot or preemptible pricing, credits, and the timing of when commitments are applied. Kubecost can reconcile allocation against your provider's billing export, replacing estimated node prices with the billed cost of each resource. Until that integration is configured, every namespace figure is an estimate built on the wrong unit price.

Aspect List / on-demand pricing Reconciled billing data
Source Public price API or custom sheet Provider billing export
Discounts and commitments Ignored Reflected
Spot nodes Often priced at on-demand rates Billed spot price
Latency Near real time Lags until billing data lands
Matches finance's total Rarely Closely, if configured correctly

The error is not uniform. A team running on spot nodes looks far more expensive than it is, while a team on committed capacity looks only modestly inflated. Relative rankings shift, and they shift in ways that punish teams for good cost decisions.

The bigger cost is credibility. When an engineering lead brings a namespace figure to a budget meeting and finance's number is substantially lower, the discussion turns to whose number is right instead of what to change. After that happens once or twice, teams stop treating the reports as real.

How should you handle idle, shared, and out-of-cluster costs?

Idle cost is the price of capacity you provisioned but no workload has claimed. It is node CPU and memory not covered by any pod's requests. In a shared cluster this is often a large share of spend for three reasons:

  • Nodes are sized for peak load.
  • Autoscalers keep headroom.
  • Bin-packing is never perfect.

If you hide idle cost, namespace totals stop reconciling with the bill, and that gap is what erodes trust.

You have three options. Each is a policy choice, and none is objectively correct:

  • Show it separately. This is the most transparent option. The drawback is that no team owns the idle bucket, so nobody works to shrink it.
  • Distribute it proportionally. Each namespace's share = (namespace allocated cost ÷ total allocated cost) × idle cost. Teams that request heavily pay more, which rewards right-sizing.
  • Distribute it evenly. This is simple, but small namespaces end up subsidising large ones.

Shared overhead works the same way. Mark kube-system, monitoring, ingress controllers, the service mesh, and managed control-plane fees as shared, then spread them across tenant namespaces. Agree the rule with teams before the first report goes out. A team that learns about a policy from a published number will treat it as a surprise charge and dispute it.

Cost Allocates to a namespace naturally? What it needs
Persistent volumes Yes, through the PVC's namespace Nothing, unless the volume is orphaned
Load balancers Mostly, through the Service's namespace A shared-cost rule for shared ingress
Network egress Partially Network-level metering; attribution is approximate
External managed services No Cloud tags matching team labels, or a manual policy

Some cost will stay in an unallocated bucket. Report that bucket openly and aim to shrink it rather than eliminate it.

How do you enforce label hygiene for team-level showback?

Namespaces are a weak proxy for ownership. A team can own several namespaces, a namespace can host workloads from several teams, and platform components often live in namespaces nobody claims. Kubecost can aggregate allocation data by any label, so pick one ownership key, such as team, plus an optional cost-center for finance, and make it mandatory.

The accompanying manifest places these labels on both the Deployment metadata and the pod template. The pod template is the part that matters: allocation is computed from running pods, so a label that exists only on the Deployment object never reaches the cost data. Labeling the namespace as well gives you a fallback for pods that slip through.

Enforce the label at admission, not in a later audit. A validating admission policy can reject any pod-creating workload whose pod template lacks a team label, or lacks a value from an approved list. Roll the policy out in audit or warn mode first so you can see which workloads would fail before you block them. Create a deliberate catch-all value, such as team: unassigned, and route it to a named owner. An unlabeled pod is then reported as a known gap with someone responsible for it, rather than disappearing into the unallocated total.

This adds friction. Deployments fail on a missing label, Helm charts need values overrides, and third-party operators may need exemptions. That cost is small compared with the alternative: engineers going through spreadsheets every month to work out who owns a workload before anyone can discuss the bill.

# Ownership labels go on the pod template: allocation is computed from running pods.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: checkout-api
  namespace: shop
  labels: {team: payments, cost-center: cc-1042}
spec:
  selector: {matchLabels: {app: checkout-api}}
  template:
    metadata:
      labels: {app: checkout-api, team: payments, cost-center: cc-1042}
    spec:
      containers:
        - {name: api, image: registry.example.com/checkout-api:1.4.2}
---
# Admission check: the pod template needs a team label from the approved list.
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:
    - expression: >-
        has(object.spec.template.metadata.labels) &&
        'team' in object.spec.template.metadata.labels &&
        object.spec.template.metadata.labels['team'] in ['payments', 'search', 'platform', 'unassigned']
      message: "Pod template needs a team label from the approved list (use 'unassigned' if unsure)."
---
# Start in Warn + Audit to find failing workloads, then switch to Deny.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata: {name: require-team-label}
spec:
  policyName: require-team-label
  validationActions: ["Warn", "Audit"]

A Deployment that sets team and cost-center labels on its pod template, and a ValidatingAdmissionPolicy with a binding that checks this label in warn-and-audit mode before you switch it to enforcement.

Building a showback report teams will act on

Pick one fixed window, such as the previous calendar month, and keep it consistent. Rolling or partial windows make month-over-month comparisons meaningless, and teams stop trusting a report whose numbers shift when they reload it. Aggregate by namespace, or by team label if you have one. Then place requested-vs-used efficiency next to each cost figure. Cost alone shows who spends the most. Efficiency shows whose spend is waste.

Worked example (illustrative estimate)

These inputs are assumed. One node costs $300 for the month. Workload requests account for $210: payments $120, search $60, batch $30. Shared system workloads such as monitoring and kube-system cost $30, and unrequested idle capacity is $60. The $90 of overhead is distributed in one of two ways. Proportional distribution splits it by each namespace's share of the $210. Even distribution gives each namespace $30.

Namespace Direct cost Proportional total Even total Request efficiency (assumed)
payments $120 $171.43 $150.00 40%
search $60 $85.71 $90.00 85%
batch $30 $42.86 $60.00 70%

Proportional distribution charges overhead in line with how much capacity each team reserves, which usually feels fairer. Even distribution weighs most heavily on small namespaces like batch.

The efficiency column is where the report becomes useful. payments uses only 40% of what it requests, so most of its $120 reserves capacity that nothing uses. Lowering those requests reduces its direct cost and also shrinks the base that idle cost is spread over. That gives the team one specific deployment to right-size instead of a general instruction to "spend less."

When should you validate, publish, or avoid chargeback?

Before any of these numbers leave the platform team, reconcile them. For a closed billing period, add allocated, idle, and shared cost for the cluster and compare the total to what the cloud provider actually billed for the same nodes, disks, and load balancers. A small gap is expected from discounts and rounding. A large one usually means a missing node pool, credits or commitments not reflected in pricing, or resources tagged to the cluster that Kubecost never saw. Find the cause before publishing, because the first question any team asks is whether the total is real.

Start with showback only

Publish numbers as visibility, not as a bill. Showback lets teams see their cost drivers and question the method while nothing is at stake. That feedback is how you discover broken labels and allocation rules that look unfair.

Preconditions for chargeback

Move to chargeback only when all of these hold:

  • Allocation rules have stayed stable across several billing periods.
  • Pricing reconciles against the invoice within a tolerance finance accepts.
  • Teams have agreed on how shared and idle costs are split, and that agreement is written down.

When to skip per-team numbers

In a small cluster run by one team, a per-namespace split adds overhead and gives no one a decision to make. Skip it there, and also while rules are still changing. Numbers published too early start disputes over method instead of spend. They also invite gaming: once requests drive the bill, teams cut them below what the workload needs, and reliability pays for it.

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 kubecost namespace 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.
  • The dependency graph answers "what does this touch?" in seconds instead of a manual audit.

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.
  • You can size a change's blast radius before merging, avoiding surprise cross-team firefighting.
  • 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.