Cost, Latency & Caching
Every LLM call costs money and time, and both scale with tokens. Hosted APIs typically charge separately for input tokens and output tokens (output is usually priced higher), and generation time grows with the number of output tokens. Understanding these drivers lets you build apps that are fast and affordable.
Note: Prices and speeds differ between providers and models and change often, so this lesson uses made-up "credit" rates. Always check your provider's current pricing page.
Estimating cost
# Hypothetical rates in credits per million tokens - NOT real prices
RATES = {
"large": {"input": 15.0, "output": 75.0},
"medium": {"input": 3.0, "output": 15.0},
"small": {"input": 1.0, "output": 5.0},
}
def cost(model, input_tokens, output_tokens):
r = RATES[model]
return (input_tokens * r["input"] + output_tokens * r["output"]) / 1_000_000
# A support bot: 2,000-token prompt (system + docs + history), 300-token answer, 50,000 requests/day
per_day = {m: cost(m, 2_000, 300) * 50_000 for m in RATES}
for model, credits in per_day.items():
print(f"{model:<7} {credits:>9,.1f} credits/day")large 2,625.0 credits/day
medium 525.0 credits/day
small 175.0 credits/day
Notice that the 2,000 input tokens dominate here: long system prompts, big retrieved contexts and long histories are paid for on every request.
Where latency comes from
| Phase | Depends on |
|---|---|
| Network + queueing | distance to the API, load |
| Processing the input ("prefill") | input length (fast per token, but long prompts add up) |
| Generating the output | number of output tokens × time per token (the dominant part for long answers) |
| Your own steps | retrieval, tool calls, multiple model calls in a chain or agent |
def latency(input_tokens, output_tokens, prefill_tps=5_000, decode_tps=60, overhead_s=0.3):
# Illustrative throughput numbers, not measurements
return overhead_s + input_tokens / prefill_tps + output_tokens / decode_tps
for out_tokens in [50, 300, 1_000]:
print(f"{out_tokens:>5} output tokens -> ~{latency(2_000, out_tokens):.1f} s") 50 output tokens -> ~1.5 s
300 output tokens -> ~5.7 s
1000 output tokens -> ~17.4 s
The quickest win is usually shorter outputs: ask for concise answers, set max_tokens, and avoid generating text nobody reads.
Response caching
If identical requests repeat (FAQ bots, repeated classifications), store the answer and skip the API call. The cache key must include everything that affects the output — model, system prompt, messages and parameters:
import hashlib
import json
cache = {}
api_calls = 0
def fake_llm(request):
global api_calls
api_calls += 1
return f"answer to: {request['messages'][-1]['content']}"
def cached_call(request):
key = hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest()
if key in cache:
return cache[key], "hit"
response = fake_llm(request)
cache[key] = response
return response, "miss"
questions = ["What are your hours?", "Do you ship abroad?", "What are your hours?", "What are your hours?"]
for q in questions:
req = {"model": "small", "system": "Shop FAQ bot.", "temperature": 0,
"messages": [{"role": "user", "content": q}]}
answer, status = cached_call(req)
print(f"{status:<4} {answer}")
print("API calls:", api_calls, "of", len(questions))miss answer to: What are your hours?
miss answer to: Do you ship abroad?
hit answer to: What are your hours?
hit answer to: What are your hours?
API calls: 2 of 4
Exact-match caching only helps when text repeats exactly. Semantic caching looks up previous answers for similar questions using embeddings — powerful, but risky if two similar-looking questions need different answers.
Prompt caching
Many providers offer prompt caching: when consecutive requests start with the same long prefix (system prompt, tool definitions, a large document, earlier conversation turns), the provider can reuse its processing of that prefix. Cached input tokens are billed at a reduced rate and processed faster. To benefit, put stable content first and changing content (the latest user message) last. With the Anthropic API you mark the end of the reusable prefix with a cache_control field (reference code):
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=500,
system=[{"type": "text", "text": LONG_PRODUCT_MANUAL,
"cache_control": {"type": "ephemeral"}}], # cache everything up to here
messages=[{"role": "user", "content": question}],
)
# response.usage reports cache_creation_input_tokens and cache_read_input_tokensOther levers
| Lever | Effect |
|---|---|
| Use the smallest model that passes your evals | lower cost and latency; route only hard requests to a larger model |
| Trim context | send the top 3 chunks, not 20; summarise long histories |
| Shorter outputs | concise instructions, max_tokens, structured output instead of prose |
| Streaming | doesn't reduce cost but makes waiting feel shorter |
| Batch APIs | many providers process non-urgent bulk jobs at a discount with delayed results |
| Parallel calls | independent sub-tasks can run at the same time |
A simple router sends easy requests to a cheap model:
def route(question):
hard_signals = ["compare", "explain why", "step by step", "analyse", "write code"]
long = len(question.split()) > 40
return "large" if long or any(s in question.lower() for s in hard_signals) else "small"
for q in ["What are your opening hours?",
"Compare the X200 and X300 kettles for a family of five.",
"Is the shop open on Sunday?"]:
print(f"{route(q):<5} <- {q}")small <- What are your opening hours?
large <- Compare the X200 and X300 kettles for a family of five.
small <- Is the shop open on Sunday?
Real routers often use a small classifier or the small model itself to decide, and are checked with evals like everything else.
Go further: Fast Inference: KV Cache, Batching and Speculative Decoding explains the serving side of these costs: prefill and decode, continuous batching and speculative decoding.
Test yourself
In the support-bot example, which token type dominated the cost?
- Output tokens
- Input tokens, because the long prompt is sent with every request
- Cached tokens
- Neither; cost is per request
How should you order a prompt to benefit from prompt caching?
- Put the changing user message first
- Put stable content (system prompt, documents) first and changing content last
- Randomise the order
- Order doesn't matter
What must a response-cache key include?
- Only the user's question
- Everything that affects the output: model, system prompt, messages and parameters
- Only the model name
- The current time