TExcelTAD

Cost Allocation by Label

A Kubernetes cluster is a single line on the cloud bill: "EC2, 14 instances, $X". Teams don't own instances; they own Pods spread over shared nodes. Cost allocation splits the cluster's cost onto the workloads that used it, and then rolls it up by namespace and label to teams, services and cost centers. OpenCost (next lesson) does exactly this; this lesson builds the model so you know what its numbers mean.

The allocation rules

The common approach, used by OpenCost and most commercial tools:

  1. Price each node's resources. From the cloud price of the instance, derive an hourly price per CPU core and per GiB of memory (OpenCost splits instance prices between CPU and RAM using default ratios or provider pricing data).
  2. Charge each container for what it reserved or used, whichever is larger: max(request, usage) × price × hours. Requests are charged because they block capacity from others; usage above requests is charged because it was consumed.
  3. Idle cost = node cost − everything allocated. It's real money (capacity nobody reserved), and you decide whether to show it separately or share it among teams in proportion to their allocation.
  4. Shared costs (the platform's own namespaces: kube-system, monitoring, gateway-system, Argo CD) are split among tenants by an agreed rule: evenly, by allocation share, or treated as platform overhead.
  5. Out-of-cluster costs (managed databases, buckets, load balancers) are added from the cloud bill using tags.

The model

python · try it yourself
HOURS = 730                        # a month
NODES = {"node-a": {"cpu": 8, "mem": 32, "price_h": 0.40},
         "node-b": {"cpu": 8, "mem": 32, "price_h": 0.40}}
CPU_SHARE = 0.65                   # part of an instance's price attributed to CPU, the rest to memory

# workload: (namespace, labels, cpu request, cpu usage, mem request GiB, mem usage GiB)
WORKLOADS = {
    "linkly":      ("team-links",  {"team": "links"},  1.0, 0.6, 2.0, 1.2),
    "redirector":  ("team-links",  {"team": "links"},  2.0, 2.4, 2.0, 1.5),
    "analytics":   ("team-growth", {"team": "growth"}, 4.0, 1.0, 8.0, 3.0),
    "qr-codes":    ("team-qr",     {},                 0.5, 0.3, 1.0, 0.5),   # unlabelled
    "prometheus":  ("monitoring",  {"team": "platform"}, 1.0, 0.9, 6.0, 5.5),
    "coredns":     ("kube-system", {"team": "platform"}, 0.2, 0.1, 0.25, 0.1),
}
SHARED_NAMESPACES = {"monitoring", "kube-system"}

total_cpu = sum(n["cpu"] for n in NODES.values()); total_mem = sum(n["mem"] for n in NODES.values())
cluster_cost = sum(n["price_h"] for n in NODES.values()) * HOURS
cpu_price = cluster_cost * CPU_SHARE / (total_cpu * HOURS)          # $ per core-hour
mem_price = cluster_cost * (1 - CPU_SHARE) / (total_mem * HOURS)    # $ per GiB-hour
print(f"cluster ${cluster_cost:.2f}/month; ${cpu_price:.4f} per core-h, ${mem_price:.4f} per GiB-h")

alloc = {}
for name, (ns, labels, cpu_r, cpu_u, mem_r, mem_u) in WORKLOADS.items():
    cost = (max(cpu_r, cpu_u) * cpu_price + max(mem_r, mem_u) * mem_price) * HOURS
    alloc[name] = (ns, labels.get("team", "__unallocated__"), cost)

allocated = sum(c for _, _, c in alloc.values())
idle = cluster_cost - allocated
print(f"allocated ${allocated:.2f}, idle ${idle:.2f} ({idle / cluster_cost:.0%})")

by_team = {}
for name, (ns, team, cost) in alloc.items():
    key = "shared" if ns in SHARED_NAMESPACES else team
    by_team[key] = by_team.get(key, 0) + cost
tenants = {t: c for t, c in by_team.items() if t != "shared"}
tenant_total = sum(tenants.values())
print(f"\n{'team':16} {'direct':>8} {'+shared':>8} {'+idle':>8} {'total':>8}")
for team, direct in sorted(tenants.items()):
    share = direct / tenant_total
    shared, idle_part = by_team["shared"] * share, idle * share
    print(f"{team:16} {direct:8.2f} {shared:8.2f} {idle_part:8.2f} {direct + shared + idle_part:8.2f}")
cluster $584.00/month; $0.0325 per core-h, $0.0044 per GiB-h
allocated $277.38, idle $306.62 (53%)

team               direct  +shared    +idle    total
__unallocated__     15.06     3.18    20.16    38.41
growth             120.45    25.48   161.32   307.25
links               93.44    19.77   125.14   238.35

What the output shows:

  • Idle is the biggest line. Over half the cluster is capacity nobody requested. That's the platform team's problem, not the tenants': consolidation, a smaller node type or autoscaling would save more than any team could. Showing idle separately keeps that visible; sharing it out (as in the last columns) gives a complete bill but hides who can fix it.
  • analytics pays for its requests, not its usage: it requests 4 cores and uses 1. That's the rightsizing conversation, with a number attached.
  • redirector pays for usage above its request (2.4 of 2.0 cores): it's also an under-request that risks CPU throttling.
  • __unallocated__ is the cost of qr-codes, which has no team label. Every unlabelled workload ends up there, and the size of that bucket is a good KPI for labelling hygiene.

Choices you have to agree on

Question Common answers
requests, usage or max of both? max(request, usage) is the usual default; usage-only rewards over-requesting
idle: separate or shared? separate in showback (actionable), shared in chargeback (complete)
shared namespaces proportional to allocation; or a flat platform fee; or carried by the platform budget
GPU, storage, network GPUs by request (they can't be shared by default), PVs by size, network by egress volume when measured
time granularity hourly or daily allocation, summed per month, so short-lived workloads pay for their hours

Write the rules down, publish them in the portal next to the numbers, and change them rarely.

Test yourself

Why is CPU usually charged as max(request, usage)?

  1. It is cheaper
  2. A request reserves capacity others can't use, and usage above the request was consumed: both cost money
  3. Kubernetes requires it
  4. Usage can't be measured

Who is usually best placed to reduce a large idle cost?

  1. Each tenant team
  2. The platform team, through consolidation, autoscaling and node sizing
  3. Finance
  4. Nobody

What does a growing __unallocated__ bucket indicate?

  1. Cheap workloads
  2. Workloads without owner labels: labelling hygiene is slipping
  3. Too many nodes
  4. Idle capacity