Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 100/ 160
05. AI System Design

Cost Optimization

Caching, routing, shorter prompts, and smaller models as a cost control stack.

IntermediateCache · Route3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

You make the AI cheaper step by step, starting with changes that don't hurt answers and testing each bigger change to make sure the answers stay good.

Think of it like…

Trimming a household budget: first cancel unused subscriptions and compare plans (free savings), then adjust habits that affect comfort (some trade-offs) and only then consider big changes like moving house (high effort, high risk), checking each month that the family is still happy.

Where you’ve seen it

Baseline: a support assistant at 100,000 requests a day, all-in cost $0.01425 a request (LLM $0.01195 plus $0.002 reranking and $0.0003 embedding and search), so $1,425 a day. Step 1, prompt caching of the 2,400-token stable prefix: $0.00885 ($885 a day). Step 2, a concise-answer instruction cuts average output from 420 to 300 tokens: $0.00765 ($765). Step 3, a semantic cache on FAQ-type intents hits 20% of requests at a lookup cost of $0.0001 each: 0.8 × $0.00765 + $0.0001 = $0.00622 ($622). Step 4, routing half of the remaining requests to a small model (about $0.0004 of LLM cost versus $0.00535, plus $0.0002 router cost): average per miss $0.005375, overall 0.8 × $0.005375 + $0.0001 = $0.0044 ($440 a day). Total: $1,425 to $440 a day, a 69% saving ($42,750 to $13,200 a month). Guardrails: golden-set quality drops 1.2 points from routing, false cache hits are 1% of hits and are audited, and cost per resolved conversation falls from $0.0238 to $0.0073.

Words you’ll hear

Lossless optimisation
A saving that doesn't change outputs, such as caching a stable prefix.
Cost per successful outcome
Spend divided by resolved or accepted results, not by raw requests.
Cost attribution
Tagging spend by feature, tenant, model and prompt version.
Optimisation ladder
Applying levers in order of safety and return, validating each.

Visual diagram

Loading interactive diagram

Theory & deep dive

The levers, in order

Start with measurement: log tokens, cost and outcome per request with tags for feature, tenant, model and prompt version, and find where the money goes (often one feature or one verbose prompt). Then apply lossless levers: prompt caching for long stable prefixes (instructions, tools, few-shot, policies), output control (concise-answer instructions, structured fields, max_tokens), removing waste (unused tool schemas, duplicated context, verbose system prompts, retrieval of chunks that never influence answers) and eliminating duplicate or retried calls (idempotency, caching deterministic results, fixing retry storms: 6% retried calls means 6% extra spend).

Next, quality-sensitive levers, each gated by evals: semantic caching for repetitive intents, routing or cascades to smaller models for easy traffic, context compression and reranking to send fewer chunks, model downgrades for specific steps (use a small model for classification and extraction, a large one for final answers), fine-tuning or distillation to move behaviour into a smaller model and asynchronous batch tiers for non-urgent work (roughly half price on many providers). Last, infrastructure: quantisation, self-hosting open models when break-even is clear, committed-use or reserved capacity. Don't forget side costs: judge-model eval runs, tracing storage and embedding refreshes can add 5% to 15%.

Applying the ladder

$1,425 → prefix caching $885 → shorter answers $765 → semantic cache $622 → routing $440 per day. The first two (about $660 a day) are lossless; the last two (about $325 a day) need guardrails and monitoring.

Key takeaway: Measure, take lossless wins, then add quality-sensitive levers behind evals, and save infrastructure moves for last.

Validating savings and keeping them

Every lever must pass two tests: quality (run the golden set per slice and an online A/B test or canary with guardrail metrics: resolution rate, escalation, thumbs-down) and savings (measure actual cost per request and per outcome after release; predicted savings often shrink because of cache misses, routing mix or retry overhead). Prefer cost per successful outcome to cost per request: routing 50% of traffic to a small model that lowers resolution by two points can still be a clear win, while a cheaper model that cuts resolution from 60% to 36% saves nothing per resolution.

