LESSON 66 ยท PRODUCTION GENAI

Cost Optimization

Learn how to control Generative AI costs without sacrificing the quality, reliability, or user experience of your application.

25 min readโ€ขIntermediateโ€ขGenerative AIโ€ขProduction

How GenAI Cost Optimization Works

MeasureTrack requests, tokens, latency, and spend.
ReduceRemove unnecessary model work and context.
RouteUse the right model for each task.
CacheReuse safe, repeated results.
BatchGroup work when real-time output is not required.
MonitorSet budgets, alerts, and quality checks.
iImportant: The cheapest model is not automatically the cheapest architecture. A low-cost model that needs three retries, huge prompts, or expensive retrieval can cost more than a better model used once.
1

What Is GenAI Cost Optimization?

Cost optimization means designing an AI system so it delivers the required quality and reliability with the lowest practical total cost.

Key idea:Optimize the whole request path, not just the model price. A useful cost equation is total cost = model usage + retrieval/data + infrastructure + retries + operational overhead.
2

Where Does the Money Go?

A production GenAI request can create several different costs.

LLM tokensINPUT + OUTPUT

Long prompts and long answers increase usage. Repeated calls multiply the cost.

Embedding callsINDEX + QUERY

Embedding documents and user queries creates model usage and processing work.

Retrieval infrastructureDATA LAYER

Vector databases, object storage, databases, and network traffic can add recurring costs.

Application infrastructurePLATFORM

Servers, queues, logs, observability, and background workers also contribute to total cost.

3

Measure Before You Optimize

You cannot optimize what you cannot see. Start by measuring cost at the request and feature level.

  • Requests: How many AI calls happen per user action?
  • Tokens: How much input and output text is processed?
  • Model: Which model handles each request?
  • Latency: How long does the request take?
  • Quality: Does a cheaper path still answer correctly?
  • Spend: Which users, features, or workflows consume the most budget?
Production habit:Attach a request ID and feature name to AI telemetry so you can answer questions such as โ€œHow much does document search cost per successful answer?โ€
4

Model Selection and Routing

Different tasks need different levels of model capability. Route simple work to efficient models and reserve expensive models for tasks that actually need them.

Simple task

Classification, extraction, short rewriting, or routing can often use a smaller model.

Balanced task

Customer support or normal Q&A may use a mid-range model with good quality and cost.

Complex task

Deep reasoning, difficult coding, or high-value decisions may justify a stronger model.

5

Python: Simple Cost-Aware Routing

Keep infrastructure decisions in application code so routing is deterministic and easy to test.

</> Python
def choose_model(task: str, quality_needed: str) -> str:
    if task in {"classify", "extract"}:
        return "small-model"

    if quality_needed == "high":
        return "premium-model"

    return "balanced-model"


print(choose_model("classify", "normal"))
print(choose_model("research", "high"))

The routing rule can later incorporate measured quality, budget, availability, and latency.

6

Reduce Input Tokens

Input tokens are often the easiest place to remove waste because applications frequently send more context than the model needs.

Trim instructions

Remove repeated rules, duplicate examples, and unnecessary prose.

Trim history

Keep only conversation history that is relevant to the current task.

Trim retrieved context

Retrieve fewer, better chunks instead of sending an entire document.

Use structured context

Pass compact fields when the model does not need verbose descriptions.

7

Control Output Length

Output tokens can become a hidden cost multiplier when an application asks for unnecessarily long answers.

Example:If a support UI only needs a short answer, asking the model for a detailed 1,000-word explanation wastes output tokens. Set an appropriate output limit and request the required format.
User requestโ€œGive me the status in 2 bullets.โ€
ModelProduces only the required amount.
ApplicationDisplays the concise response.
8

Optimize RAG Context

RAG can lower the need for large prompts, but poorly tuned retrieval can still create unnecessary model usage.

Too much context

Sending 20 weak chunks increases tokens, latency, and the chance of irrelevant information confusing the model.

Focused context

Use metadata filters, good chunking, similarity search, and reranking to provide a smaller evidence set.

Rule of thumb:Do not optimize retrieval only for Recall@K. Also measure how much retrieved context is actually useful to the final answer.
9

Caching

Caching avoids repeating expensive work when the same result can safely be reused.

Exact response cache

Reuse the answer for identical, deterministic requests when freshness requirements allow it.

Embedding cache

Store embeddings for documents or repeated queries instead of recalculating them.

Retrieval cache

Reuse expensive retrieval results for short periods when the underlying data is stable.

Semantic cache

Reuse answers for sufficiently similar questions only when correctness and freshness are controlled.

10

Python: A Small Cache

This simple example shows the idea behind caching an expensive operation.

</> Python
cache = {}


def get_answer(question: str, generate_answer):
    key = question.strip().lower()

    if key in cache:
        return cache[key]

    answer = generate_answer(question)
    cache[key] = answer
    return answer


print(get_answer("What is RAG?", lambda q: "RAG retrieves evidence before generation."))

Real systems need expiration, invalidation, size limits, and a cache shared across application instances.

11

Batching and Asynchronous Work

Not every AI task needs an immediate response. Batch offline work when possible and move long-running jobs to background workers.

Real-time

Chat responses, interactive agents, and checkout assistance need low waiting time.

Async

Document indexing, report generation, bulk classification, and nightly summaries can run in the background.

Batch

Large collections of independent items can be processed together when the provider supports it.

12

Avoid Unnecessary Model Calls

