SkillNavora
AI Master Course › Week 4 › New lesson 3 of 7
Week 4 · extends Subject 15

Latency and cost

Users leave slow products and finance teams cancel expensive ones. Measure where the time and money go, then use the cheapest lever that keeps quality.

In plain words. A restaurant: latency is how long the customer waits, cost is the price of ingredients and staff. You do not fix slow service by buying a bigger oven if the queue is at the till. Measure each step first.

1. Why it matters

  • Model calls are usually the slowest and most expensive step, but not always; retrieval, network and your own code add up.
  • Costs scale with tokens times requests. A prompt that is 2,000 tokens too long costs real money at 100,000 requests a day.
  • The right business number is cost per successful task, not cost per request.

2. Key ideas

LatencyTime from request to answer. Report p50 (typical) and p95 (slow tail), not the average.
Time to first tokenHow long before the first words appear. Streaming makes long answers feel fast.
Input and output tokensYou pay for both; output tokens are usually several times dearer per token and are generated one by one, so they drive latency.
Cost per requestinput tokens x input price + output tokens x output price.
Cost per successful taskTotal cost divided by tasks done correctly. A cheaper model that fails more often can cost more per success.
Prompt cachingThe provider reuses a long, repeated prompt prefix (instructions, documents) at a much lower price and with less delay.
Response cachingYou store answers to repeated questions and skip the model call entirely.
Model routingSend easy requests to a small, fast model and hard ones to a larger model.
BatchingSend non-urgent work as a batch job, usually at a large discount, with results later.

3. How it works, step by step

  1. Instrument: time every step (retrieve, prompt build, model, post-processing) and log tokens per request.
  2. Find the biggest share of time and of cost before changing anything.
  3. Free wins first: shorter prompts, fewer or smaller chunks, a lower max_tokens, prompt caching for the fixed prefix, response caching for repeats.
  4. Then trade-offs: a smaller model or lower effort for easy requests, batching for offline work.
  5. Re-run the eval after every change; keep it only if quality stays above the bar.
  6. Report cost per successful task and p95 latency to the business.

4. Code you can run

Run it from the starter project folder: python examples/l3_latency_cost.py. It runs offline for free; add an API key in .env to use Claude.

examples/l3_latency_cost.py (in the starter project)
"""Lesson 3: where the time goes, what a request costs, and what caching saves.
Run: python examples/l3_latency_cost.py"""
import functools, os, sys, time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from starter.costs import Timer, cost_per_successful_task, percentile, request_cost
from starter.rag import answer, index_pdf

PDF = os.path.join(os.path.dirname(__file__), "..", "data", "sample_policy.pdf")

timer = Timer()
with timer.part("index"):
    store = index_pdf(PDF)
with timer.part("answer"):
    r = answer(store, "When must expense claims be submitted?", log=False)
print("1) Timings for one cold request (offline mode)")
print(timer.report())
print("   inside answer():", r["timings_ms"])

print("\n2) Cost of one request at three illustrative price points (per 1M tokens)")
tokens_in, tokens_out = 1800, 250
for name, pin, pout in [("large model", 4.00, 20.00), ("mid model", 2.00, 10.00), ("small model", 0.10, 0.50)]:
    print(f"   {name:<12} ${request_cost(tokens_in, tokens_out, pin, pout):.5f} per request  -> ${request_cost(tokens_in, tokens_out, pin, pout) * 10000:.2f} per 10,000 requests")

print("\n3) Cost per successful task (what managers care about)")
for name, cost_each, success_rate in [("cheap but weak", 0.0005, 0.60), ("dearer but accurate", 0.0020, 0.95)]:
    n = 1000
    print(f"   {name:<20} ${cost_per_successful_task(cost_each * n, int(n * success_rate)):.5f} per correct answer ({success_rate:.0%} pass)")

print("\n4) Caching repeated questions")
@functools.lru_cache(maxsize=256)
def cached_answer(q: str) -> str:
    return answer(store, q, log=False)["answer"]

times = []
for i in range(5):
    t = time.perf_counter(); cached_answer("How many days a week can I work remotely?"); times.append((time.perf_counter() - t) * 1000)
print(f"   first call {times[0]:.3f} ms, repeat calls about {sum(times[1:]) / 4:.4f} ms (cache hits: {cached_answer.cache_info().hits})")
print(f"   p50 {percentile(times, 50):.4f} ms, p95 {percentile(times, 95):.3f} ms")
Real output (offline mode, captured when this page was built)
1) Timings for one cold request (offline mode)
index           18.64 ms   91.6%
answer           1.70 ms    8.4%
   inside answer(): {'retrieve': 0.17, 'generate': 0.53}

2) Cost of one request at three illustrative price points (per 1M tokens)
   large model  $0.01220 per request  -> $122.00 per 10,000 requests
   mid model    $0.00610 per request  -> $61.00 per 10,000 requests
   small model  $0.00031 per request  -> $3.05 per 10,000 requests

3) Cost per successful task (what managers care about)
   cheap but weak       $0.00083 per correct answer (60% pass)
   dearer but accurate  $0.00211 per correct answer (95% pass)

4) Caching repeated questions
   first call 0.737 ms, repeat calls about 0.0018 ms (cache hits: 4)
   p50 0.0005 ms, p95 0.737 ms

5. What the code does

  • Timer.part times each named step, so you see that indexing is the slow part here and should happen once, not per request.
  • request_cost turns token counts into money; the three price points are illustrative.
  • cost_per_successful_task shows the dearer, more accurate option costing more per correct answer here, but the gap shrinks a lot once failures are counted. Run the numbers for your own case.
  • lru_cache answers a repeated question from memory; repeats cost no tokens at all.

6. Common mistakes and fixes

ProblemFix
Reporting the average latencyOne slow call in twenty hides in the average. Report p95.
Re-indexing documents on every requestIndex once and store the vectors; only embed the question per request.
max_tokens far above what answers needLong outputs are slow and costly. Set a sensible ceiling and ask for concise answers.
Switching to a smaller model without an evalQuality drops silently. Run the golden set first.
Caching personalised answers for everyoneCache only answers that do not depend on the user, or include the user in the cache key.

7. Product manager view

  • Put latency and cost targets in the PRD: for example p95 under 4 seconds, cost per resolved ticket under 2 rupees.
  • Build the business case on cost per successful task and on adoption, not on list prices.
  • Ask for a monthly cost forecast: requests per day x tokens per request x price, with a 30 percent buffer.

8. Assignment

Instrument your chatbot: log time per step and tokens per request for 50 questions. Report p50 and p95 latency, cost per request and cost per correct answer. Apply one optimisation, re-run the eval and show the before and after.

Check your work against the model answer for Subject 15.

9. Interview questions

How would you reduce the latency of an LLM feature?

Measure each step first. Then stream the output, cut prompt and output length, cache repeated prefixes and answers, run retrieval in parallel, and route easy requests to a faster model, checking quality with the eval each time.

What is the difference between p50 and p95 latency?

p50 is the median request; p95 is the time 95 percent of requests beat. p95 shows the slow tail that users complain about.

How do you estimate the monthly cost of an AI feature?

Requests per month x (input tokens x input price + output tokens x output price), plus embeddings, storage and evaluation runs, with a buffer for growth and retries.

Why can a cheaper model cost more?

If it fails more often, retries, escalations and human fixes raise the cost per successful task.

Refer & earn