Skip to content
CNPE · Chapter 14 of 22 Day 12: OpenCost – what does a team cost?

Day 12: OpenCost – what does a team cost?

Goal: Install OpenCost with prices for your own data centre, read costs per namespace and team, compare requested and used resources, and shrink a service based on measured values · Duration: approx. 45 min · Prerequisite: Day 11

Briefing

  • A platform shares out one common cluster. Without numbers, teams request a lot “just to be safe” – and block capacity they don’t use. FinOps makes costs visible and attributable.
  • OpenCost (CNCF) calculates costs from two sources: what a node costs (price list or cloud API) and who occupies it and how heavily (metrics from Prometheus).
  • Important: for every container, OpenCost calculates max(request, usage). If you request 1 CPU and use 5 m, you pay for 1 CPU – the node is occupied for everyone else.
  • Without a cloud there is no pricing API. You set your own prices per vCPU hour, GiB hour and storage – calculated from purchase, power and operations.

Drill 1: OpenCost with your own prices

# on cp1
mkdir -p ~/cnpe/tag12 && cd ~/cnpe/tag12
cat > opencost-werte.yaml <<'EOF'
opencost:
  prometheus:
    internal:                                  # Prometheus from Day 10
      enabled: true
      serviceName: monitoring-kube-prometheus-prometheus
      namespaceName: monitoring
      port: 9090
  customPricing:
    enabled: true
    provider: custom
    costModel:                                 # prices in euros per hour
      description: Eigenes Rechenzentrum
      CPU: "0.031"                             # per vCPU
      spotCPU: "0.031"
      RAM: "0.004"                             # per GiB
      spotRAM: "0.004"
      GPU: "0.95"
      storage: "0.00005"                       # per GiB of volume
      zoneNetworkEgress: "0"                   # network traffic costs nothing extra in your own data centre
      regionNetworkEgress: "0"
      internetNetworkEgress: "0"
  metrics:
    serviceMonitor:
      enabled: true                            # Prometheus collects the cost metrics
  ui:
    enabled: true
service:
  type: NodePort
EOF
helm repo add opencost https://opencost.github.io/opencost-helm-chart
helm repo update
helm install opencost opencost/opencost --version 2.5.35 -n opencost --create-namespace -f opencost-werte.yaml
k -n opencost rollout status deploy/opencost --timeout=300s
k -n opencost get svc opencost

Expected (abridged, your NodePorts will differ):

STATUS: deployed
deployment "opencost" successfully rolled out
NAME       TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)                                        AGE
opencost   NodePort   10.99.206.64   <none>        9003:32608/TCP,8081:30594/TCP,9090:31863/TCP   63s

Port 9003 is the API, 9090 the UI. OpenCost needs a few minutes of measurements before the numbers make sense – wait five minutes.

Save your progress? Sign up for free

Drill 2: Cost of the nodes

# on cp1
# Cost per node and hour – from the prices and the size of the nodes
curl -s http://172.16.0.126:30090/api/v1/query --data-urlencode 'query=node_total_hourly_cost' \
  | jq -r '.data.result[] | "\(.metric.node) \(.value[1])"'
# Month (730 hours)
curl -s http://172.16.0.126:30090/api/v1/query --data-urlencode 'query=sum(node_total_hourly_cost) * 730' \
  | jq -r '.data.result[0].value[1]'

Expected:

cp1 0.17072328186035157
worker1 0.09302284240722657
worker2 0.09302287292480468
260.4413679504394

cp1 (4 vCPU, 12 GB): 4 × 0.031 + 11.7 × 0.004 ≈ €0.17 per hour. Around €260 per month for the lab – at your own prices.

Save your progress? Sign up for free

Drill 3: Cost per team

# on cp1
API=http://172.16.0.126:$(k -n opencost get svc opencost -o jsonpath='{.spec.ports[?(@.port==9003)].nodePort}')
# Allocation API: last hour, by namespace, accumulated into one value
curl -s "$API/allocation/compute?window=1h&aggregate=namespace&accumulate=true" \
  | jq -r '["NAMESPACE","CPU-REQ","CPU-NUTZ","RAM-REQ-MiB","RAM-NUTZ-MiB","EUR/h"],
      (.data[0] | to_entries[] | select(.key|startswith("team-"))
      | [.key, (.value.cpuCoreRequestAverage*1000|round|tostring+"m"), (.value.cpuCoreUsageAverage*1000|round|tostring+"m"),
         (.value.ramByteRequestAverage/1048576|round), (.value.ramByteUsageAverage/1048576|round),
         (.value.totalCost*1000|round/1000)]) | @tsv' | column -t

Expected (numbers vary):

NAMESPACE           CPU-REQ  CPU-NUTZ  RAM-REQ-MiB  RAM-NUTZ-MiB  EUR/h
team-blue           687m     5m        790          84            0.012
team-gelb           408m     3m        721          23            0.003
team-green          152m     0m        195          19            0.006
team-green-staging  0m       0m        0            3             0

(NUTZ is short for usage.) Team Blue requests 687 m CPU and uses 5 m – over 99 % of the CPU it pays for sits idle. OpenCost expresses this as efficiency:

