LLM API cost and latency: tokens, prompt caching, batching and model choice
LLM bills and p99 latency grow with tokens, not with request counts. How to estimate cost per task, keep the prefix stable so prompt caching hits, batch work that isn't urgent, pick a smaller model only with quality measured, and set per-user token budgets.
On this page
1. The problem
A support chatbot sends 30 pages of policy (about 20,000 tokens) with every question. 50,000 questions a day is 1 billion input tokens; at an assumed 3 USD per million tokens, input alone costs 3,000 USD a day. p99 is 9 seconds.
2. Key idea
Providers charge and spend time per token, so cost follows prompt and answer length, not request count. Output tokens usually cost 4–8× input tokens and are generated one by one, so they dominate latency.
2.1 Which lever first?
Cheapest first: cache, batch, fewer tokens, and only last a different model. Retries and tool loops resend the whole context, so they count against the budget too.
| Lever | Use when | Don't use when |
|---|---|---|
| Prompt cache | the start of the prompt is long and repeated | the prompt is under the provider's minimum (often ~1,024 tokens) |
| Batch API | nightly jobs, bulk classification | a user is waiting |
| Smaller model, routing by difficulty | classification, extraction | there's no quality check to compare |
| Output token cap | answers for humans, schema-bound JSON | you need long text in full |
| Fewer input tokens (fewer RAG chunks, summarized history) | context grows over time | the dropped part holds needed information |
3. In Java
String answer(String userId, String question) {
String key = "llm:tokens:" + userId + ":" + LocalDate.now(ZoneOffset.UTC);
long used = Optional.ofNullable(redis.opsForValue().get(key)).map(Long::parseLong).orElse(0L);
if (used > DAILY_TOKEN_LIMIT) throw new TooManyRequestsException("Daily quota used up");
ChatResponse res = chat.prompt()
.system(POLICY_PROMPT) // fixed part, always first: the cache can hit
.user(question) // changing part, after it
.call().chatResponse();
Usage usage = res.getMetadata().getUsage();
String model = res.getMetadata().getModel();
meter.counter("llm.tokens", "model", model, "type", "input").increment(usage.getPromptTokens());
meter.counter("llm.tokens", "model", model, "type", "output").increment(usage.getCompletionTokens());
redis.opsForValue().increment(key, usage.getTotalTokens());
redis.expire(key, Duration.ofDays(2));
return res.getResult().getOutput().getText();
}Other languages: the Python, Node.js and Go SDKs all return usage with every response; field names differ per provider.
How prompt caching works
- The provider stores the computed state of the prompt's beginning. A later request with the same, byte-identical prefix pays much less for that part and gets its first token sooner.
- What breaks the prefix: the current time, a request id or the user's name at the top; tools in a changing order; JSON built from unsorted maps.
- Some providers cache automatically, others need cache breakpoints; writing the cache can cost more than reading it. Caches live a few minutes, so sparse traffic hits less.
- Verify with the cache-read token count in
usage, and chart that ratio on a dashboard.
4. Working with AI
Hand to AI: a script estimating cost from real usage logs, grouping tokens by feature and model; a test asserting the prompt prefix doesn't change between two requests.
Check yourself in AI-written code:
- The fixed part of the prompt comes first, with no time or request id in it; tools have a fixed order.
- Each feature has an output token cap.
- Every call records input, output and cache-read tokens by model and feature.
- There's a per-user or per-tenant token quota, checked before calling.
5. Exercises
Exercise 1: Review "prompt caching enabled"
The AI says "prompt caching is on, cost will drop 90%". A day later, cache-read tokens are still 0. Find the bug and fix it.
String system = "Today is " + LocalDateTime.now() + ".\n" + POLICY_DOC;
chat.prompt().system(system).user(question).call().content();Solution 1
LocalDateTime.now() sits at the top of the system prompt, so the prefix changes every second and the cache never hits; each request may even pay the cache-write price.
Fix: put POLICY_DOC first and the date last (or in the user message), with the date only, not the time. Test: send two requests back to back and assert cache-read tokens are above 0; alert when that ratio drops.
Exercise 2: Read a bill that tripled
Requests per day are flat, but this week's bill is 3× last week's. Dashboard: input tokens per request went from 6,000 to 19,000, the cache-read ratio from 70% to 2%, starting with Tuesday's deploy. Diagnose it, say what to do in 15 minutes, fix the root cause.
Solution 2
- Tuesday's release both lengthened the prompt (full history or more RAG chunks) and changed the prefix (the user's name inserted at the top, or tool order changing on every startup).
- 15 minutes: diff the prompt against the previous release; roll back or switch it off with a feature flag.
- Root fix: per-user parts go after the fixed part, sort tools by name, cap or summarize history. Alert when the cache-read ratio drops or average input tokens rise more than 30%.
Summary
- Cost per task = input tokens × input price + output tokens × output price, including retries and tool loops.
- Output tokens dominate latency.
- The prompt cache needs a byte-identical prefix: fixed first, changing last.
- Non-urgent work goes through the Batch API; move to a smaller model only with quality checks.
- Per-user token quotas, token metrics per model.
Further reading: Evaluating LLM output.
Comments
Community rules