AI ENGINEERING · LLMS IN PRODUCTION · OPERATIONS · 32 OF 35

Cutting LLM Cost and Latency: Caching, Streaming, Routing

Where LLM cost comes from (input tokens, output tokens, number of calls) and where latency comes from (time to first token, output length, sequential calls). A worked monthly bill cut by about 80% with shorter prompts, prompt caching, shorter answers, routing, response caching and a batch API; streaming, parallel calls and perceived speed; budgets, rate limits, timeouts with fallbacks; and why to track p50 and p95.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Calls × tokens × price
  • trim
  • cache
  • route
  • batch
  • stream
  • parallel
  • budgets
  • timeouts
  • p95

Notes

The idea

Two formulas carry this episode. Cost per request is the number of calls, times input tokens at the input price plus output tokens at the output price. The model keeps no memory, so the whole context is paid for again on every call. Latency is time to first token plus output length over generation speed, added up across calls that wait on each other. Every lever shrinks one of those terms.

Two formulas
cost per request =
  calls × (in tokens × in price
         + out tokens × out price)

latency =
  for each call that must wait:
    time to first token
    + out tokens / tokens per second
  + tool and network time

whole context resent every call

A worked bill

Let us price a feature with illustrative prices. A support bot gets a million requests a month, each making two calls: one to pick a tool, one to answer. Each call sends six thousand input tokens and gets four hundred back. At three dollars per million input tokens and fifteen per million output, input costs thirty six thousand and output twelve thousand. A nightly summary job adds six thousand. Fifty four thousand a month, two thirds of it input.

Baseline bill, one month
support bot: 1M requests / month
2 calls each: tool step + answer
per call: 6,000 in, 400 out
  (3,000 prompt + tools, 2,500 docs,
   500 chat and question)
illustrative price per 1M tokens:
  in 3 USD, out 15 USD
in:  12,000M tok × 3  = 36,000
out:    800M tok × 15 = 12,000
nightly ticket summaries =  6,000
total                    = 54,000

Lever 1: shorter prompts

Lever one, shorter prompts. Find out which tokens actually earn their place. Here an eval shows three document chunks answer as well as five, so each call drops from six thousand input tokens to five thousand. Input falls from thirty six thousand dollars to thirty thousand. Also summarise old chat turns, drop tools the feature never uses, and never paste a whole API response when three fields would do.

Lever 1: shorter prompts
eval: 3 doc chunks answer as
  well as 5
  docs: 2,500 → 1,500 tok per call
per call: 6,000 → 5,000 in
input: 10,000M × 3 = 30,000
saves 6,000 USD / month

also: summarise old chat turns,
drop tools the feature never uses,
send 3 fields, not a whole
API response

Lever 2: prompt caching

Lever two, prompt caching. The system prompt and tool list, three thousand tokens, are identical on every call. Put them first, mark them cacheable, and the provider reuses work it already did. Say cached reads cost a tenth of the normal price. Each call now bills like two thousand three hundred tokens, and input drops to thirteen thousand eight hundred. The biggest lever here, and it shortens time to first token too.

Lever 2: prompt caching
prompt + tools: 3,000 tokens,
  identical on every call
cached read: say ~10% of the
  normal input price

billed per call:
  2,000 + 3,000 × 0.1 = 2,300
input: 4,600M × 3 = 13,800
saves 16,200 USD / month

stable parts first, changing last

Lever 3: shorter answers

Lever three, fewer output tokens, the expensive and slow ones. Ask for two to four sentences, set a max tokens limit on every call, have the tool step return short JSON instead of prose, and stop the model restating the question. Going from four hundred to two hundred and fifty tokens per call cuts output from twelve thousand dollars to seven thousand five hundred, and answers finish sooner.

Lever 3: fewer output tokens
answers average 400 tokens;
users read the first 150

• ask for 2-4 sentences
• set max_tokens on every call
• tool step returns short JSON
• no restating the question

per call: 400 → 250 out
output: 500M × 15 = 7,500
saves 4,500, answers finish sooner

Lever 4: routing

Lever four, routing to a smaller model. Reset my password does not need a frontier model. A router sends easy requests to a small model at about a tenth of the price, and hard ones, like a disputed refund, to the big one. If sixty percent are easy, the chat bill drops from twenty one thousand three hundred to about nine thousand eight hundred. The router can be rules, a classifier, or a cascade that escalates when a check fails.

Lever 4: route by difficulty
chat bill so far:
  13,800 + 7,500 = 21,300
60% easy → small model, ~1/10 price
40% hard → frontier model

21,300 × (0.4 + 0.6 × 0.1)
  = 21,300 × 0.46 ≈ 9,800
saves ~11,500 USD / month

router: rules, a classifier, or
escalate when a check fails

