Sub topic 17
Managing cost and latency
This chapter assumes you can call a model API from Python, read JSON, and have seen the prompting, retrieval, and tool-use chapters. It covers where the money and the waiting time go in an LLM feature, and the usual ways to reduce both without hurting quality.
Where cost comes from
Hosted models bill by the token. A token is a chunk of text, roughly three to four English characters. Most providers charge separately for input tokens (everything you send) and output tokens (everything the model writes). Output tokens usually cost several times more than input tokens.
A request's cost is:
cost = input_tokens * input_price + output_tokens * output_pricePrices are quoted per million tokens and change often. Treat any number in this chapter as an example, and read your provider's current price list.
Three things inflate input tokens more than people expect:
- Long system prompts that are resent on every call.
- Conversation history. In a chat, each turn resends all earlier turns, so total input grows faster than the number of turns.
- Retrieved passages in a retrieval-augmented generation (RAG) feature. Ten passages of 500 tokens add 5,000 input tokens to every question.
Agents multiply these effects. Each loop iteration is a new model call that carries the whole history plus the latest tool result.
Where latency comes from
Latency is the time between sending a request and getting a usable answer. Two parts matter:
- Time to first token: the wait before output starts. It grows with input length and with server load.
- Generation time: output tokens are produced one after another, so time grows roughly in proportion to output length.
A rough model is:
latency = queue_and_network + input_processing + output_tokens * time_per_tokenOutput length is therefore the most direct lever. A classifier that returns one label finishes far sooner than one that writes a paragraph of explanation first.
Measure before you optimize
Log the numbers for every call. Most APIs return token counts in the response. Record them with the model name, the feature, and elapsed time.
import time
def timed_call(complete_with_usage, prompt, log):
start = time.perf_counter()
text, usage = complete_with_usage(prompt) # usage: {"input": int, "output": int}
elapsed = time.perf_counter() - start
log.append({
"seconds": round(elapsed, 3),
"input_tokens": usage["input"],
"output_tokens": usage["output"],
})
return text
def fake_model(prompt):
return "billing", {"input": len(prompt.split()), "output": 1}
log = []
timed_call(fake_model, "Classify this ticket: I was charged twice", log)
print(log)Then look at percentiles, not averages. The 95th percentile (p95) is the time that 95% of requests beat. Users notice the slow tail, and an average hides it.
Levers that reduce cost and latency
Choose the smallest model that passes your tests
Providers offer a range of models. Smaller ones are cheaper and faster, and are often good enough for classification, extraction, and short rewrites. Use the evaluation set from the testing chapter. Run each candidate model on it, and pick the cheapest one that meets your quality bar. Re-run the comparison when new models appear.
A common design is routing: a small model handles easy requests and a larger one handles hard ones. Routing adds its own failure mode. If the router sends a hard request to the small model, quality drops silently, so keep sampling and reviewing routed traffic.
Shorten the prompt
- Remove instructions that your tests show have no effect.
- Keep few-shot examples to the fewest that hold quality.
- Retrieve fewer, better passages. Check whether top 3 performs as well as top 10.
- Summarize or trim old conversation turns, keeping recent turns verbatim.
Limit output
Ask for the label only, or for JSON with no commentary. Set a maximum output token parameter as a safety cap. If the cap is too low, the reply is cut off mid-answer, so validate the result as in the structured output chapter and treat a truncated reply as a failure.
Use prompt caching
Many providers can cache a long, unchanging prompt prefix, such as a system prompt or a reference document. Cached input tokens are billed at a reduced rate and are processed faster. Caching only matches an identical prefix, so put stable content first and variable content (the user's question) last. Check your provider's minimum prefix size and cache lifetime.
Cache whole answers
If the same request recurs, store the answer in your own cache. Key it on a hash of the model, prompt, and settings.
import hashlib
import json
_cache = {}
def cached_complete(complete, model, prompt, temperature=0):
key = hashlib.sha256(
json.dumps([model, prompt, temperature]).encode()
).hexdigest()
if key not in _cache:
_cache[key] = complete(prompt)
return _cache[key]
calls = []
def fake_complete(p):
calls.append(p)
return "bug"
cached_complete(fake_complete, "small-model", "Ticket: app crashes")
cached_complete(fake_complete, "small-model", "Ticket: app crashes")
print(len(calls)) # 1This suits deterministic tasks such as classification. It is a poor fit for personalized answers, and any answer built from data that changes needs an expiry time.
Stream output
Streaming sends tokens as they are generated. Total time is unchanged, but the user sees text after the first token instead of waiting for the whole reply. This improves perceived latency in chat and drafting. It does not help when you must validate the full output before showing it, as with JSON.
Run independent calls in parallel
If you must classify 50 documents, or call three tools that do not depend on each other, issue the calls concurrently. Wall-clock time falls toward the slowest single call. Respect provider rate limits, and retry on rate-limit errors with exponential backoff, which means waiting longer after each failure.
Batch work that is not urgent
Some providers offer a batch interface that runs jobs asynchronously, often within hours, at a discount. It suits nightly summarization or bulk labeling. It does not suit anything a user is waiting for.
Trade-offs and failure modes
| Change | Saves | Risk |
|---|---|---|
| Smaller model | Cost and time | Lower accuracy on hard cases |
| Shorter prompt | Input cost | Dropped instruction changes behavior |
| Fewer retrieved passages | Input cost | Answer's source is missing |
| Output cap | Output cost and time | Truncated replies |
| Answer cache | Whole call | Stale or wrong-user answers |
| Batch API | Cost | Delay |
Other failure modes to watch:
- Retry storms. Automatic retries on timeouts multiply load and cost. Cap the number of retries.
- Runaway agent loops. Set a maximum step count and a per-task token budget, and stop when either is reached.
- Unbounded user input. A user can paste a book. Limit input length before you send it.
- Cost surprises from growth. A feature that costs little in a pilot can be expensive at scale, so estimate before launch.
Estimating before you build
Estimate with a small calculation, using your own measured token counts and current prices.
def monthly_cost(requests_per_day, in_tokens, out_tokens,
in_price_per_m, out_price_per_m, days=30):
per_request = (in_tokens * in_price_per_m
+ out_tokens * out_price_per_m) / 1_000_000
return per_request * requests_per_day * days
# Example prices only: $1 per million input, $4 per million output
print(round(monthly_cost(10_000, 1_200, 150, 1.0, 4.0), 2))This prints 540.0. Try changing the retrieved passages from ten to three and see how the input term moves. Add a safety margin of at least 20 to 30 percent, because real traffic has longer inputs than your samples.
A practical order of attack
- Instrument token counts and latency per feature.
- Cap input and output lengths.
- Move stable content to the front and enable prompt caching.
- Test smaller models against your evaluation set.
- Trim retrieved context and history.
- Add streaming, parallelism, and answer caching where they fit.
- Set budgets and alerts so a bug cannot spend without limit.
Exercise
A support bot sends a 3,000-token system prompt and the full chat history on every turn. Replies are slow to start and the bill is growing faster than traffic. Name two changes that reduce input cost, and say what you would check after making them.
Show answer
Enable prompt caching with the system prompt placed first as a stable prefix, and trim or summarize older conversation turns while keeping recent ones. After the changes, re-run the evaluation set to confirm answer quality did not drop, and compare input tokens per request, cost, and p95 latency before and after.
Exercise
Your JSON extraction feature starts failing validation after you lower the maximum output tokens to save money. What is the likely cause, and how should the code respond to this failure?
Show answer
The cap is cutting replies off before the JSON is complete, so parsing fails. Raise the cap to fit the longest expected output, and treat a truncated or unparseable reply as an error: reject it, optionally retry once, and log it rather than passing partial data downstream.