Attributing AI spend: labels, request context, shared costs and chargeback
The finance director asks you which feature generates 40% of the AI spend and which customer consumes more than it pays. If the answer takes a week of spreadsheets, the problem is not the costs: it is that the spend does not carry the name of whoever generates it. This article builds the part that is missing between the per-call log (the one from the first article of the group) and a report somebody can use: labels on the infrastructure, the request context that tags every call to the model, an explicit rule for splitting what is shared, and three models for charging back. The four listings are executed, with invented and declared data.
A note on scope: here we work in Python and SQL, without a cluster. Kubernetes labels are treated as strings with syntax rules to verify, and the allocation tools for clusters (for example OpenCost, an open-source project that measures and allocates container costs and supports showback and chargeback) are cited but not run.
Direct costs, shared costs, costs with no owner
A call to a model has a direct cost: the tokens read in the response, times the price of the model, and the log already knows which feature it is if the feature was tagged. Then there are costs that no single call generates: the machine hosting the vector index, the platform, the nightly job that computes embeddings. And finally a third category, the most uncomfortable, which is the spend you cannot attribute because nobody put a label on it. For every euro of the month you can therefore say one of three things: "it belongs to this feature", "it is split with this rule" or "I don't know whose it is", and the quality of your cost tracking is measured by the third.
The FinOps Foundation, in its AI document, sets out the principle in two sentences: allocate before optimising, and allocate at the level at which the business measures, that is a use case, a product, a team or a feature. It also gives a maturity indicator: as an example target, at least 70% of the cost attributed to a known owner at the initial level (Crawl), 85% at the intermediate level and over 90% at the advanced level. These are targets taken from the community, not norms, and they have the merit of being a fraction you can compute. The first listing computes it.
Labels: few, mandatory and checked
For infrastructure workloads, labels are the simplest allocation mechanism, and Kubernetes fixes their syntax: the key has a mandatory name segment of at most 63 characters, alphanumeric at the ends with hyphens, underscores and dots inside, and an optional prefix that must be a DNS subdomain; the value has the same 63-character limit, may be empty and cannot contain spaces. A value such as Data Science is therefore not a valid label, and a tool that reads labels risks discarding it or, worse, accepting it and losing it in an aggregation. The same FinOps document proposes example keys (Project, Environment, Workload, Team, CostCenter, among others) that I translate here into lowercase labels, one for each typical question:
teamandcost-center, to know who pays and which budget line it is charged to;featureorproject, for the cost of a product feature;environment, to separate production, test and development;workload, to tell training, inference and batch jobs apart.
The list is neither exhaustive nor mandatory as a whole: the practical rule is that every required label must correspond to a question somebody really wants to answer, because every mandatory label is a maintenance cost for whoever does the release. Four checked keys are better than ten ignored ones.
The first listing checks six invented workloads against four mandatory keys and against the label syntax. The two regular expressions CHIAVE and VALORE encode the rules of the document; problemi returns a list of defects for each workload, and the final total is the fraction of spend with all labels valid, that is the indicator of the Crawl level.
"""Label coverage: how much spend has an owner? INVENTED workloads and costs.
The syntax of key and value is the one in the Kubernetes documentation on labels."""
import re
NOME = r"[A-Za-z0-9]([-_.A-Za-z0-9]{0,61}[A-Za-z0-9])?" # name segment: max 63, starts and ends alphanumeric
VALORE = re.compile(rf"^({NOME})?$") # the value may be empty
CHIAVE = re.compile(rf"^(([a-z0-9]([-a-z0-9]*[a-z0-9])?\.)*[a-z0-9]([-a-z0-9]*[a-z0-9])?/)?{NOME}$")
OBBLIGATORIE = ("team", "feature", "environment", "cost-center")
CARICHI = [ # (workload, monthly cost in EUR, labels)
("chat-api", 820.0, {"team": "backend", "feature": "chat", "environment": "prod", "cost-center": "cc-001"}),
("summaries", 410.0, {"team": "backend", "feature": "summaries", "environment": "prod", "cost-center": "cc-001"}),
("vector-index", 300.0, {"team": "ml-platform", "feature": "chat", "environment": "prod"}), # cost-center missing
("batch-embedding",260.0, {"team": "ml-platform", "environment": "prod", "cost-center": "cc-002"}), # feature missing
("agent-trials", 190.0, {"team": "Data Science", "feature": "agent", "environment": "dev", "cost-center": "cc-002"}), # value with a space
("old-job", 120.0, {}),
]
def problemi(label):
out = [f"missing {k}" for k in OBBLIGATORIE if k not in label]
for k, v in label.items():
if not CHIAVE.match(k): out.append(f"invalid key {k!r}")
if not VALORE.match(v): out.append(f"invalid value {v!r}")
return out
totale = sum(c for _, c, _ in CARICHI)
attribuita = 0.0
for nome, costo, label in CARICHI:
p = problemi(label)
if not p: attribuita += costo
print(f"{nome:16s} {costo:7.1f} EUR {'OK' if not p else '; '.join(p)}")
print(f"\nspend with all labels valid: {attribuita:.1f} of {totale:.1f} EUR = {attribuita / totale:.1%}")
print(f"workloads with valid labels: {sum(1 for _, _, l in CARICHI if not problemi(l))} of {len(CARICHI)}")
# Output:
# chat-api 820.0 EUR OK
# summaries 410.0 EUR OK
# vector-index 300.0 EUR missing cost-center
# batch-embedding 260.0 EUR missing feature
# agent-trials 190.0 EUR invalid value 'Data Science'
# old-job 120.0 EUR missing team; missing feature; missing environment; missing cost-center
#
# spend with all labels valid: 1230.0 of 2100.0 EUR = 58.6%
# workloads with valid labels: 2 of 6
With 2,100 euros of spend, only 58.6% has all four labels valid: below the 70% of the example target. What the listing shows you is the shape of the defects: a missing label (two cases), a value with a space and a workload with no labels at all, and each has a different remedy. Missing labels are prevented at the entrance, with a check that rejects the release (in Kubernetes this is done with an admission controller, not run here); the invalid value is fixed upstream; the orphan workload is assigned by hand once and then left to expire. A check that runs only as a report produces a list of defects that nobody receives; one that runs before the release produces a rejection that somebody reads.
Request context: tagging calls without rewriting functions
Infrastructure labels do not tell you which customer generated a single call. For that you need a request context: a value that enters when the request comes in, stays visible to all the code that request runs and disappears on the way out. In Python, for this purpose, there is the contextvars module, and the official documentation is explicit on a point that matters here: context-aware state should be kept in context variables and not in threading.local(), to prevent it from leaking out of its perimeter in concurrent code. Anyone using an asynchronous framework has exactly that case.
In the listing richiesta is a context manager that sets customer and feature on the way in and restores them on the way out with reset, even when the request fails; chiama_modello does not receive the customer as an argument and reads it from the context, so no intermediate function needs to know about it. The model is fake: the function only creates the cost event. The variables are created at module level, as the documentation recommends, and not inside a function.
"""Per-user attribution without passing the customer into every function: contextvars (standard library).
The 'middleware' is a context manager; the model is a FAKE. INVENTED data."""
from collections import Counter
from contextlib import contextmanager
from contextvars import ContextVar
CLIENTE: ContextVar[str | None] = ContextVar("customer", default=None)
FUNZIONE: ContextVar[str | None] = ContextVar("feature", default=None)
EVENTI: list[dict] = []
@contextmanager
def richiesta(cliente, funzione):
"""Sets the context when the request comes in and restores it on the way out, even with an exception."""
t1, t2 = CLIENTE.set(cliente), FUNZIONE.set(funzione)
try:
yield
finally:
CLIENTE.reset(t1); FUNZIONE.reset(t2)
def chiama_modello(token):
"""In a real application the call to the provider goes here: the event picks up the context on its own."""
EVENTI.append({"cliente": CLIENTE.get() or "UNATTRIBUTED", "funzione": FUNZIONE.get() or "UNATTRIBUTED",
"costo_eur": token * 2.0 / 1e6})
with richiesta("alpha", "chat"):
chiama_modello(1_500); chiama_modello(2_500)
with richiesta("beta", "summaries"):
chiama_modello(30_000)
try:
with richiesta("beta", "chat"):
chiama_modello(4_000)
raise RuntimeError("error halfway through the request")
except RuntimeError:
pass
chiama_modello(9_000) # a night job that nobody wrapped in richiesta()
somme = Counter()
for e in EVENTI:
somme[(e["cliente"], e["funzione"])] += e["costo_eur"]
for k, v in sorted(somme.items()):
print(f"{k[0]:15s} {k[1]:15s} {v:.6f} EUR")
tot = sum(somme.values())
print(f"share of unattributed spend: {sum(v for k, v in somme.items() if k[0] == 'UNATTRIBUTED') / tot:.1%}")
print("context after the requests:", CLIENTE.get(), FUNZIONE.get())
# Output:
# UNATTRIBUTED UNATTRIBUTED 0.018000 EUR
# alpha chat 0.008000 EUR
# beta chat 0.008000 EUR
# beta summaries 0.060000 EUR
# share of unattributed spend: 19.1%
# context after the requests: None None
The output shows three attributed rows and one "UNATTRIBUTED" row: the night job that nobody wrapped in the context manager weighs 19.1% of the spend, and beta's request that raised an exception is counted all the same, because the call to the model happened before the error. The last line confirms that the context is empty again after the requests. The design point is the unattributed row: it must not be hidden or discarded, it must be made visible and brought to zero, because it is the number that tells you where the instrumentation is missing. A second limit: the context does not cross process boundaries, so a call to another service must receive the customer in a header or a message field and restore it on the other side.
Shared costs: the rule must be chosen, and declared
The vector index costs a thousand euros a month and serves three features. Splitting it is a policy choice, not a calculation, and every rule has an effect on behaviour. The second listing splits the same amount with three rules: in proportion to direct cost, in proportion to the use of the index (here the queries) and in equal parts. It works in whole cents and uses the largest-remainder method, so the sum of the parts is exactly the total and no cent disappears in the rounding; an assertion checks it.
"""Splitting a shared cost (vector index, platform) across three features.
Three rules, same total, different numbers. INVENTED data; amounts in whole cents so nothing is lost."""
CONDIVISO = 1_000_00 # 1,000.00 EUR in cents
# How much each feature consumed, under different measures
diretto = {"chat": 820_00, "summaries": 410_00, "agent": 190_00} # direct cost in cents
richieste_indice = {"chat": 30_000, "summaries": 2_000, "agent": 8_000} # vector index queries
def ripartisci(totale, pesi):
"""Splits totale (int) in proportion to the weights with the largest-remainder method:
the sum of the parts is EXACTLY the total, with no cents disappearing."""
s = sum(pesi.values())
base = {k: totale * v // s for k, v in pesi.items()}
resto = totale - sum(base.values())
ordine = sorted(pesi, key=lambda k: (-(totale * pesi[k] % s), k)) # whoever has the highest fractional remainder
for k in ordine[:resto]:
base[k] += 1
return base
regole = {
"proportional to direct cost": ripartisci(CONDIVISO, diretto),
"proportional to index usage": ripartisci(CONDIVISO, richieste_indice),
"in equal parts": ripartisci(CONDIVISO, {k: 1 for k in diretto}),
}
for nome, parti in regole.items():
assert sum(parti.values()) == CONDIVISO
righe = " ".join(f"{k} {v / 100:7.2f}" for k, v in parti.items())
print(f"{nome:30s} {righe}")
print("\nfull cost per feature (direct + share)")
for nome, parti in regole.items():
righe = " ".join(f"{k} {(diretto[k] + parti[k]) / 100:8.2f}" for k in diretto)
print(f"{nome:30s} {righe}")
# Output:
# proportional to direct cost chat 577.47 summaries 288.73 agent 133.80
# proportional to index usage chat 750.00 summaries 50.00 agent 200.00
# in equal parts chat 333.33 summaries 333.33 agent 333.34
#
# full cost per feature (direct + share)
# proportional to direct cost chat 1397.47 summaries 698.73 agent 323.80
# proportional to index usage chat 1570.00 summaries 460.00 agent 390.00
# in equal parts chat 1153.33 summaries 743.33 agent 523.34
The full cost of the summaries feature goes from 698.73 euros with the rule proportional to direct cost to 460.00 with the usage rule, and to 743.33 with equal parts: the full cost of the same feature varies by more than 60% depending on the criterion, from 460.00 to 743.33 euros. The usage rule is the closest to the cause, because whoever queries the index more pays more, but it requires a measure you often do not have; proportion to direct cost is easy to compute but makes those who are already expensive pay more even if they do not use the index; equal parts are simple and almost always unfair, and make sense only for platforms that serve everybody in the same way. What you must not do is change the rule every month: choose a rule, write it down and review it at fixed intervals, otherwise every comparison between months becomes a comparison between rules.
Chargeback: three models and what they reward
The FinOps Foundation recommends starting with showback: showing each team its own cost, by project and by type of workload, before charging it, because visibility alone often changes behaviour. The real charge, chargeback, comes after the numbers have been accepted. To charge customers or teams, the most common models are three.
- Actual cost plus margin: the customer pays what it generated, with a percentage on top.
- Fixed fee: the customer pays an agreed figure, independent of use.
- Hybrid: a fee with a quota of use included, and beyond that threshold the actual cost plus margin.
The first rewards transparency and protects the margin, but makes the cost unpredictable for whoever pays; the second is predictable for the customer and leaves you the risk of heavy customers; the third is a compromise that caps the risk without turning the fee into a pay-per-use invoice. The third listing computes them with SQL on an events table, in an in-memory SQLite database: no file, no server. The 20% margin and the thresholds are parameters of the example.
"""Three chargeback models computed with SQL on an events table. IN-MEMORY SQLite (standard library):
no file, no server. The same constructs (CTE, CASE, SUM) work on PostgreSQL;
ClickHouse syntax differs in some functions and was not run here. INVENTED data."""
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE cost_events (cliente TEXT, funzione TEXT, giorno TEXT, costo_eur REAL);
INSERT INTO cost_events VALUES
('alpha','chat','2026-10-03', 40.0), ('alpha','chat','2026-10-17', 55.0), ('alpha','summaries','2026-10-20', 20.0),
('beta','chat','2026-10-05', 300.0), ('beta','summaries','2026-10-21', 150.0),
('gamma','agent','2026-10-09', 12.0);
CREATE TABLE contratto (cliente TEXT, canone_eur REAL, incluso_eur REAL);
INSERT INTO contratto VALUES ('alpha', 100.0, 150.0), ('beta', 100.0, 150.0), ('gamma', 100.0, 150.0);
""")
MARGINE = 1.20 # cost + 20%: a parameter of the example, not a recommendation
q = """
WITH speso AS (
SELECT cliente, SUM(costo_eur) AS costo FROM cost_events GROUP BY cliente
)
SELECT s.cliente,
ROUND(s.costo, 2) AS costo_reale,
ROUND(s.costo * :m, 2) AS costo_piu_margine,
c.canone_eur AS canone_fisso,
ROUND(c.canone_eur + MAX(0, s.costo - c.incluso_eur) * :m, 2) AS ibrido
FROM speso s JOIN contratto c USING (cliente)
ORDER BY s.cliente
"""
print(f"{'customer':8s}{'cost':>9s}{'cost+20%':>11s}{'fee':>9s}{'hybrid':>9s}")
for r in db.execute(q, {"m": MARGINE}):
print(f"{r[0]:8s}{r[1]:9.2f}{r[2]:11.2f}{r[3]:9.2f}{r[4]:9.2f}")
tot = db.execute("""SELECT SUM(costo_eur) FROM cost_events""").fetchone()[0]
ric_fisso = db.execute("SELECT SUM(canone_eur) FROM contratto").fetchone()[0]
print(f"\ntotal cost {tot:.2f} EUR; revenue with fixed fee {ric_fisso:.2f} EUR; margin of the fixed fee {ric_fisso - tot:+.2f} EUR")
for r in db.execute("SELECT cliente, canone_eur - SUM(costo_eur) FROM cost_events JOIN contratto USING (cliente) GROUP BY cliente ORDER BY 1"):
print(f" fixed-fee margin on {r[0]}: {r[1]:+.2f} EUR")
# Output:
# customer cost cost+20% fee hybrid
# alpha 115.00 138.00 100.00 100.00
# beta 450.00 540.00 100.00 460.00
# gamma 12.00 14.40 100.00 100.00
#
# total cost 577.00 EUR; revenue with fixed fee 300.00 EUR; margin of the fixed fee -277.00 EUR
# fixed-fee margin on alpha: -15.00 EUR
# fixed-fee margin on beta: -350.00 EUR
# fixed-fee margin on gamma: +88.00 EUR
With a fixed fee of 100 euros, customer beta, which generated 450 euros of cost, makes you lose 350 euros, and the total of the three customers is a loss of 277 euros even though only one of them is out of scale. The hybrid with 150 euros included brings it back to 460 euros, while for the small customers the bill stays equal to the fee. You also see the limit of these models: none of the three says whether the price the customer pays is right for the value it receives, and for that you need the other half of the discussion, that is the cost per outcome. The query uses only portable constructs (CTE, CASE, SUM) and also works on PostgreSQL; for ClickHouse some functions differ, and I did not run it there.
Frequently asked questions
Infrastructure labels or context in the code: which one do I need?
You need both, because they answer different questions. Labels attribute the cost of workloads (machines, volumes, services); the request context attributes the cost of every call to a model to a customer and a feature. If you have only the first you do not see the customer, if you have only the second you do not see the machine.
How much unattributed spend is acceptable?
The FinOps Foundation uses 70%, 85% and 90% of cost attributed to an owner as example targets for the three maturity levels. They are community references, not mandatory thresholds: the useful indicator is your own unattributed share, month after month.
Can I charge customers for the cost of a model used by several features?
Yes, but with a written, stable splitting rule. The direct cost of a call is attributed to the customer that generated it; the share of what is shared depends on the rule chosen, and as the second listing shows the full cost of the same feature changes by more than 60% between the most favourable and the least favourable criterion.
What you can do now
You can compute the share of spend with valid labels and read the result against a target, you can tag calls to the model with a context that does not pass through the intermediate functions, and you can bring the unattributed share into view. You can split a shared cost without losing cents, and you know that the rule changes the numbers more than it changes the spend. You can compare three chargeback models on an events table. The data in the listings is invented: replace it with your own and change the margins. The next step is to use this data to control spend within the month, in the article on the monthly cost; for the twelve-month forecast see the driver model, and for the map of the cost items the cost map.
Sources
- FinOps for AI Overview (FinOps Foundation) - allocate before optimising, example tag keys, mapping every API key to a team, showback before chargeback; consulted on 2026-11-13
- Maturity Model (FinOps Framework) - example targets for the share of attributed cost (70%, 85%, over 90%); consulted on 2026-11-13
- Labels and Selectors (Kubernetes documentation) - syntax of label keys and values, 63-character limit, prefix as a DNS subdomain; consulted on 2026-11-13
- OpenCost documentation - open-source, vendor-neutral project to measure and allocate container costs, for monitoring, showback and chargeback; consulted on 2026-11-13 (not run)
- contextvars - Context Variables (Python documentation) - context variables instead of
threading.local()in concurrent code, to be created at module level; consulted on 2026-11-13 - Local runs:
python3 -Ion the four listings (standard library, in-memory SQLite), each twice with identical output; workloads, costs and customers invented for the example

Commenti
Caricamento commenti...
Sign in to comment