Levers 5 and 6

Two more levers. A response cache stores finished answers, so a repeat question skips the model entirely. At fifteen percent hits, the chat bill falls to about eight thousand three hundred. Key it on the user's plan and the docs version too, and never share personal answers. And work nobody is waiting for, like the nightly summaries, goes through a batch API at roughly half price. Six thousand becomes three thousand.

Response cache and batch API
response cache
  15% of questions repeat
  9,800 × 0.85 ≈ 8,300
  key: normalised question +
  plan + docs version
  never share personal answers

batch API for offline work
  ~50% off, results within ~24 h
  summaries: 6,000 → 3,000

The new bill

The bill, lever by lever. Fifty four thousand at the start. Fewer chunks, forty eight thousand. Prompt caching, thirty one thousand eight hundred. Shorter answers, twenty seven thousand three hundred. Routing, about fifteen thousand eight hundred. Response cache, fourteen thousand three hundred. Batching, about eleven thousand three hundred. Nearly eighty percent lower, same features. Each saving applies to what is left, so change one lever at a time and check quality after each.

The new bill, USD per month
baseline                   54,000
1 three chunks, not five   48,000
2 prompt caching           31,800
3 shorter answers          27,300
4 route 60% to small      ~15,800
5 response cache, 15%     ~14,300
6 batch the nightly job   ~11,300

~79% lower. Savings stack on
what is left, so order changes
each share: measure one at a time

Where latency comes from

Now latency. Each call costs time to first token, which grows with prompt length and queueing, plus output length divided by speed. Calls that wait on each other add up. Here the bot rewrites the query on the frontier model, one and a half seconds. It searches docs, then looks up the account, almost a second. Then it writes four hundred tokens at fifty a second, nearly nine seconds. Eleven point two in total, all behind a spinner.

Where 11.2 seconds go
1 rewrite query, frontier model
   0.7 s first token + 40 tok  1.5 s
2 search docs                  0.3 s
3 look up account              0.5 s
4 answer, frontier model
   0.9 s first token
   + 400 tok at 50 tok/s       8.9 s
total, all one after another  11.2 s

no streaming: a spinner for
the whole 11.2 s

Latency levers

Four fixes. Rewrite the query on a small fast model, six tenths of a second. The doc search and the account lookup are independent, so run them in parallel and pay only for the slower one, half a second. Stream the answer, so words appear as they are generated. And keep it to two hundred and fifty tokens. First words now appear at two seconds instead of eleven point two, and the answer is done at seven.

Same request, faster
1 rewrite on a small model    0.6 s
2+3 search and lookup in
    parallel: max(0.3, 0.5)   0.5 s
4 answer, streamed:
    first token after         0.9 s
first text on screen at       2.0 s
  + 250 tok at 50 tok/s      +5.0 s
fully done at                 7.0 s

first words 5x sooner:
2.0 s instead of 11.2 s

Perceived speed

What users feel matters as much as the stopwatch. Stream every answer, and while an agent works, show what it is doing, like checking your order. Optimistic UI shows the message and a placeholder at once. Speculate when it is cheap: start retrieval while the user types, and discard it if unused. For agents, every step is a full model call, so cap the steps and give each task a time budget.

Make it feel fast
• stream tokens, and show tool
  progress: "Checking your order"
• optimistic UI: show the
  message and a skeleton at once
• speculate: start retrieval
  while the user is typing;
  discard it if unused
• agents: cap steps (say 8)
  and set a wall-clock budget

Budgets and limits

Send all model traffic through one gateway that can count and say no. Give each user a budget, like two hundred thousand tokens a day on the free tier, then switch to a smaller model or stop politely. Give each feature a monthly budget with alerts at half and eighty percent, so a runaway loop is caught in hours. Rate limit each user, queue to stay under the provider's limits, and keep a kill switch per feature.

Budgets and limits
per user: e.g. 200k tokens/day
  on free tier, then a smaller
  model or a polite stop
per feature: monthly budget,
  alerts at 50% and 80%
rate limits: requests per
  minute per user; queue to stay
  under provider token limits
every call: max_tokens set
kill switch per feature

Timeouts and fallbacks

Providers slow down and fail, so every call needs a deadline. Use two timeouts: one for the first token, a few seconds, and one for the whole call. On a timeout or rate limit, retry once with backoff and jitter. Then fall back: another region or provider, a smaller model, a cached answer, and finally an honest please retry. Never retry without limit. In an outage that piles on load and cost exactly when things are worst.

Timeouts and fallbacks
first-token timeout: ~3-10 s
plus a total timeout per call
retry once, backoff + jitter
fallback chain:
  other region or provider
  → smaller model
  → cached or canned answer
  → honest "please retry"

