Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. AI System Design

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.

Chaand Sheikh

·27 November 2026AI System Design

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.

Check before the call, record after it request checkspent + estimatevs the limit model call log_callone JSON line recordreal cost blocked: $0, no tokens ok over
The decline happens before the purchase. A blocked call never reaches the model, so it costs nothing.

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

GuardWhat it does
Cap the outputSet max tokens, so one reply can't run on and on. It also makes the worst-case estimate smaller.
Cache repeatsSame prompt again? Reuse the saved answer and pay nothing. See caching for AI apps.
Route to a cheaper modelEasy questions to the small model, hard ones to the large one. See LLM model routing.
Alert earlyWarn 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

StepIn code
Cost of a calltokens × price per million, input and output separately
Counttiktoken before the call; the provider's usage field after it
Logone JSON line per call: time, user, model, tokens, cost
Guardcheck spent + worst-case estimate before, record the real cost after
Result here40 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 81 of 89

Previous
Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
Next post
Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback

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.

On this page

  • The overnight bill
  • Where the cost comes from
  • The meter: count, price, log
  • The budget guard
  • Forty simulated calls
  • The guard trips
  • A dashboard from the log
  • The same guard behind an API
  • More guards to add
  • Common mistakes
  • Recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.