# on cp1
curl -s "$API/allocation/compute?window=1h&aggregate=namespace&accumulate=true" \
  | jq -r '.data[0]["team-blue"] | "cpuEff=\(.cpuEfficiency) ramEff=\(.ramEfficiency) total=\(.totalEfficiency)"'

Expected:

cpuEff=0.00778 ramEff=0.10701 total=0.02034

team-green-staging shows 0 requests: the pod there was created on Day 6, before Kyverno set the LimitRange on Day 9 – it has no requests and, by this calculation, costs only its usage. One more reason to enforce defaults from the start.

Save your progress? Sign up for free

Drill 4: Shrink based on measurements

For podinfo, you derive requests from real usage: CPU from the 95th percentile, memory from the maximum – each with headroom.

# on cp1
# CPU in millicores: 95th percentile of the 5-min rate over one hour (subquery [1h:1m])
curl -s http://172.16.0.126:30090/api/v1/query --data-urlencode \
  'query=max by (container) (quantile_over_time(0.95, rate(container_cpu_usage_seconds_total{namespace="team-blue",container="podinfo"}[5m])[1h:1m])) * 1000' \
  | jq -r '.data.result[] | "cpu_p95_m \(.value[1])"'
# Memory in MiB: highest working set of the last hour
curl -s http://172.16.0.126:30090/api/v1/query --data-urlencode \
  'query=max by (container) (max_over_time(container_memory_working_set_bytes{namespace="team-blue",container="podinfo"}[1h])) / 1048576' \
  | jq -r '.data.result[] | "mem_max_mib \(.value[1])"'
k -n team-blue get deploy podinfo -o jsonpath='{.spec.template.spec.containers[0].resources}{"\n"}'

Expected:

cpu_p95_m 9.951811160032175
mem_max_mib 22.0078125
{"limits":{"cpu":"200m","memory":"128Mi"},"requests":{"cpu":"50m","memory":"64Mi"}}

With double headroom for CPU and around 50 % for memory: 20 m and 32 Mi. The limits stay – they protect against outliers.

# on cp1
k -n team-blue set resources deploy/podinfo --requests=cpu=20m,memory=32Mi
k -n team-blue rollout status deploy/podinfo --timeout=90s

Expected:

deployment.apps/podinfo resource requirements updated
deployment "podinfo" successfully rolled out

In an hour, the Allocation API shows 60 m less CPU request for team-blue. In a GitOps setup, this change belongs in the team’s repo as a commit.

Save your progress? Sign up for free

Exercise: The most expensive namespace

Time limit: 5 minutes. Which namespace cost the most in the last hour, and what share of its costs is CPU?

Solution

# on cp1
curl -s "$API/allocation/compute?window=1h&aggregate=namespace&accumulate=true" \
  | jq -r '.data[0] | to_entries | max_by(.value.totalCost) | "\(.key) \(.value.totalCost) cpu_anteil=\(.value.cpuCost/.value.totalCost)"'

Expected (values vary):

kube-system 0.03073 cpu_anteil=0.8011714936544093

The most expensive namespace is the platform itself: kube-system with the control plane, Cilium and CoreDNS – mainly because of their CPU requests. In practice, such “platform costs” are distributed proportionally across the teams.

Save your progress? Sign up for free

Challenge

Time limit: 10 minutes. Management wants costs per team, not per namespace – team-green and team-green-staging belong together. The namespaces carry the label team.

Solution

# on cp1
# aggregate=label:team aggregates by the label team (namespace labels are included)
curl -s "$API/allocation/compute?window=1h&aggregate=label:team&accumulate=true" \
  | jq -r '.data[0] | to_entries[] | "\(.key) \(.value.totalCost)"'

Expected (values vary):

__unallocated__ 0.05507
blue 0.01255
gelb 0.00286
green 0.00559

__unallocated__ is every pod without the label team – the platform. That is why Kyverno on Day 9 enforces the label not only on the namespace: without clean labels there is no clean cost attribution.

Save your progress? Sign up for free

Checkpoint

# on cp1
k -n opencost get deploy opencost -o jsonpath='{.status.readyReplicas}{"\n"}'
# own prices active: cost per vCPU hour
curl -s http://172.16.0.126:30090/api/v1/query --data-urlencode 'query=avg(node_cpu_hourly_cost)' | jq -r '.data.result[0].value[1]'
# podinfo shrunk
k -n team-blue get deploy podinfo -o jsonpath='{.spec.template.spec.containers[0].resources.requests}{"\n"}'

Expected:

1
0.031
{"cpu":"20m","memory":"32Mi"}

Interview Note

  • Why does OpenCost calculate with the request and not with usage? The scheduler reserves the request – the space is occupied for others, even if it sits empty.
  • How do you distribute the costs of the platform itself? As “shared costs”, proportionally by consumption or as a fixed amount per team; what matters is that it is documented and the same for everyone.
  • Where do requests come from if you don’t want to guess them? From measurements (percentiles over days), automatically with the Vertical Pod Autoscaler in recommendation mode.

Enterprise Note

  • Derive prices yearly from the real calculation (depreciation, power, licences, staff).
  • Send cost reports from the API to teams via a CronJob; budgets with alerts in Prometheus (sum by (namespace) (...) > Budget).
  • VPA in mode Off as a recommender; changes via pull request into the team repo.
  • Report GPU costs separately – that is where FinOps pays off most (separate course “FinOps for GPU”).

Contents

More