never retry forever: it piles
on load and cost in an outage

p50 and p95

Measure percentiles, not averages. Take a hundred requests: ninety finish in two seconds, ten take twenty. The mean is three point eight seconds, a time no user experienced. The median, p fifty, is two seconds. The p ninety five is twenty seconds, what one user in twenty suffers, and they are the ones who complain. Track both for first token and total time, per feature, and track cost per request the same way.

Why averages lie
100 requests:
  90 take 2 s, 10 take 20 s

mean = (90×2 + 10×20) / 100
     = 3.8 s  (nobody waited 3.8)
p50  = 2 s    the typical user
p95  = 20 s   1 user in 20

track p50 and p95 of first token
and total time, per feature;
and cost per request p95

Numbers worth knowing

Ballparks. Output costs three to five times input. Cached input, ten to fifty percent of the normal price. Batch APIs, about half price, with results within a day. Small models, ten to thirty times cheaper than frontier ones. Time to first token, a fifth of a second to two seconds. Output, thirty to two hundred tokens a second. One agent step, half a second to five. And p ninety five is often two to five times p fifty.

Ballpark numbers
output vs input price  ~3-5x
cached input           ~10-50% of price
batch API              ~50% off, ~24 h
small vs frontier      ~10-30x cheaper
time to first token    ~0.2-2 s
output speed           ~30-200 tok/s
one agent step         ~0.5-5 s
p95 vs p50             often ~2-5x

prices change: recompute often

Common mistakes

Common mistakes. Optimising before knowing which feature spends the money. Cutting prompts or switching models without re running evals, so quality quietly drops. A timestamp at the top of the prompt, which makes every cache read a miss. No max tokens and no step cap, so one bad loop burns a day's budget. Reporting averages. And counting cost per call, not per successful task: a cheap model that needs three retries is not cheap.

Common mistakes
• optimising before measuring
  cost per feature
• cutting tokens without evals,
  so quality quietly drops
• a timestamp at the top of the
  prompt: every cache misses
• no max_tokens, no step cap
• reporting averages, not p95
• cost per call, not per
  successful task

Say it like this

How to say it. Cost is calls times tokens times price, so I attack each term: trim context, cache the stable prefix, cap output, route easy traffic to a small model, and batch offline work, checking evals after each change. For latency I stream, parallelise independent calls and use small models early. A gateway enforces budgets, rate limits, timeouts and fallbacks. And I report p fifty and p ninety five, never the average.

In the interview
  • "Cost is calls × tokens × price, so I cut each term: trim docs, cache the stable prefix, cap output, route easy traffic to a small model, batch offline work, all checked by evals. For latency: stream, parallel calls, small models early. Budgets and timeouts live in the gateway. I watch p95."

Interview questions

Q1What drives the cost of an LLM feature?

Input tokens, output tokens and the number of calls. The whole context is resent on every call, output tokens cost roughly 3-5x more than input, and agents, chains and retries multiply the number of calls, so long-prompt apps are often dominated by input cost.

Q2What makes an LLM response slow?

Time to first token (which grows with prompt length and queueing), plus output length divided by generation speed, summed over every call that must wait for the previous one, plus tool and network time. Long answers and sequential chains are the usual culprits.

Q3How would you cut the monthly bill of an LLM feature?

Measure cost per feature first, then trim the prompt, cache the stable prefix, cap output length, route easy requests to a smaller model, cache repeat answers and move offline work to a batch API. Re-run evals after each change so quality does not silently drop.

Q4How does model routing save money without losing quality?

A router (rules, a classifier, or a cascade that escalates when a check fails) sends easy requests to a model roughly a tenth of the price and keeps the frontier model for hard ones. Evals per route confirm the small model is good enough for its share of traffic.

Q5What is the difference between prompt caching and response caching?

Prompt caching reuses the provider-side work for an identical prompt prefix, so the call still runs but input is cheaper and faster. Response caching stores the finished answer in your own system and skips the model call entirely, which only works for repeat questions and must be keyed so personal answers are never shared.

Q6How do you make an LLM feature feel faster?

Stream tokens so the first words appear in a second or two, show tool progress, run independent calls in parallel, use small models for early steps like query rewriting, keep answers short, cap agent steps and use optimistic UI or speculative prefetching.

Q7How do you stop LLM costs from running away?

Route all calls through a gateway that enforces per-user and per-feature budgets with alerts, rate limits, max_tokens on every call, step caps for agents and a kill switch. Track cost per successful task, not just per call.

Q8Why report p95 latency instead of the average?

Latency is long-tailed, so the mean describes no real user: 90 requests at 2 s and 10 at 20 s average 3.8 s. p50 shows the typical experience and p95 shows what one user in twenty suffers, which is where complaints and timeouts come from.