One of the biggest savings is simply not making a model call when deterministic code can answer the request.

Good architecture:Use normal application code for authentication, validation, arithmetic, permissions, feature flags, and fixed business rules. Use an LLM when language understanding or generation adds real value.
Can code answer?Yes โ†’ use deterministic logic.
Needs language?Yes โ†’ call the model.
Needs evidence?Add focused retrieval.
13

Retries Can Multiply Cost

Retries improve reliability, but uncontrolled retries can turn one failed request into several paid model calls.

Retry only retryable errors

Do not retry invalid input or deterministic application failures.

Use exponential backoff

Spread retries instead of immediately repeating requests.

Set a retry limit

Bound the maximum number of attempts per request.

Track retry cost

Measure how much spend comes from failed and repeated calls.

14

Rate Limits, Budgets, and Guardrails

Cost control should be enforced at the application level, not left to individual developers.

Per-user limits

Limit requests or expensive actions per user or account.

Feature budgets

Give high-cost features explicit daily or monthly budgets.

Token limits

Bound context and output so a single request cannot become unexpectedly large.

Spend alerts

Notify the team when usage exceeds expected thresholds.

15

Cost-Aware Agent Design

Agents can make multiple model and tool calls, so their cost needs explicit boundaries.

PlanSet a useful goal and stop condition.
Choose toolCall only tools needed for the task.
ObserveProcess the result.
Continue?Stop as soon as the goal is satisfied.
Important:Set maximum steps, maximum tokens, timeouts, and tool permissions. An agent that can loop indefinitely is also a cost risk.
16

Python: Estimate Request Cost

A simple estimator makes cost assumptions visible in tests and dashboards.

</> Python
def estimate_cost(input_tokens: int, output_tokens: int,
                  input_price: float, output_price: float) -> float:
    input_cost = input_tokens / 1_000_000 * input_price
    output_cost = output_tokens / 1_000_000 * output_price
    return input_cost + output_cost


cost = estimate_cost(8_000, 1_500, 2.00, 8.00)
print(f"Estimated cost: ${cost:.4f}")

Provider prices change, so keep pricing configuration outside business logic and refresh it from your approved source.

17

Quality vs Cost: Optimize the Right Metric

A lower bill is not an optimization if users receive worse answers and start retrying or abandoning the product.

Bad optimization

Choose the cheapest model for every request and ignore answer quality, retries, and conversion.

Better optimization

Define an acceptable quality threshold, then minimize cost while staying above that threshold.

Think in cost per successful outcome:For many products, the important metric is not cost per model call but cost per correct answer, completed workflow, or successful customer action.
18

Cost Monitoring Dashboard

Useful dashboards connect AI usage to product behavior.

  • Total AI spend per day and month
  • Spend by model and provider
  • Input and output tokens
  • Average cost per request
  • Cost by feature, tenant, or user segment
  • Cache hit rate
  • Retry rate and failed requests
  • Quality score and successful outcome rate
19

Common Cost Optimization Mistakes

Using one model for everything

Simple tasks may be overpaying for capabilities they do not need.

Sending the full conversation

Long histories can silently increase token usage on every turn.

Retrieving too many chunks

More context is not automatically better context.

Ignoring retries

Timeouts and failed requests can multiply spend.

No per-user limits

A single user or automation can consume a disproportionate budget.

Optimizing price only

Lower model cost can be offset by lower quality and more follow-up work.

20

Mini Project: Build a Cost-Aware RAG Assistant

Design a small knowledge assistant that answers questions while keeping cost under control.

1. MeasureTrack tokens, model calls, retrieval count, latency, and request cost.
2. RetrieveReturn a small candidate set and rerank when the quality gain justifies the cost.
3. RouteUse a smaller model for simple questions and a stronger model for complex cases.
4. CacheCache embeddings and safe repeated requests.
5. LimitSet output, retry, and agent-step limits.
6. EvaluateCompare cost per successful answer, not only cost per request.
21

When Should You Optimize?

Start cost-aware design early, but avoid premature complexity.

Prototype

Measure basic usage and avoid obvious waste. Keep the architecture simple.

Growing product

Add routing, caching, limits, dashboards, and retrieval optimization as usage increases.

Large scale

Use detailed attribution, budgets, provider strategies, batch processing, and continuous evaluation.

22

Quick Quiz

1. What is usually the best first step in cost optimization?

Measure where requests, tokens, retries, and infrastructure spend are going.

2. Should every request use the most powerful model?

No. Route tasks according to their quality requirements and measured outcomes.

3. Why can RAG become expensive?

Retrieval can return too much context, increasing tokens, latency, and model usage.

4. How can agents create unexpected cost?

They can make repeated model and tool calls, especially without step and token limits.

5. What metric is better than model-call cost alone?

Cost per successful outcome, such as a correct answer or completed workflow.

23

30-Second Recap

01Measure AI usage before changing the architecture.
02Use the smallest model that reliably meets the quality target.
03Reduce unnecessary tokens, context, model calls, and retries.
04Use caching and asynchronous processing where appropriate.
05Control agent steps, output size, rate limits, and budgets.
06Optimize cost together with quality, latency, and successful outcomes.

Key Takeaways

  • GenAI cost is an architecture problem, not only a model-pricing problem.
  • Token reduction, model routing, caching, batching, and retrieval tuning can produce major savings.
  • Production systems need budgets, rate limits, retry controls, and cost observability.
  • Always validate that cost reductions preserve the quality users need.