11B.6 Budgets, Quotas, Cost Attribution and Chargeback
You already know how to price one call (03.7), cap one request, and cap one agent run (08A.2, 08A.3). This lesson is about the next level up: an organization. Many teams, many features and many users share one provider account. Someone has to decide who may spend how much, stop spending when the money runs out, and answer the question "who spent this?" at the end of the month. You will build a small budget ledger with a four-level hierarchy (organization, team, feature, user), wrap OpenAI and Anthropic calls with it, learn which attribution features the providers give you, and turn the totals into showback and chargeback reports.
What you'll learn
- The difference between a budget (dollars), a quota (tokens or requests as a share of capacity) and a rate limit (a speed limit), and when each one is the right tool
- A budget hierarchy (organization, team, feature, user): how a parent caps its children, why the sums are allowed to exceed the parent, and which level should block a call first
- Reserve-then-settle accounting across all levels at once, done atomically, with unknown costs, rolling windows and in-flight calls handled correctly
- How to count tokens before the call and turn the count into a safe worst-case estimate, and what a pessimistic estimate costs you
- Where to enforce: in each app, in a shared gateway, or at the provider, and why you want more than one
- Attribution: tags that travel with every call, and what OpenAI projects, Anthropic workspaces, Amazon Bedrock application inference profiles and LiteLLM budgets add (all checked on 1 December 2026)
- Showback and chargeback, standard-rate versus pass-through pricing, and how to allocate shared costs (vector database, tracing, committed capacity) without leaving a rounding gap
- A tiny evaluation that fails your build when cost data stops being trustworthy
What you don't need
- API keys. Every sample except the SDK reference snippets runs offline in plain Python with a fake clock. The provider calls are shown with offline stand-in clients, and their output is real output from those stand-ins.
- Docker, Redis or a database. The ledger is in memory; Part 3 explains what changes when you move it to a shared store, but you do not run one here.
- Rate limits, throughput options, kill switches and alerts: those are 11B.7. The cost of agents, long contexts, caching and evals is 11B.8.
Setup
Python 3.11+ and the standard library only. The SDK reference snippets in Part 5 use openai and anthropic; install them only if you want to run those against a real account.
uv init budgets --bare --python 3.13 && cd budgets
# nothing to install for the ledger, the demos and the tests
uv add openai anthropic # optional: only for the Part 5 reference snippets
# or: pip install openai anthropicAs of 1 December 2026. Provider facts in this lesson were read from the providers' documentation pages on that date and are marked with it. Prices are parameters in the code, never constants: check each provider's pricing page before you rely on a number. The two price rows used in the samples ($2 and $10 per million input and output tokens for Claude Sonnet 5.5, and $2 and $10 for gpt-6.2-sol, with cached input at $0.10 on both) were read on that date.
Every code block starts with a comment giving its file name. Save the files in one folder and run them with python3.
What you must be able to do after this lesson#
- Explain the difference between a budget, a quota and a rate limit, and pick the right one for a given control
- Design a four-level budget hierarchy (organization, team, feature, user) with windows in UTC and oversubscribed children
- Reserve a worst-case cost across every level atomically, settle the real cost, and keep the reservation when usage is unknown
- Test a budget ledger for the rules it must never break, including a concurrency test and a window roll with an open reservation
- Choose where to enforce a budget (app wrapper, gateway, provider) and set each layer at a different height
- Tag every call so spend can be attributed, then produce a showback report and allocate shared costs without a rounding gap
- Write a cost-data check that fails the build when tag coverage or reconciliation gets worse
Why this matters for an AI engineer#
A prototype has one bill and one owner. A product has ten features, four teams and a finance department. Without budgets, one team's runaway loop spends everyone's month. Without attribution, nobody can say whose feature is expensive. Without a ledger that is correct under concurrency, two requests can both see "$0.02 left" and both spend it.
| You'll hear... | You'll understand it after... |
|---|---|
| "Give every tenant a daily token quota." | 1.2 Budget, quota, limit and 3.1 The design |
| "The search team's loop ate the company's month." | 1.3 The hierarchy and Part 4 |
| "We reserve the worst case, then settle." | 2.1 The worst-case estimate and 3.3 Try it |
| "Tag every call with a team." | Part 5 |
| "Showback now, chargeback next quarter." | 6.1 Showback and chargeback |
| "Who pays for the shared vector database?" | 6.3 Allocating shared costs |
| "Our cost report is 9% off the invoice." | 6.4 Closing the month and Part 7 |
Part 1: The budget model#
1.1 What you already have, and what is missing#
Three earlier lessons built the lower layers. Do not rebuild them; use them.
| Layer | Where it lives | What it controls |
|---|---|---|
| One call | 03.7, Part 12 | max_output_tokens, a per-request cost guard, per-user daily budgets with reserve-then-settle |
| One agent run | 08A.2, 3.3 and 08A.3 | Steps, tokens, money and seconds for one execution |
| One tenant | 11B.1, 7.2 | A token quota for one tenant, with reserve and settle |
What none of them gives you is the organization view. Look at the three code samples above: each guards one number (one user, one run, one tenant). A real company needs several numbers that depend on each other: "this user may spend $2 a day, inside this feature's $200, inside this team's $3,000, inside the company's $20,000". It also needs one record of who spent what, so the same data can answer both "may this call go ahead?" and "what do we charge the search team?". That is this lesson.
1.2 Budget, quota, rate limit: three different things#
People use these words loosely. In this lesson they mean three different controls.
| Control | Unit | Question it answers | Resets | Example |
|---|---|---|---|---|
| Budget | Money (USD) | "How much may this owner spend?" | Per window (day or month) | The search team may spend $3,000 this month |
| Quota | Tokens or requests | "How much of the shared capacity may this owner use?" | Per window | Each tenant gets 5 million tokens a day |
| Rate limit | Tokens or requests per minute | "How fast may this owner go?" | Continuously (a token bucket) | Support may send 24,000 tokens per minute |
Why have both budgets and quotas? Dollars are what finance understands, and they stay meaningful when you switch models. Tokens are what the provider's rate limits count, and they are what you can promise a customer ("1 million tokens a month on this plan") without exposing your prices. A tenant plan is usually a quota. A team allowance is usually a budget. Rate limits are the subject of 11B.7.
This lesson's code stores dollars, because one ledger then covers every model and provider. If you need a token quota, the same code works with tokens as the unit (a token is just a smaller unit): 11B.1, 7.2 shows that form.
1.3 The hierarchy: organization, team, feature, user#
Most organizations need four levels. Each level protects against a different failure.
| Level | Typical owner | What it protects against | Typical window |
|---|---|---|---|
| Organization | Finance, platform team | Total spend over what the company agreed to pay; a leaked key | Month, plus a daily cap |
| Team | An engineering manager | One team starving the others; a team's project overrunning | Month |
| Feature | The product owner | One runaway feature (an agent loop, a re-run batch job) eating the team's month | Day or month |
| User or tenant | The product | One heavy user (a bot, a scraper, an abusive account) | Day |
A call belongs to one path, such as acme / support / triage-bot / user-7. Every level on that path must have room, or the call is refused. That is all-or-nothing: a denied call must not leave a half-held reservation on the levels that did have room.
Three design rules:
- A parent caps its children, and the children's limits may add up to more than the parent's. The team limits in the demo below are $0.15 each under an organization limit of $0.12. This is called oversubscription and it is deliberate: teams rarely all spend their full allowance at once, so sizing every child to fit inside the parent would leave most of the budget unused. The parent limit is the hard wall; the child limits are fairness guards.
- Name the level that blocked the call. "Denied" is useless to a support engineer. "Denied at
acme/support: $0.0199 left, call needs $0.0251" tells them which owner to talk to. The ledger below returns the blocking path. - Give lazily created levels a default. You will not pre-create a budget for each of ten thousand users. A default per-user limit applies to every user node the first time it appears.
1.4 Windows, units and time#
- Pick a window per level and say it out loud. A daily window on users catches abuse within hours. A monthly window on teams matches how finance plans. A level can have more than one window (a daily cap and a monthly cap); you check each.
- Use UTC for windows. A budget that resets at "midnight" for a team in Chennai, a user in Berlin and a server in Virginia is a support ticket. Several providers also reset on UTC: Anthropic's monthly spend cap restarts at 00:00 UTC on the first day of the month (as of 1 December 2026, from its rate limits page).
- Fixed windows are simple; sliding windows are smoother. A fixed daily window lets a user spend a full day's budget at 23:59 and again at 00:01. For a daily user cap that is usually fine. If it is not, use a rate limit as well (11B.7).
- Keep money as integers. Floating-point dollars drift: add
0.1ten million times and you are off by a visible amount. The ledger stores micro-dollars (1 USD = 1,000,000), so every sum is exact and a reconciliation to the cent is possible. - In-flight calls cross the window boundary. A call reserved at 23:59 may settle at 00:01. Its reservation must survive the reset (otherwise the new day starts oversubscribed), and its settlement must land in the new window. The code does exactly this, and a test proves it.
Part 2: Counting before the call#
2.1 The worst-case estimate#
A budget check is only a control if it happens before the call. Afterwards it is a report. Before the call, you do not know the real cost, so you reserve the worst case:
worst case = input_tokens x input_price + max_output_tokens x output_price- Input tokens you can count. Use a local estimate when the answer is not close to a limit, and the provider's counting endpoint when it is. 03.7, Part 2 teaches both and shows the OpenAI
responses.input_tokens.countand Anthropicmessages.count_tokenscalls. Count with the model you will actually call: Claude 4.7 and later use a tokenizer that produces about 30% more tokens for the same text than earlier Claude models (Anthropic pricing page, 1 December 2026), so an estimate tuned on an older model undercounts. - Output tokens you can only cap. The cap is
max_output_tokenson OpenAI andmax_tokenson Anthropic. Reasoning tokens count against the cap on both (03.7, 12.1). - Assume nothing is cached. Caching only lowers the real cost, so ignoring it keeps the estimate safe. (Cache write premiums can raise a cost above the plain input price; 11B.8 covers when. Add a small safety margin if you cache heavily with writes.)
- Take the long-context tier into account. Some models charge more for the whole request above a prompt-size threshold (Claude Haiku 5.5 above 100,000 tokens; OpenAI's long-context rates above 272,000 input tokens, both checked on 1 December 2026). Estimate with the tier the prompt size selects, or a request that crosses the line will cost several times what you reserved. 11B.8, Part 3 shows the cliff.
The ledger file below has estimate_input_tokens() (characters divided by 3, deliberately pessimistic) and worst_case_usd().
2.2 What a pessimistic estimate costs#
Reserving the worst case has a price: over-reservation. If a call reserves $0.025 but really costs $0.010, the extra $0.015 is locked until it settles. With many calls in flight at once, a small budget can look full while most of the "spent" money is only held.
You will see this in the demo: a user with a $0.04 daily limit is denied their third call while only $0.02 has actually been spent, because the third call would need $0.0251 of headroom.
Ways to shrink the gap, in order of effort:
- Lower the cap. A
max_output_tokensset from your measured p99 output length, not "2,000 just in case", cuts the worst case directly (03.7, 12.1). - Tighten the estimate per feature. Use the feature's own measured output p95 as the reserve, and keep the hard cap as a separate safety net.
- Settle quickly. Stream-then-settle holds the reservation for the length of the stream; long agent steps hold it longer.
- Size limits knowing the lock-up. If a user can have four calls in flight at $0.025 each, their effective daily headroom is $0.10 lower than the nominal limit at peak.
Do not fix over-reservation by reserving the expected cost. A budget that can be overrun by one expensive call is a report, not a control.
Part 3: The ledger#
3.1 The design#
The ledger has two operations that matter and one table that pays off later.
reserve(path, worst_case_usd, **tags)takes the call's path and worst-case cost. It checks every node from the root to the leaf under one lock. If any level lacks room it returns a denial naming that level and holds nothing. If all have room it holds the amount on all of them and returns aReservation.settle(reservation, actual_usd)releases the hold on every level and charges the real cost. PassingNonemeans "the call failed and I never saw usage": the reservation is kept as spent. Over-charging a budget by a few cents is better than letting failures spend for free (03.7, 12.3 says the same).eventsgets one row per settled call, with the tags you passed toreserve. That table is the showback report, the chargeback input and the reconciliation input. One ledger, three uses.
The window logic rolls a node when its window has elapsed: used resets, reserved does not.
3.2 The code#
# budget_ledger.py: a hierarchical budget ledger with atomic reserve and settle (lesson 11B.6)
"""Org > team > feature > user budgets. Money is kept as integer micro-dollars
(1 USD = 1_000_000) so sums never drift. Standard library only."""
from __future__ import annotations
import itertools
import threading
from dataclasses import dataclass, field
MICRO = 1_000_000
def usd(micros: int) -> str:
return f"${micros / MICRO:,.4f}"
class FakeClock:
"""A clock you control, so tests never sleep."""
def __init__(self, now: float = 0.0) -> None:
self.now = now
def __call__(self) -> float:
return self.now
def advance(self, seconds: float) -> None:
self.now += seconds
@dataclass
class Node:
path: tuple[str, ...]
limit: int | None = None # micro-dollars per window; None = no limit at this level
window_s: float = 86_400.0
used: int = 0
reserved: int = 0
window_start: float = 0.0
@dataclass(frozen=True)
class Reservation:
id: int
path: tuple[str, ...]
micros: int
tags: dict
@dataclass(frozen=True)
class Decision:
ok: bool
reservation: Reservation | None = None
blocked_at: tuple[str, ...] | None = None
reason: str = ""
class Ledger:
def __init__(self, clock=None) -> None:
self.clock = clock or FakeClock()
self._nodes: dict[tuple[str, ...], Node] = {}
self._defaults: dict[int, tuple[int, float]] = {} # depth -> (limit, window) for lazy nodes
self._open: dict[int, Reservation] = {}
self._ids = itertools.count(1)
self._lock = threading.Lock()
self.events: list[dict] = [] # one row per settled call: the tag table
# -- configuration ----------------------------------------------------------------------
def set_limit(self, path: tuple[str, ...], limit_usd: float, window_s: float = 86_400.0) -> None:
node = self._node(path)
node.limit, node.window_s = round(limit_usd * MICRO), window_s
def set_default(self, depth: int, limit_usd: float, window_s: float = 86_400.0) -> None:
"""Every node created lazily at this depth (for example each new user) gets this limit."""
self._defaults[depth] = (round(limit_usd * MICRO), window_s)
def _node(self, path: tuple[str, ...]) -> Node:
if path not in self._nodes:
node = Node(path, window_start=self.clock())
if len(path) in self._defaults:
node.limit, node.window_s = self._defaults[len(path)]
self._nodes[path] = node
return self._nodes[path]
def _roll(self, node: Node) -> None:
if self.clock() - node.window_start >= node.window_s:
node.used = 0 # reserved is NOT reset: in-flight calls still hold their estimate
node.window_start = self.clock()
# -- the two operations that matter ------------------------------------------------------
def reserve(self, path: tuple[str, ...], worst_case_usd: float, **tags) -> Decision:
"""All-or-nothing: every level from the org down to the leaf must have room, or nothing is held."""
need = round(worst_case_usd * MICRO)
with self._lock:
chain = [self._node(path[:i]) for i in range(1, len(path) + 1)]
for node in chain:
self._roll(node)
for node in chain: # check first ...
if node.limit is not None and node.used + node.reserved + need > node.limit:
left = node.limit - node.used - node.reserved
return Decision(False, blocked_at=node.path,
reason=f"{'/'.join(node.path)} has {usd(max(left, 0))} left, call needs {usd(need)}")
for node in chain: # ... then hold
node.reserved += need
res = Reservation(next(self._ids), path, need, dict(tags))
self._open[res.id] = res
return Decision(True, reservation=res)
def settle(self, res: Reservation, actual_usd: float | None) -> int:
"""Release the hold and charge the real cost. Unknown cost (None) keeps the reservation as spent."""
with self._lock:
if self._open.pop(res.id, None) is None:
raise ValueError(f"reservation {res.id} is not open (settled twice?)")
charged = res.micros if actual_usd is None else round(actual_usd * MICRO)
for i in range(1, len(res.path) + 1):
node = self._node(res.path[:i])
self._roll(node)
node.reserved -= res.micros
node.used += charged
self.events.append({"path": res.path, "micros": charged, "unknown": actual_usd is None, **res.tags})
return charged
# -- reading ----------------------------------------------------------------------------
def report(self, path: tuple[str, ...]) -> dict:
with self._lock:
node = self._node(path)
self._roll(node)
return {"path": "/".join(path), "limit": node.limit, "used": node.used, "reserved": node.reserved,
"remaining": None if node.limit is None else node.limit - node.used - node.reserved}
def worst_case_usd(price: dict, input_tokens: int, max_output_tokens: int) -> float:
"""Upper bound for one call: every input token uncached, the whole output allowance used."""
return (input_tokens * price["input"] + max_output_tokens * price["output"]) / 1e6
def estimate_input_tokens(text: str, chars_per_token: float = 3.0) -> int:
"""A deliberately pessimistic local estimate (fewer characters per token than English prose
averages). When the decision is close, use the provider's count endpoint instead (03.7)."""
return int(len(text) / chars_per_token) + 1
def chargeback(direct: dict[str, int], shared: dict[str, int], method: str = "proportional",
weights: dict[str, int] | None = None) -> dict[str, int]:
"""Allocate shared costs (micro-dollars) across teams. Result sums EXACTLY to direct + shared.
method: proportional (by direct spend), even, or weighted (agreed fixed weights)."""
teams = sorted(direct)
pool = sum(shared.values())
if method == "even":
w = {t: 1 for t in teams}
elif method == "weighted":
w = {t: (weights or {}).get(t, 0) for t in teams}
else:
w = dict(direct)
total_w = sum(w.values())
if total_w == 0:
raise ValueError("no weight to allocate shared costs against")
shares = {t: pool * w[t] // total_w for t in teams}
left = pool - sum(shares.values()) # largest-remainder rounding: hand out the last micros
for t in sorted(teams, key=lambda t: (-(pool * w[t] % total_w), t))[:left]:
shares[t] += 1
return {t: direct[t] + shares[t] for t in teams}Three details deserve a second look.
reserve()does its check in one loop and its hold in another, under one lock. Splitting the loops is what makes a denial leave nothing behind.chargeback()at the bottom hands out the last few micro-dollars by largest remainder, so the allocated total equals the real total exactly. Part 6 uses it.FakeClocklets every test and demo jump a day forward without sleeping. Passtime.timein production.
3.3 Try it: the ledger in action#
The demo builds the four-level tree with deliberately tiny limits so every outcome is visible: an organization limit of $0.12 a day, two teams at $0.15 each (oversubscribed), one feature at $0.10, and a default of $0.04 per user. Every call "uses" 40% of its worst case. Save as demo.py:
# demo.py: the ledger in action (lesson 11B.6). Run: python3 demo.py
from collections import defaultdict
from budget_ledger import FakeClock, Ledger, chargeback, estimate_input_tokens, usd, worst_case_usd
# Prices are parameters. These two rows are Anthropic list prices read on 2026-12-01 (USD per million tokens).
PRICES = {
"claude-sonnet-5-5": {"input": 2.00, "output": 10.00},
"claude-haiku-5-5": {"input": 0.10, "output": 0.50}, # prompts up to 100,000 tokens only
}
clock = FakeClock()
ledger = Ledger(clock)
ORG, SUPPORT, SEARCH = ("acme",), ("acme", "support"), ("acme", "search")
ledger.set_limit(ORG, 0.12) # the whole company: $0.12 a day (tiny, for the demo)
ledger.set_limit(SUPPORT, 0.15)
ledger.set_limit(SEARCH, 0.15) # 0.15 + 0.15 > 0.12: oversubscribed on purpose
ledger.set_limit(SUPPORT + ("triage-bot",), 0.10)
ledger.set_default(4, 0.04) # every user: $0.04 a day
question = "Where is my order? " * 400 # a long prompt (7,600 characters)
inp = estimate_input_tokens(question)
price = PRICES["claude-sonnet-5-5"]
worst = worst_case_usd(price, inp, max_output_tokens=2_000)
print(f"estimated input {inp:,} tokens; worst case for one call {usd(round(worst * 1e6))}")
def call(path, who, actual=None, **tags):
d = ledger.reserve(path, worst, **tags)
if not d.ok:
print(f" DENIED {who:<8} blocked at {'/'.join(d.blocked_at)}: {d.reason}")
return
ledger.settle(d.reservation, actual if actual is not None else worst * 0.4) # pretend the call used 40%
print(f" ok {who:<8} charged {usd(ledger.events[-1]['micros'])}")
print("\n1. A user hits the user budget ($0.04)")
bot = SUPPORT + ("triage-bot",)
for i in range(4):
call(bot + ("user-1",), "user-1", team="support", feature="triage-bot", user="user-1")
print("\n2. Other users of the same feature keep working; the feature budget ($0.10) is shared")
for u in ("user-2", "user-3", "user-4"):
call(bot + (u,), u, team="support", feature="triage-bot", user=u)
print("\n3. Search team spends; the ORG cap ($0.12) bites before the team cap ($0.15)")
for i in range(1, 9):
call(SEARCH + ("ranker", f"svc-{i}"), f"svc-{i}", team="search", feature="ranker", user=f"svc-{i}")
print("\n4. A failed call has unknown cost: the reservation stays as spent")
ledger.set_limit(ORG, 5.00) # raise the org cap so this step can run
before = ledger.report(ORG)["used"]
d = ledger.reserve(SEARCH + ("ranker", "svc-9"), worst, team="search", feature="ranker")
ledger.settle(d.reservation, None) # the stream broke: we never saw usage
print(f" org used {before} -> {ledger.report(ORG)['used']} micro-dollars (the whole {round(worst * 1e6)} reservation)")
print("\n5. The next day (fake clock +24h): used resets, nothing carried except open reservations")
clock.advance(86_400)
print(" org:", ledger.report(ORG))
print("\n6. Showback from tags, then chargeback with shared costs")
by_team = defaultdict(int)
for e in ledger.events:
by_team[e["team"]] += e["micros"]
print({t: usd(v) for t, v in sorted(by_team.items())})
shared = {"vector-db": 120_000, "tracing": 60_000} # micro-dollars: pretend $0.12 and $0.06
for method in ("proportional", "even"):
out = chargeback(dict(by_team), shared, method)
print(f" {method:<12}", {t: usd(v) for t, v in out.items()}, "total", usd(sum(out.values())))estimated input 2,534 tokens; worst case for one call $0.0251
1. A user hits the user budget ($0.04)
ok user-1 charged $0.0100
ok user-1 charged $0.0100
DENIED user-1 blocked at acme/support/triage-bot/user-1: acme/support/triage-bot/user-1 has $0.0199 left, call needs $0.0251
DENIED user-1 blocked at acme/support/triage-bot/user-1: acme/support/triage-bot/user-1 has $0.0199 left, call needs $0.0251
2. Other users of the same feature keep working; the feature budget ($0.10) is shared
ok user-2 charged $0.0100
ok user-3 charged $0.0100
ok user-4 charged $0.0100
3. Search team spends; the ORG cap ($0.12) bites before the team cap ($0.15)
ok svc-1 charged $0.0100
ok svc-2 charged $0.0100
ok svc-3 charged $0.0100
ok svc-4 charged $0.0100
ok svc-5 charged $0.0100
DENIED svc-6 blocked at acme: acme has $0.0197 left, call needs $0.0251
DENIED svc-7 blocked at acme: acme has $0.0197 left, call needs $0.0251
DENIED svc-8 blocked at acme: acme has $0.0197 left, call needs $0.0251
4. A failed call has unknown cost: the reservation stays as spent
org used 100270 -> 125338 micro-dollars (the whole 25068 reservation)
5. The next day (fake clock +24h): used resets, nothing carried except open reservations
org: {'path': 'acme', 'limit': 5000000, 'used': 0, 'reserved': 0, 'remaining': 5000000}
6. Showback from tags, then chargeback with shared costs
{'search': '$0.0752', 'support': '$0.0501'}
proportional {'search': '$0.1832', 'support': '$0.1221'} total $0.3053
even {'search': '$0.1652', 'support': '$0.1401'} total $0.3053Read it step by step.
- Step 1.
user-1gets two calls through and is denied the third and fourth. Only $0.02 has been charged, but the next call needs $0.0251 of headroom and the user has $0.0199 left. That is over-reservation (2.2) made visible. - Step 2. Other users of the same feature are unaffected by
user-1's limit. They share the feature's $0.10; it has used $0.02 so far and reaches $0.05 after these three calls, so all three pass. - Step 3. The search team ($0.15 limit) is blocked at the organization level after five calls, because the support team already used part of the company's $0.12. The message names
acme, notacme/search. Neither team broke its own limit; the parent ran out first. That is oversubscription doing its job. - Step 4. A call whose stream broke settles with
None, and the whole reservation ($0.025068) is charged. The organization total moves by exactly that amount. - Step 5. A day later
usedis zero. Nothing else carries over, because no reservation was left open. - Step 6. The
eventstable, grouped by theteamtag, gives the showback.chargeback()then adds $0.18 of shared costs, once in proportion to direct spend and once evenly. Both totals are $0.3053, to the micro-dollar.
3.4 Tests that prove the rules#
A ledger that is not tested under concurrency is a ledger you cannot trust. These ten tests cover the rules in 3.1: a denial holds nothing at any level, the tightest level names itself, settle charges the actual amount, unknown cost keeps the reservation, double settle is an error, windows roll while open reservations carry over, 60 threads never oversell, defaults apply to new users, and allocations sum exactly. Save as test_budget_ledger.py:
# test_budget_ledger.py: the rules the ledger must never break (lesson 11B.6). Run: python3 -m unittest -v
import threading
import unittest
from budget_ledger import MICRO, FakeClock, Ledger, chargeback
ORG, TEAM, LEAF = ("o",), ("o", "t"), ("o", "t", "u")
class LedgerTests(unittest.TestCase):
def make(self, org=1.0, team=0.5, leaf=0.2):
clock = FakeClock()
ledger = Ledger(clock)
ledger.set_limit(ORG, org)
ledger.set_limit(TEAM, team)
ledger.set_limit(LEAF, leaf)
return ledger, clock
def test_denial_holds_nothing_at_any_level(self):
ledger, _ = self.make(leaf=0.1)
self.assertFalse(ledger.reserve(LEAF, 0.2).ok)
for path in (ORG, TEAM, LEAF):
self.assertEqual(ledger.report(path)["reserved"], 0)
def test_the_tightest_level_names_itself(self):
ledger, _ = self.make(org=0.3, team=0.5, leaf=0.4)
d = ledger.reserve(LEAF, 0.35)
self.assertEqual(d.blocked_at, ORG)
def test_settle_charges_actual_and_releases_the_rest(self):
ledger, _ = self.make()
d = ledger.reserve(LEAF, 0.10)
ledger.settle(d.reservation, 0.04)
r = ledger.report(LEAF)
self.assertEqual((r["used"], r["reserved"]), (round(0.04 * MICRO), 0))
def test_unknown_cost_keeps_the_reservation_as_spent(self):
ledger, _ = self.make()
d = ledger.reserve(LEAF, 0.10)
self.assertEqual(ledger.settle(d.reservation, None), round(0.10 * MICRO))
self.assertEqual(ledger.report(ORG)["used"], round(0.10 * MICRO))
def test_double_settle_is_an_error(self):
ledger, _ = self.make()
d = ledger.reserve(LEAF, 0.01)
ledger.settle(d.reservation, 0.01)
with self.assertRaises(ValueError):
ledger.settle(d.reservation, 0.01)
def test_window_rolls_but_open_reservations_carry_over(self):
ledger, clock = self.make()
done = ledger.reserve(LEAF, 0.05)
ledger.settle(done.reservation, 0.05)
in_flight = ledger.reserve(LEAF, 0.10) # reserved at 23:59 ...
clock.advance(86_400) # ... and the day ends
r = ledger.report(LEAF)
self.assertEqual((r["used"], r["reserved"]), (0, round(0.10 * MICRO)))
ledger.settle(in_flight.reservation, 0.06) # settles into the NEW window
self.assertEqual(ledger.report(LEAF)["used"], round(0.06 * MICRO))
def test_concurrent_reserves_never_oversell(self):
ledger, _ = self.make(org=100, team=100, leaf=1.0) # leaf holds exactly ten 0.1 reservations
results = []
def worker():
results.append(ledger.reserve(LEAF, 0.1).ok)
threads = [threading.Thread(target=worker) for _ in range(60)]
[t.start() for t in threads]
[t.join() for t in threads]
self.assertEqual(sum(results), 10)
def test_default_limit_applies_to_new_users(self):
ledger, _ = self.make()
ledger.set_default(3, 0.05)
self.assertFalse(ledger.reserve(("o", "t", "new-user"), 0.06).ok)
self.assertTrue(ledger.reserve(("o", "t", "new-user"), 0.04).ok)
class ChargebackTests(unittest.TestCase):
def test_allocation_sums_exactly(self):
direct = {"a": 333_333, "b": 333_333, "c": 333_334}
for method in ("proportional", "even"):
out = chargeback(direct, {"db": 100_001}, method)
self.assertEqual(sum(out.values()), sum(direct.values()) + 100_001)
def test_weighted_uses_agreed_weights(self):
out = chargeback({"a": 0, "b": 0}, {"db": 1_000}, "weighted", {"a": 3, "b": 1})
self.assertEqual(out, {"a": 750, "b": 250})
if __name__ == "__main__":
unittest.main()Run python3 -m unittest -v and you get real output:
test_allocation_sums_exactly (test_budget_ledger.ChargebackTests.test_allocation_sums_exactly) ... ok
test_weighted_uses_agreed_weights (test_budget_ledger.ChargebackTests.test_weighted_uses_agreed_weights) ... ok
test_concurrent_reserves_never_oversell (test_budget_ledger.LedgerTests.test_concurrent_reserves_never_oversell) ... ok
test_default_limit_applies_to_new_users (test_budget_ledger.LedgerTests.test_default_limit_applies_to_new_users) ... ok
test_denial_holds_nothing_at_any_level (test_budget_ledger.LedgerTests.test_denial_holds_nothing_at_any_level) ... ok
test_double_settle_is_an_error (test_budget_ledger.LedgerTests.test_double_settle_is_an_error) ... ok
test_settle_charges_actual_and_releases_the_rest (test_budget_ledger.LedgerTests.test_settle_charges_actual_and_releases_the_rest) ... ok
test_the_tightest_level_names_itself (test_budget_ledger.LedgerTests.test_the_tightest_level_names_itself) ... ok
test_unknown_cost_keeps_the_reservation_as_spent (test_budget_ledger.LedgerTests.test_unknown_cost_keeps_the_reservation_as_spent) ... ok
test_window_rolls_but_open_reservations_carry_over (test_budget_ledger.LedgerTests.test_window_rolls_but_open_reservations_carry_over) ... ok
----------------------------------------------------------------------
Ran 10 tests in 0.003s
OK3.5 From in-memory to production#
The in-memory ledger is the tested logic and the seam for unit tests. In production the store must be shared by every process that makes model calls, and the "check all levels, then hold" step must stay atomic across a network. Three practical shapes (described here, not run in this lesson):
| Store | How to keep reserve atomic | Watch out for |
|---|---|---|
| Redis | One Lua script that reads every level's counters, checks them, and increments all of them, or none. Redis runs a script without interleaving other commands | Keys per level and per window (budget:acme:support:2026-12-01); set a TTL on window keys; one script per call means the levels must live on one shard (use hash tags) |
| PostgreSQL | One transaction that locks the level rows in a fixed order (organization first, then team, feature, user) with SELECT ... FOR UPDATE, checks, and updates |
Always lock in the same order or two transactions deadlock; keep the transaction short and never hold it open across the model call |
| A gateway's database | The gateway does it for you (see Part 4) | Check that budgets are actually enforced: LiteLLM's proxy, for example, needs a Postgres database or budgets are not enforced (its docs, 1 December 2026) |
Whatever the store, four extras matter in production:
- An idempotency key per reservation. A retry of "reserve" after a network blip must not hold the money twice. Key it by request ID.
- A sweeper for stale reservations. If a worker dies between
reserveandsettle, its hold never releases. Give every reservation a timestamp and release (as spent, to be safe) any older than the longest call you allow. The demo comment in 11B.1, 7.2 names the same leak. - An append-only event log next to the counters. Counters are fast; the log is the audit trail and the thing you reconcile against the invoice. If they disagree, the log wins.
- Fail-closed or fail-open, decided per level. If the store is down, do you refuse calls (safe, but an outage of your ledger becomes an outage of your product) or allow them (available, but unmetered)? 11B.7, 4.3 gives the rule of thumb: closed for expensive or risky features, open only for cheap ones, and always alert.
Part 4: Where to enforce#
A budget check can live in three places. Each sees different things and each can be bypassed in a different way.
| Place | What it sees | Strength | Weakness |
|---|---|---|---|
| Your app code (a wrapper around the SDK, like the one below) | The user, the feature, the prompt, the agent run | Knows the business context; can downgrade a model instead of refusing | Every service must use the wrapper; one forgotten call site is unmetered |
| A shared gateway (a proxy every service calls, 11C.3) | Every call that goes through it | One enforcement point, language-neutral, can require a team tag on every call | Sees only what callers tell it; one more thing that can go down |
| The provider (project or workspace spend limits, org hard limits) | All traffic on the account | Cannot be bypassed by your code; protects against a leaked key | Coarse (a project or workspace, not a user), a circuit breaker rather than a budget, and its error looks different (see below) |
The professional answer is all three, set at different heights: a provider limit well above normal spend, your gateway or app limits below it, and alerts on both (03.7, 12.4).
4.1 Provider-side limits that exist (checked 1 December 2026)#
| Provider | What you can set | Notes |
|---|---|---|
| OpenAI | Organization spend alerts and a hard monthly spend limit; per-project rate and spend limits (OpenAI's production best practices page) | Project limits cannot exceed organization limits. Use a separate project for staging and production and a service account per application. 03.7 12.4 has the admin API calls (amounts in cents) |
| Anthropic | A monthly organization spend limit below your tier's cap; per-workspace spend limits and rate limits (rate limits page and workspaces page) | A workspace limit cannot be above the organization's. Hitting a limit you set returns 400 invalid_request_error; hitting your tier's cap returns 429 rate_limit_error with no retry-after. 03.8, 4.2 teaches the difference. Per-user monthly spend limits exist only in the Claude Code workspace |
| A gateway | LiteLLM proxy: budgets at the global, team, team-member, internal-user, virtual-key and customer level, each with max_budget and budget_duration; tpm_limit and rpm_limit per key, user or team |
LiteLLM's docs say budgets need a Postgres database; without one they are not enforced. Other gateways have similar features; check each one's docs |
A provider-side limit is a circuit breaker, not a budget: when it trips, every feature on that project or workspace stops at once. That is why you keep it high and keep your own budgets lower.
4.2 The wrapper#
This is the app-layer enforcement point: estimate, reserve, call, read usage, price it, settle. It is written for the real openai and anthropic SDKs, and offline it runs against stand-in clients with the same response shape. Anthropic's usage.input_tokens counts only tokens after the last cache breakpoint, with cache reads and writes reported in separate fields; OpenAI's usage.input_tokens includes the cached part, which input_tokens_details.cached_tokens reports as a subset (03.7 normalizes these). Save as guarded_call.py next to budget_ledger.py:
# guarded_call.py: reserve, call, settle: one wrapper for OpenAI and Anthropic (lesson 11B.6)
"""The wrapper takes any client object shaped like the official SDK. Offline we pass stand-ins;
in production you pass openai.OpenAI() or anthropic.Anthropic(). Standard library only."""
from __future__ import annotations
from types import SimpleNamespace as NS
from budget_ledger import Ledger, estimate_input_tokens, usd
# USD per million tokens: (input, cached or cache-read input, output). Read 2026-12-01 from the providers' pricing pages.
PRICES = {
("anthropic", "claude-sonnet-5-5"): (2.00, 0.10, 10.00),
("openai", "gpt-6.2-sol"): (2.00, 0.10, 10.00),
}
def usage_usd(provider: str, model: str, usage) -> float:
"""Turn a provider usage object into dollars. Anthropic reports uncached input separately from cache reads;
OpenAI's input_tokens INCLUDES the cached part, so the cached share is subtracted. (Cache WRITE premiums
are left out here: see 11B.8 and 11B.4.)"""
inp, cached, out = PRICES[(provider, model)]
if provider == "anthropic":
fresh, read = usage.input_tokens, getattr(usage, "cache_read_input_tokens", 0) or 0
write = getattr(usage, "cache_creation_input_tokens", 0) or 0
return ((fresh + write) * inp + read * cached + usage.output_tokens * out) / 1e6
read = usage.input_tokens_details.cached_tokens
return ((usage.input_tokens - read) * inp + read * cached + usage.output_tokens * out) / 1e6
def guarded_call(ledger: Ledger, path: tuple[str, ...], client, provider: str, model: str,
prompt: str, max_output_tokens: int, **tags):
inp, _, out = PRICES[(provider, model)]
worst = (estimate_input_tokens(prompt) * inp + max_output_tokens * out) / 1e6 # nothing cached, output cap used
decision = ledger.reserve(path, worst, provider=provider, model=model, **tags)
if not decision.ok:
return None, decision.reason # a typed refusal the caller can show or log
try:
if provider == "openai":
resp = client.responses.create(model=model, input=prompt, max_output_tokens=max_output_tokens)
else:
resp = client.messages.create(model=model, max_tokens=max_output_tokens,
messages=[{"role": "user", "content": prompt}])
actual = usage_usd(provider, model, resp.usage)
except Exception:
ledger.settle(decision.reservation, None) # unknown cost: keep the whole reservation
raise
ledger.settle(decision.reservation, actual)
return resp, f"charged {usd(round(actual * 1e6))} (reserved {usd(decision.reservation.micros)})"
# ---- offline stand-ins shaped like the SDK responses (NOT real API replies) -----------------------------
class FakeOpenAI:
responses = NS(create=lambda **kw: NS(usage=NS(input_tokens=3_000, output_tokens=400,
input_tokens_details=NS(cached_tokens=2_048))))
class FakeAnthropic:
messages = NS(create=lambda **kw: NS(usage=NS(input_tokens=200, cache_read_input_tokens=2_800,
cache_creation_input_tokens=0, output_tokens=400)))
class BrokenAnthropic:
@staticmethod
def _boom(**kw):
raise TimeoutError("stream broke before usage arrived")
messages = NS(create=_boom)
if __name__ == "__main__":
ledger = Ledger()
ledger.set_limit(("acme",), 0.03)
path = ("acme", "support", "triage-bot", "user-7")
prompt = "Summarise this ticket. " * 300
for provider, model, client in (("openai", "gpt-6.2-sol", FakeOpenAI), ("anthropic", "claude-sonnet-5-5", FakeAnthropic)):
resp, note = guarded_call(ledger, path, client, provider, model, prompt, 800, team="support", feature="triage-bot")
print(f"{provider:<10} {note}")
try:
guarded_call(ledger, path, BrokenAnthropic, "anthropic", "claude-sonnet-5-5", prompt, 800, team="support")
except TimeoutError as e:
print("anthropic call failed:", e, "-> reservation kept as spent")
resp, note = guarded_call(ledger, path, FakeOpenAI, "openai", "gpt-6.2-sol", prompt, 800, team="support")
print("openai ", note)
print(ledger.report(("acme",)))Output from the offline stand-ins (these are not real API replies; they only prove the wiring):
openai charged $0.0061 (reserved $0.0126)
anthropic charged $0.0047 (reserved $0.0126)
anthropic call failed: stream broke before usage arrived -> reservation kept as spent
openai acme has $0.0066 left, call needs $0.0126
{'path': 'acme', 'limit': 30000, 'used': 23391, 'reserved': 0, 'remaining': 6609}Reading it: the OpenAI call reserved $0.0126 and settled at $0.0061 because 2,048 of its 3,000 input tokens were cached. The Anthropic call settled at $0.0047 for the same reason. The third call timed out before usage arrived, so its whole reservation was kept as spent. The fourth call was refused because only $0.0066 was left. Both real SDK calls take the same arguments the stand-ins accept: client.responses.create(model=..., input=..., max_output_tokens=...) on OpenAI and client.messages.create(model=..., max_tokens=..., messages=[...]) on Anthropic. In production, also read the cache write tokens (cache_creation_input_tokens on Anthropic, cache_write_tokens on GPT-5.6 and later) as 11B.8 explains; the sample leaves write premiums out to stay short.
4.3 Downgrade or refuse#
When a reservation is denied, the app can downgrade to a cheaper model, shrink the output cap, queue the work for a batch window, or refuse with a clear message. 03.7, 12.2 teaches the ladder and its two rules (every rung must pass your evals for that feature, and every refusal needs a user message and a log line), and 07.11, 4.10 shows staged degradation before the hard stop. The only addition at organization level is to log the blocking path that the ledger returns, so support can tell which owner ran out. 11B.5 covers which model to fall back to.
Part 5: Attribution: tags, projects and workspaces#
Deep-dive
You can only allocate spend you tagged. Attribution has two halves, and you want both.
5.1 Your own tags#
Every reserve() call above accepts tags (team, feature, user, env, provider, model), and they land in the events table on settle. Rules that keep the table useful:
- A small, fixed vocabulary.
teamandfeaturecome from a registry (a YAML file in your repo is enough), not from free text. A typo creates a phantom team. - Required tags fail closed. At the gateway or wrapper, refuse a call with no
teamtag. Untagged spend is the number-one reason chargeback reports are wrong. If you cannot refuse (legacy code), send untagged calls to a clearly namedunallocatedbucket with an owner and a shrinking target. - Do not put personal data in tags. Use a hashed or pseudonymous user ID (03.2, 10.3). Tags end up in logs, dashboards and finance spreadsheets.
- Tag at span-creation time, as 11B.1, 7.4 says: tracing already carries
featureandtenant_hash, so the trace is the tag table (11A.1, 2.6).
5.2 What the providers carry#
As of 1 December 2026, checked against each provider's documentation.
| Provider | Attribution unit | How you reach it | What it gives you |
|---|---|---|---|
| OpenAI | Projects (and API keys, service accounts) | One project per environment and per major feature or team; per-project rate and spend limits | The organization Usage and Costs APIs group by project_id, api_key_id, user_id, line_item, model, service_tier and more (03.7, 13.1; fields as recorded there in November 2026) |
| Anthropic | Workspaces (and API keys) | Create a workspace per team, environment or product. The default workspace cannot be renamed or deleted; an organization can have up to 1,000 workspaces by default; the anthropic-workspace-id response header tells you which workspace a request counted against |
The Usage and Cost Analytics API (beta) groups by workspace_id, api_key_id, model, service_tier, actor and more (03.7, 13.2). Cost rows are after discounts and before credits |
| Amazon Bedrock | Application inference profiles | Create a profile per application or team, with tags; invoke the model through the profile's ARN |
Usage and cost are tracked per profile, and the tags feed AWS cost allocation tags (Bedrock inference profile docs) |
| Azure | Resource tags and PTU reservation scoping | Tag the resource; scope a reservation to subscriptions or resource groups | Microsoft Cost Management can distribute reservation costs across teams ("Charge back Azure Reservation costs", linked from the Foundry provisioned throughput page) |
| Gemini / Vertex AI | Google Cloud projects and billing labels | One project per environment and feature | Cloud Billing reports and BigQuery export, daily (03.7, 13.3) |
Reading the Anthropic and OpenAI APIs is a reporting-job task. They need admin-level credentials that can read the whole organization, so keep those keys out of the application that serves users (03.7, Part 13). The Anthropic call that groups by workspace is, per its documentation:
# illustrative: needs an Anthropic Admin API key (not a workspace key). Beta endpoint, checked 2026-12-01.
import anthropic
client = anthropic.Anthropic(api_key=ADMIN_KEY) # read from your secret manager, never hard-code
rows = client.beta.organization.analytics.usage.list(
starting_at="2026-11-01T00:00:00Z", ending_at="2026-12-01T00:00:00Z",
time_bucket_width="1d", group_by=["workspace_id"])
for row in rows:
print(row.starting_at, row.group.workspace_id, row.usage.total_tokens)# illustrative: needs an OpenAI admin key. Pattern from lesson 03.7 (13.1).
from openai import OpenAI
admin = OpenAI(admin_api_key=ADMIN_KEY)
costs = admin.admin.organization.usage.costs(
start_time=START, end_time=END, bucket_width="1d", group_by=["project_id", "line_item"])Part 6: Showback, chargeback and shared costs#
Deep-dive
6.1 Showback and chargeback#
- Showback reports what each team spent. Nobody is billed. It builds awareness, finds the untagged spend, and costs almost nothing: it is a
GROUP BY teamon theeventstable. - Chargeback moves the money: the finance system actually debits each team's cost center. It changes behavior faster and creates arguments, so you want clean data first.
Start with showback for one or two months. Fix the tag gaps and the reconciliation drift (6.4). Then switch to chargeback with a published method. This is the same advice as 11B.1, 7.4, now with the ledger that produces the numbers. Cost per resolved outcome, the number a product is priced on, is 13A.6, 6.2.
6.2 What price do teams pay?#
| Method | How | When it fits |
|---|---|---|
| Pass-through | Teams pay exactly what the provider charged | Small organizations; full transparency. Teams feel every price change and every discount you negotiate |
| Standard rate (internal price list) | Teams pay a fixed internal price per token class, updated quarterly | Larger organizations. It hides the noise of provider price changes and lets the platform team keep the difference (or the loss) while it renegotiates |
| Pass-through plus a platform fee | Cost plus a percentage for the gateway, tracing, evals and on-call | When the platform team has real costs of its own; publish the percentage |
Whichever you pick, publish it, and say what happens when the provider's price changes mid-month (03.7 Part 4 keeps prices with valid_from dates for exactly this).
6.3 Allocating shared costs#
Some costs belong to nobody in particular: the vector database, the tracing platform, the gateway, committed capacity (11B.1, 1.4 lists them). The chargeback() function allocates them three ways.
| Method | Rule | Good for | Problem |
|---|---|---|---|
| Proportional to direct spend | Your share = your direct cost / total direct cost | The default; heavy users pay more | A team that is cheap on tokens but uses the vector database heavily is under-charged |
| Even split | Every team pays the same | Small fixed platform costs (the gateway) | Punishes the tiny team |
| Fixed weights | Agreed percentages (60/30/10) | When a driver is measurable but not in the ledger (index size, GB stored) | Weights go stale; review them quarterly |
Look at the demo output in 3.3: with $0.18 shared, proportional charges search $0.2340 and support $0.1365, while even gives $0.2103 and $0.1602. Both sum to $0.3053. The choice moves about $0.02 between the teams: the method is a policy decision, so write it down.
Two traps. First, rounding: dividing $100 between three teams gives $33.33 three times and loses a cent. chargeback() hands out the leftover micro-dollars by largest remainder so the total is exact (a test proves it). Second, committed capacity (provisioned throughput, committed-use discounts) is paid whether or not it is used. Allocate it by each team's share of the commitment, not its share of tokens, or the team that sized the commitment pays nothing for the idle part (11B.7, Part 3).
6.4 Closing the month, and reconciling#
At month end, compare your ledger with the provider's own numbers per project or workspace. 03.7, 13.5 has the script, and 03.7, 13.2 lists the data's freshness and what its cost rows include (recorded in November 2026). Four decisions follow from those facts.
- Close on day 8, not day 1. Anthropic's analytics data can take up to 24 hours and values can be revised for about 7 days after month end.
- Say whether teams are charged before or after credits and discounts. Anthropic's cost rows are after discounts and before credits.
- Allocate priority or committed spend separately (6.3). Anthropic's analytics shows Priority Tier requests with zero token cost because the commitment fee is billed separately.
- Give untagged and unknown spend an owner. Report them as their own rows, with a target to shrink them.
Projecting next quarter's spend from these numbers (a growth-rate forecast with forecast_monthly()) is 11B.1, 7.5. This lesson does not cover forecasting.
Part 7: Evaluate it#
Budget and attribution code is not a model, but it still needs an evaluation: a set of checks with a pass rule, run in CI, so a deploy that forgets a tag or breaks pricing fails loudly. Modules 10A and 10B teach evaluation. Start with the concept lessons in 10A, then the DeepEval lessons in 10B, then the optional Inspect lessons.
What to measure for this lesson's topic
- Budget invariants.
used + reserved <= limitat every level, always (a property test with random calls and a fake clock). - Tag coverage. The share of spend with every required tag.
- Unknown-cost share. The share of spend charged as "reservation kept because usage was unknown".
- Reconciliation error. Your total against the provider's cost report for the same period.
- Cost per successful task for each feature, which is the unit chargeback should ultimately report for agents (10A.7, 5.6 and 6.3).
A concrete tiny eval. Inputs: the ledger's events for one day (here 2,000 synthetic calls) and the provider's cost total. Metrics and pass rule: untagged share at most 1%, unknown-cost share at most 1%, reconciliation within 3%; overall pass only if all three pass. Save as attribution_check.py:
# attribution_check.py: three pass/fail checks on your own cost data (lesson 11B.6)
"""Inputs: the ledger's settled events and the provider's cost total for the same day.
Checks: (1) tag coverage, (2) unknown-cost share, (3) reconciliation within a tolerance."""
import random
from budget_ledger import MICRO, Ledger
REQUIRED_TAGS = ("team", "feature")
MAX_UNTAGGED_SHARE = 0.01 # at most 1% of spend may lack a required tag
MAX_UNKNOWN_SHARE = 0.01 # at most 1% of spend may be "reservation kept, real cost unknown"
RECONCILE_TOLERANCE = 0.03 # tracker and provider within 3%
def check(events: list[dict], provider_total_micros: int) -> list[tuple[str, bool, str]]:
total = sum(e["micros"] for e in events)
untagged = sum(e["micros"] for e in events if any(not e.get(t) for t in REQUIRED_TAGS))
unknown = sum(e["micros"] for e in events if e["unknown"])
delta = abs(total - provider_total_micros) / provider_total_micros
return [
("tag coverage", untagged / total <= MAX_UNTAGGED_SHARE, f"untagged share {untagged / total:.2%} (max {MAX_UNTAGGED_SHARE:.0%})"),
("unknown cost", unknown / total <= MAX_UNKNOWN_SHARE, f"unknown-cost share {unknown / total:.2%} (max {MAX_UNKNOWN_SHARE:.0%})"),
("reconciliation", delta <= RECONCILE_TOLERANCE, f"tracker ${total / MICRO:,.2f} vs provider ${provider_total_micros / MICRO:,.2f}, off by {delta:.2%} (max {RECONCILE_TOLERANCE:.0%})"),
]
def synthetic_day(untagged_every: int, seed: int = 11) -> tuple[list[dict], int]:
rng = random.Random(seed)
ledger = Ledger()
provider_total = 0
for i in range(1, 2_001):
cost = round(rng.uniform(0.002, 0.03), 6)
tags = {"team": rng.choice(["support", "search"]), "feature": rng.choice(["triage-bot", "ranker"])}
if untagged_every and i % untagged_every == 0:
tags.pop("team") # a call site that forgot the tag
d = ledger.reserve(("acme", "x"), 0.05, **tags)
ledger.settle(d.reservation, cost)
provider_total += round(cost * MICRO) * 1.004 # provider's number is a hair higher: late records
return ledger.events, int(provider_total)
for label, every in (("healthy day", 0), ("a deploy forgot the team tag on 1 call in 20", 20)):
events, provider = synthetic_day(every)
print(f"== {label}")
results = check(events, provider)
for name, ok, detail in results:
print(f" {'PASS' if ok else 'FAIL'} {name:<15} {detail}")
print(" overall:", "PASS" if all(ok for _, ok, _ in results) else "FAIL")== healthy day
PASS tag coverage untagged share 0.00% (max 1%)
PASS unknown cost unknown-cost share 0.00% (max 1%)
PASS reconciliation tracker $32.05 vs provider $32.17, off by 0.40% (max 3%)
overall: PASS
== a deploy forgot the team tag on 1 call in 20
FAIL tag coverage untagged share 4.33% (max 1%)
PASS unknown cost unknown-cost share 0.00% (max 1%)
PASS reconciliation tracker $32.05 vs provider $32.17, off by 0.40% (max 3%)
overall: FAILThe second run models a deploy that forgot the team tag on one call in twenty. Cost and reconciliation are fine, but 4.33% of spend is now unallocatable, so the check fails. That is the failure that silently corrupts a chargeback report, and it is exactly what a cost-data eval exists to catch.
Where to go next in Modules 10A and 10B
- Concept lessons first: 10A.7 Evaluating Agents, Tool Use and Multimodal Systems (task success and cost per successful task), 10A.8 Regression Testing, CI and Experiment Tracking (run budgets in CI), 10A.11 Evaluating Agent Memory and Context Management and 10A.12 Evaluating Multi-Agent Systems and Validating User Simulators (cost per task for multi-agent setups).
- DeepEval (required track): 10B.2 DeepEval fundamentals, 10B.3 judges and custom metrics, 2.7 cost tracking, 10B.4 built-in metrics, Part 8 cost, latency and variance, 10B.5 tracing and agent evaluation, 7.7 cost, 10B.6 datasets, 3.7 call-count arithmetic and 10B.7 red teaming, CI and platform. Per-span costs from 10B.5 are the raw material for your
eventstable. - Inspect AI (optional): 10B.12, 13.5 cost control in CI (optional) and 10B.15, 7.6 cost limits (optional). The cost of running evals themselves is the third part of this set: 11B.8, Part 6.
Common misconceptions#
- "A provider spend limit is my budget." It is a circuit breaker for the whole project or workspace. It cannot tell one user or feature from another, and it stops everything at once.
- "If the budget check runs after the call, we are covered." After the call the money is gone. A check after the call is a report.
- "Reserve the expected cost, not the worst case." Then one expensive call can overrun the budget. Reserve the worst case, and tighten it with a lower cap, not a lower guess.
- "Child budgets must add up to the parent." They need not. Oversubscription is normal; the parent is the hard wall.
- "A tag is enough for attribution." Tags are only as good as their coverage. Measure the untagged share and fail the build when it grows.
- "Splitting into many workspaces or projects is free." It costs cache hits (caches are isolated per workspace on Anthropic) and adds admin work.
- "Floats are fine for money." Sums drift and a reconciliation to the cent fails. Use integers.
- "Chargeback on day 1 of the next month." Provider data can be revised for about a week. Close on day 8.
Key takeaways#
- Budget is money, quota is tokens, rate limit is speed. Use the right one.
- Model your org as a hierarchy (organization, team, feature, user). A parent caps its children; children may be oversubscribed.
- Check all levels or none, before the call, with the worst case; settle the real cost after; keep the reservation when the real cost is unknown.
- Use integers for money, UTC for windows, and make in-flight reservations survive a window reset.
- Enforce in three layers: your wrapper or gateway below, the provider's limits above, alerts on both.
- Attribution = your tags + the provider's units (projects, workspaces, inference profiles). Require tags; measure the untagged share.
- Showback first, chargeback later. Publish the pricing method and the shared-cost method. Close on day 8.
- Test the ledger under concurrency and put a cost-data check in CI.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Budget | A money limit for an owner over a window |
| Quota | A limit on tokens or requests an owner may use over a window |
| Hierarchy (budget) | Nested owners (organization, team, feature, user) where every level on a call's path must have room |
| Oversubscription | Child limits adding up to more than the parent's, on purpose |
| Reserve-then-settle | Hold the worst-case cost before the call, then replace it with the real cost after |
| Worst-case estimate | Counted input times input price plus the output cap times output price, assuming nothing is cached |
| Over-reservation | Money locked by a pessimistic estimate until the call settles |
| All-or-nothing reserve | A reservation that holds on every level or on none |
| Micro-dollar | One millionth of a dollar; the integer unit that keeps sums exact |
| Showback | Reporting each team's spend without billing it |
| Chargeback | Billing each team's cost center for its spend |
| Shared cost allocation | Splitting costs no team owns (vector database, tracing) by usage, evenly or by agreed weights |
| Largest-remainder rounding | Handing out leftover units so an allocation sums exactly |
| Cost allocation tag | A key and value (team, feature) attached to spend so it can be grouped |
| Workspace (Anthropic) | An organizational unit with its own keys, members, limits and cache isolation |
| Project (OpenAI) | An organizational unit with its own keys and per-project rate and spend limits |
| Application inference profile (Bedrock) | A tagged profile through which you invoke a model so usage and cost are tracked per application |
| Unallocated bucket | The named owner of spend that arrived without a required tag |
Exercises#
- Add a monthly window. Extend
Nodeso one level can have both a daily and a monthly limit, andreserve()checks both. Write a test where the daily limit has room but the monthly does not. Hint: keep a list of(limit, window_s, used, window_start)per node and loop over it; blocked-at should say which window. - Measure over-reservation. Run 1,000 calls with random actual cost between 20% and 100% of the worst case and a user limit that fits 20 average calls. Count denials that happened while the user's real spend was below 70% of the limit. Then lower
max_output_tokensand repeat. Hint: recordusedat each denial fromledger.report(path). - Required tags. Make
reserve()raiseValueErrorifteamorfeatureis missing, unless the path starts with("acme", "unallocated"). Then makeattribution_check.pyreport the unallocated share separately. Hint: put the rule in one function so the wrapper and the gateway share it. - Weighted chargeback with a floor. Add a method that charges every team at least $0.01 of shared cost and splits the rest proportionally. Prove the total is exact with a property test over random inputs. Hint: allocate the floor first, then run
chargebackon the remainder. - A gateway check. Write down, for your own organization (or an invented one), the three enforcement layers and a number for each: the provider limit, the gateway limit, the app limit. Check that provider > gateway > app and explain what you do on each denial. Hint: use the "circuit breaker, not a budget" rule from 4.1.
- Reconcile for real (optional, needs a key). Run the 03.7
s13_reconcile.pyagainst your own account's costs for one day and compute the percentage difference. Hint: compare per project (OpenAI) or per workspace (Anthropic) rather than in total.
Check yourself#
- What is the difference between a budget, a quota and a rate limit?A budget limits money, a quota limits tokens or requests as a share of capacity, and a rate limit limits speed (per minute). They answer different questions and you usually need all three.
- Why must a reserve check all levels before holding any of them?Otherwise a denial at one level would leave holds on the levels that passed, and those holds would block other calls until a sweeper released them. All-or-nothing keeps denials free.
- A team has a $100 limit; its three features have $60, $60 and $60 limits. Is that allowed, and why might you do it?Yes. That is oversubscription: $180 of child limits under a $100 parent. It is useful because features rarely peak together, and the parent is the hard wall. Each child limit is a fairness guard.
- Why reserve the worst case rather than the expected cost?Because the real cost is unknown until the call finishes. Reserving the expected cost lets one expensive call overrun the budget, which turns the check into a report. Tighten the estimate by lowering the cap.
- What should
settle()do when the call failed and usage is unknown?Keep the whole reservation as spent. Over-charging by a few cents is better than letting failed calls spend for free. - Why store money as integers?Floating-point sums drift, so a reconciliation to the cent can fail. Integer micro-dollars keep every sum exact.
- A call is reserved at 23:59 and settled at 00:01. What must happen to its reservation and its charge?The reservation must survive the window reset (so the new day is not oversubscribed), and the charge must land in the new window when it settles.
- Name the three places a budget can be enforced and one weakness of each.Your app (weakness: every call site must use the wrapper), a shared gateway (weakness: it only knows what callers tell it, and it is one more thing that can fail), the provider (weakness: coarse, trips everything at once, and its error differs from a rate limit).
- Why is a provider spend limit a "circuit breaker, not a budget"?When it trips, every feature on that project, workspace or account stops together. It cannot tell a heavy user from a normal one, so keep it high and put your own, finer budgets below it.
- Why can splitting into many Anthropic workspaces raise your costs?Anthropic prompt caches are isolated per workspace on the Claude API, so teams in different workspaces cannot share a cache hit on the same long prefix, and each pays its own cache write.
Further resources#
Existing lessons:
- 03.7 Token Counting, Cost Tracking and Prompt Caching: counting, price tables, per-user budgets, provider limits, the admin cost APIs and reconciliation
- 03.8 Errors, Rate Limits, Timeouts and Retries: why a spend-cap 429 is not a rate limit
- 11B.1 Cost and Latency Optimization: tenant quotas, agent budgets, chargeback and showback
- 11B.2 Tokenomics: unit economics and the price map
- 13A.6 Metrics, Experiments and Unit Economics: cost per successful task, pricing models and cost caps as product features
- 08A.2 The Tool Loop and 08A.3: per-run budgets
Official documentation (read on 1 December 2026):
- OpenAI: production best practices (projects, rate and spend limits)
- OpenAI: rate limits
- Anthropic: workspaces
- Anthropic: rate limits and spend limits
- Anthropic: Usage and Cost Analytics API
- Amazon Bedrock: create an application inference profile
- LiteLLM proxy: users, teams and budgets
← 11B.5 — Model Selection and Routing | Module 11B overview | 11B.7 — Rate Limits Across Teams, Throughput Options, Kill Switches and Spend Alerts →