Keep the savings by building controls into the platform: budgets and alerts per feature and tenant, token caps and agent step limits, a price table updated when providers change rates (re-run break-even analyses), dashboards that show cost by prompt version (a prompt edit that adds 800 tokens is a cost regression), and a review in the pull-request process for changes that touch prompts, models or retrieval. Avoid false economies: starving retrieval of context so answers get worse and users ask again, over-aggressive caching that serves stale or wrong answers, premature self-hosting that adds fixed cost and operations, and optimising a feature that is 3% of spend. Revisit regularly: model prices fall, new cheaper models appear and traffic mix shifts, so the ladder needs re-running.

Cost per resolution

$440 a day for 100,000 requests at an assumed 60% resolution rate is $0.0044 per request ÷ 0.60 = $0.0073 per resolved conversation, versus $0.01425 ÷ 0.60 = $0.0238 at baseline: a 69% fall, provided resolution really stayed near 60% in the online test.

Key takeaway: Validate quality and measured savings per outcome, then lock gains in with budgets, dashboards and review.

How it works, step by step

Step 1 of 4
Engineering

1. Instrument and attribute

Log tokens, cost and outcomes with feature, tenant, model and prompt-version tags; find the biggest spenders.

$1,425/day baseline
Key numbers at this step
Include
retrieval and judge costs

When to use it & trade-offs

What it is

Cost optimisation for LLM products is the practice of lowering cost per successful outcome with a stack of controls applied in order of safety and return: first the lossless ones (prompt caching, shorter outputs, trimming wasted tokens, de-duplicating calls), then the quality-sensitive ones (semantic caching, model routing, smaller or distilled models, context compression), and finally infrastructure moves (batch tiers, self-hosting, quantisation). Each lever is validated against the eval set and an online guardrail, savings are measured after changes ship, and spend is attributed by feature so effort goes where the money is.

Why it matters: LLM costs scale with usage, and success makes them painful: a feature that costs $0.014 per request becomes a $1,425 daily bill at 100,000 requests. Optimisation is an engineering discipline with a trade-off at every step, because the easy way to cut cost (a weaker model, less context) quietly cuts quality. Sequencing by risk, measuring per outcome and keeping evals in the loop lets you capture large savings without regressing the product.

When to reach for it

  • Scaling a successful AI feature
  • Planning budgets and unit economics
  • Prioritising engineering work by dollars saved

When to avoid or be careful

  • Cutting cost by downgrading the model without evals
  • Measuring only cost per request
  • Optimising small cost lines while the main one is untouched

Levers by risk and return

Prompt caching and output limits
Best for: First, lossless savings

Strengths: Large saving, no quality change.

Watch out: Needs stable prefixes and prompt discipline.

Semantic cache and routing
Best for: Repetitive and mixed-difficulty traffic

Strengths: Big savings at scale.

Watch out: Quality risk; needs evals and audits.

Self-hosting and quantisation
Best for: Stable, high-volume workloads

Strengths: Lowest unit cost at scale.

Watch out: Fixed cost and operations burden.

Interview signals & numbers to know

When this topic comes up

  • “Our LLM bill doubled this quarter”
  • “What does one resolved conversation cost?”
  • Prompt caching and routing
  • Cost attribution by feature
  • Cost per outcome

Benchmarks & rules of thumb

$1,425 → $440 -
daily cost at 100,000 requests after the four levers
−69% -
total saving in the example
$0.0238 → $0.0073 -
cost per resolved conversation

Common mistakes & follow-ups

Common interview mistakes

  • Skipping the lossless levers and jumping straight to a smaller model.
  • Forgetting that retries and judge calls are part of the bill.
  • Not re-running the analysis when provider prices change.

Likely interviewer follow-ups

  • How would you cut LLM costs by 50% without hurting quality?
  • Which optimisations are risk-free?
  • How do you verify that a savings idea really worked?
Interview tip: Present the ladder with dollars at each step, marking which are lossless. It shows prioritisation by risk and return.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Cost Optimization with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Context Window Management
Next topic
Prompt Injection