Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
A retry bug loops a ticket summariser 3,000 times overnight and the invoice is how you find out. Count tokens with tiktoken, price input and output separately, log one JSON line per call, and check a per-user daily budget before every call: in 40 simulated calls the nightly job is blocked at call 24, with 31 calls made and 9 blocked.
What you will learn
- Work out the cost of one call from input and output tokens at a price per million
- Count tokens with tiktoken and write one JSON log line per call
- Build a budget guard that checks a worst-case estimate before the call and records the real cost after
- Read the log as a per-user dashboard, and add the other guards: cap, cache, route, alert
Before you start
- LLM Tokens, Context Windows and Cost
- Basic Python
An LLM app is billed per token, and the bill arrives after the money is spent. In this article we keep an eye on that spend in three small steps: count the tokens of every call, log one line per call with its price, and check a budget before each call so a runaway user is stopped before the invoice does it for you.
The project uses saved request and reply texts, so no model is called. The token counts are real counts of real strings, and the cost is a real calculation at example prices. Always take the real numbers from your provider's pricing page.
The overnight bill
Imagine a support tool that summarises tickets with an LLM. One day a retry bug creates a loop, and it keeps starting again. Each time, it calls the model. By morning that's 3,000 calls. Then the invoice arrives, and that's how you find out.
Two things were missing. A log, so nobody could say which call, which user or which prompt cost what. And a limit, so nothing said stop.
Think of a prepaid travel card. Every purchase is written down, and when the balance would go below zero, the card declines. That's what we build.
Where the cost comes from
Every call has input tokens (your prompt) and output tokens (the reply), and each has its own price per million tokens. The price table in prices.py:
# EXAMPLE prices in US dollars per one million tokens.
# Example numbers only - check the provider's pricing page and edit this table.
PRICES = {
"example-small": {"input": 1.00, "output": 5.00},
"example-large": {"input": 3.00, "output": 15.00},
}
So the cost of one call is:
cost = (input_tokens × input_price + output_tokens × output_price) / 1,000,000
Worked out for one call on the large model: 556 input tokens come to about $0.0017, 181 output tokens to about $0.0027, so the total is $0.0044, just under half a cent. Notice that an output token costs five times as much as an input token here. Long replies are the expensive part. (Why tokens, and not words, is covered in tokens, context windows and cost.)
The meter: count, price, log
meter.py is the whole tracking half:
import json
from datetime import datetime, timezone
import tiktoken
from prices import PRICES
ENC = tiktoken.get_encoding("cl100k_base") # an approximation of any provider's counter
def count_tokens(text):
return len(ENC.encode(text))
def cost_usd(model, input_tokens, output_tokens):
p = PRICES[model]
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
def log_call(path, user, model, prompt, reply):
rec = {"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"user": user, "model": model,
"input_tokens": count_tokens(prompt), "output_tokens": count_tokens(reply)}
rec["cost_usd"] = round(cost_usd(model, rec["input_tokens"], rec["output_tokens"]), 6)
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(rec) + "\n")
return rec
A tiktoken encoder turns text into tokens, and count_tokens counts them; for our long prompt that's 556. tiktoken is an approximation of a provider's own counter, but it's close enough to budget with. When a real API answers, it returns the true counts in its usage field, and those are the ones to log. log_call builds a record with a timestamp, the user and the model, counts both sides, prices them, and appends one JSON line to calls.jsonl. One line per call. That's the meter.
The budget guard
Now the limit, in guard.py:
from datetime import date
class BudgetExceeded(Exception):
pass
class BudgetGuard:
def __init__(self, daily_limit_usd):
self.limit = daily_limit_usd
self.spent = {} # (user, day) -> dollars
def spent_today(self, user):
return self.spent.get((user, date.today()), 0.0)
def check(self, user, estimate):
"""Call before the model call: stop if this call would pass the limit."""
if self.spent_today(user) + estimate > self.limit:
raise BudgetExceeded(
f"{user} would pass the ${self.limit:.2f} daily limit "
f"(spent ${self.spent_today(user):.4f})")
def record(self, user, cost):
"""Call after the model call with the real cost."""
key = (user, date.today())
self.spent[key] = self.spent.get(key, 0.0) + cost
The guard keeps a ledger of dollars spent per user per day. check runs before the call: today's spend plus the estimate for this call, and if that's over the limit it raises BudgetExceeded. record runs after the call, with the actual cost. Check before, record after, exactly like the travel card.
Forty simulated calls
simulate.py runs 40 calls for three users. Ana and Ben ask now and then; a nightly job keeps looping, just like the bug.
from guard import BudgetExceeded, BudgetGuard
from meter import count_tokens, cost_usd, log_call, summarize
from texts import LONG_PROMPT, LONG_REPLY, SHORT_PROMPT, SHORT_REPLY
LOG = "calls.jsonl"
MODEL = "example-large"
MAX_OUTPUT = 300 # the most we allow the model to write per call
open(LOG, "w").close()
guard = BudgetGuard(daily_limit_usd=0.05)
# 40 simulated calls: two people ask a few times, a nightly job keeps looping.
plan = [("ana", SHORT_PROMPT, SHORT_REPLY), ("nightly-job", LONG_PROMPT, LONG_REPLY),
("ben", SHORT_PROMPT, SHORT_REPLY), ("nightly-job", LONG_PROMPT, LONG_REPLY)] * 10
blocked = 0
for n, (user, prompt, reply) in enumerate(plan, start=1):
estimate = cost_usd(MODEL, count_tokens(prompt), MAX_OUTPUT)
try:
guard.check(user, estimate)
except BudgetExceeded as err:
blocked += 1
print(f"call {n:02d} BLOCKED {err}")
continue
# (the model call would happen here; we use the saved reply)
rec = log_call(LOG, user, MODEL, prompt, reply)
guard.record(user, rec["cost_usd"])
print(f"call {n:02d} {user:<11} in={rec['input_tokens']:>4} out={rec['output_tokens']:>3} "
f"cost=${rec['cost_usd']:.4f} today=${guard.spent_today(user):.4f}")
print(f"\n{len(plan) - blocked} calls made, {blocked} blocked")
for user, t in summarize(LOG).items():
print(f"{user:<11} calls={t['calls']:>2} tokens={t['tokens']:>6} cost=${t['cost_usd']:.4f}")
The estimate is the important line. Before the call we don't know how long the reply will be, so we assume the worst we allow: the real input tokens plus MAX_OUTPUT, 300 output tokens. For the nightly job that's 556 × $3 + 300 × $15 per million, about $0.0062. The first calls:
call 01 ana in= 136 out= 61 cost=$0.0013 today=$0.0013
call 02 nightly-job in= 556 out=181 cost=$0.0044 today=$0.0044
call 03 ben in= 136 out= 61 cost=$0.0013 today=$0.0013
call 04 nightly-job in= 556 out=181 cost=$0.0044 today=$0.0088
Each call gets one line: who made it, tokens in and out, the cost, and that user's total today. Any bill can now be explained, one call at a time.
The guard trips
call 22 nightly-job in= 556 out=181 cost=$0.0044 today=$0.0482
call 23 ben in= 136 out= 61 cost=$0.0013 today=$0.0079
call 24 BLOCKED nightly-job would pass the $0.05 daily limit (spent $0.0482)
call 25 ana in= 136 out= 61 cost=$0.0013 today=$0.0093
call 26 BLOCKED nightly-job would pass the $0.05 daily limit (spent $0.0482)
...
call 40 BLOCKED nightly-job would pass the $0.05 daily limit (spent $0.0482)
31 calls made, 9 blocked
ana calls=10 tokens= 1970 cost=$0.0132
nightly-job calls=11 tokens= 8107 cost=$0.0482
ben calls=10 tokens= 1970 cost=$0.0132
At call 24 the nightly job has spent $0.0482. Adding the $0.0062 estimate would pass the five-cent limit, so the guard says blocked, even though $0.0482 is still under $0.05. That's the point of checking the worst case: the guard stops the call that could go over, not the one after it. Ana and Ben keep going, and every nightly call after that is blocked. Blocked means the model was never called, so no tokens and no cost. With a limit like this, the overnight loop would have stopped long before morning.
A dashboard from the log
The last three lines come from summarize, which reads calls.jsonl line by line and adds up calls, tokens and cost per user:
def summarize(path):
totals = {}
for line in open(path, encoding="utf-8"):
r = json.loads(line)
t = totals.setdefault(r["user"], {"calls": 0, "tokens": 0, "cost_usd": 0.0})
t["calls"] += 1
t["tokens"] += r["input_tokens"] + r["output_tokens"]
t["cost_usd"] = round(t["cost_usd"] + r["cost_usd"], 6)
return totals
One look and the runaway user stands out: ten calls each for Ana and Ben at about 1.3 cents, eleven for the nightly job at about 4.8 cents. Group the same log by model or by day and you can see who spends what, then put an alert on it. For a fuller picture of what else belongs in that log line (trace ids, latency, prompt version), see observability and tracing for LLM apps.
The same guard behind an API
In a web service the guard becomes an HTTP answer. In the full-stack capstone project of the course, the daily budget is set per API key, and a request that would pass it gets a 429 Too Many Requests with a Retry-After header. To watch it trip, the budget is set tiny, three hundredths of a cent: the first two requests go through, the third gets a 429, and the amount spent doesn't move. One question there ("how do I shuffle a list in place?") used 108 tokens in and 24 out; with the stand-in test model those counts are an estimate at about four characters per token, while a real provider returns the true counts.
Two rules carry over. Check before you spend, using what this key spent today plus the worst case for this call. And a refusal is free: a 429, or an off-topic question the service refuses, never reaches the model.
More guards to add
| Guard | What it does |
|---|---|
| Cap the output | Set max tokens, so one reply can't run on and on. It also makes the worst-case estimate smaller. |
| Cache repeats | Same prompt again? Reuse the saved answer and pay nothing. See caching for AI apps. |
| Route to a cheaper model | Easy questions to the small model, hard ones to the large one. See LLM model routing. |
| Alert early | Warn at 80% of the limit, before anything is blocked. |
Every one of these starts the same way: count, log, then check before the call.
Common mistakes
- Checking after the call. By then the money is spent. The check has to come first.
- Estimating with the expected reply length. Use the maximum you allow, or a long reply slips past the limit.
- One price for both sides. Output tokens usually cost more; price them separately.
- Hard-coding prices forever. They change. Keep them in one table and update it from the pricing page.
- Logging only totals. Without one line per call you can't say which user or prompt caused the spike.
Recap
| Step | In code |
|---|---|
| Cost of a call | tokens × price per million, input and output separately |
| Count | tiktoken before the call; the provider's usage field after it |
| Log | one JSON line per call: time, user, model, tokens, cost |
| Guard | check spent + worst-case estimate before, record the real cost after |
| Result here | 40 calls, 31 made, 9 blocked; the nightly job stopped at $0.0482 |
Try it yourself
Change MODEL to example-small and run the simulation again. Is the nightly job still blocked, and what does that tell you about where the limit should sit for each model? Then lower MAX_OUTPUT to 200 and watch the estimate shrink. Finally, add an alert to BudgetGuard that prints a warning the first time a user passes 80% of the limit.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.