Cost Optimization and Token Budgeting

Estimate, measure and reduce the cost of every query.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 20 · Lesson 6 of 9 · Advanced

Cost Optimization and Token Budgeting

Estimate, measure and reduce the cost of every query.

A RAG system's running cost is mostly LLM tokens, plus embedding, vector database and hosting costs. At a few hundred questions a day this hardly matters; at a million, a 30% saving is real money. This lesson shows how to measure cost per question and which levers reduce it, starting with those that cost no quality at all.

Where the money goes

LLM cost per question = input tokens × input price + output tokens × output price, with cached input tokens billed at a much lower rate. Input tokens include the system prompt, retrieved chunks, conversation history and the question. Every extra LLM call (query rewriting, grading, judging) adds its own input and output.

Measure cost per question

The API reports exact token usage on every response. Record it, convert it to money and attach it to your request logs. The prices below are examples from the time of writing; keep them in configuration and check the current price list.

cost_tracker.py
# USD per million tokens (example values; check current pricing)
PRICES = {
    "claude-opus-5-5":   {"input": 4.00, "output": 20.00, "cache_read": 0.20},
    "claude-sonnet-5-5": {"input": 2.00, "output": 10.00, "cache_read": 0.10},
    "claude-haiku-5-5":  {"input": 0.10, "output": 0.50},
}
CACHE_WRITE_MULTIPLIER = 1.25        # 5-minute cache writes cost a little more than normal input

def request_cost(model: str, usage) -> float:
    p = PRICES[model]
    cache_read_price = p.get("cache_read", p["input"] * 0.1)
    cost = (usage.input_tokens * p["input"]
            + (usage.cache_creation_input_tokens or 0) * p["input"] * CACHE_WRITE_MULTIPLIER
            + (usage.cache_read_input_tokens or 0) * cache_read_price
            + usage.output_tokens * p["output"])
    return cost / 1_000_000

class CostTracker:
    def __init__(self):
        self.total, self.calls = 0.0, []

    def record(self, step: str, model: str, response) -> None:
        cost = request_cost(model, response.usage)
        self.total += cost
        self.calls.append({"step": step, "model": model, "usd": round(cost, 6),
                           "in": response.usage.input_tokens, "out": response.usage.output_tokens})

Report cost per question by pipeline step. It is common to discover that an "optional" step, such as a grader or a query rewriter, costs as much as the answer itself.

Free wins (no quality cost)

  1. Prompt caching for the system prompt, examples, tools and conversation history (Prompt Caching). Verify hits with the usage fields.
  2. Deduplicate and merge chunks so you do not pay for the same text twice (Context Budgeting).
  3. Trim the system prompt: remove outdated rules and redundant examples.
  4. Answer caches for frequent standalone questions (Caching).
  5. Batch processing for offline work. Indexing-time LLM calls (contextual retrieval, metadata extraction, summaries) and evaluation runs can use the Message Batches API at half price.

Trade-offs to measure

These levers can lower quality, so test each one against your golden set before rolling it out:

  • Fewer or shorter chunks in the prompt: retrieve wide, rerank, send only the best.
  • Lower effort: low effort uses fewer thinking and output tokens and is often enough for RAG answers.
  • Shorter answers: ask for concise answers; output tokens are the most expensive kind.
  • Fewer LLM steps: route simple questions past rewriting and self-correction.
  • A different model for some steps: lighter steps such as routing or classification can sometimes run on a smaller, cheaper model. Measure it first: a more capable model at lower effort may match the smaller model's cost while staying more accurate, and a single model keeps prompt caching simpler.

Judge cost per successful answer

A cheaper configuration that answers 10% fewer questions correctly is not cheaper if users then ask again, escalate to human support or stop trusting the system. Track cost per question and quality together, and compare cost per correctly answered question.

Other costs

  • Embeddings: usually small; cache by content hash so re-indexing only pays for changes.
  • Vector database: memory dominates; consider quantization and smaller dimensions at scale (Dimensions and Quantization).
  • Rerankers and local models: GPU hosting is a fixed cost; hosted rerank APIs are per request.

Key takeaways

  • Log token usage and cost per question, broken down by pipeline step.
  • Take the free wins first: prompt caching, deduplication, trimmed prompts, answer caches and batch processing.
  • Test quality-affecting levers (fewer chunks, lower effort, different models) against your golden set.
  • Optimise cost per correctly answered question, not cost per request.