Token counting, cost & latency
Estimate per-request cost and cut it with shorter prompts, caching and smaller models.
By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.
In short
LLM cost is mostly input tokens plus output tokens times their prices, and latency grows with output length and model size. Measuring both per request shows where to cut.
Explained simply
You pay for an LLM call by the token. Every token you send (input) has a price, and every token the model writes (output) has a usually higher price. A long system prompt, a long chat history or many pasted documents all add input tokens on every single call.
Latency means waiting time. Two numbers matter: how long until the first words appear, and how long until the whole answer is done. The model writes output one token at a time, so a long answer takes longer than a long question.
You cannot improve what you do not measure. Log the token counts, the cost and the time for every call. After a day you will see which feature, prompt or user drives most of the bill.
Then use the levers: send fewer tokens, ask for shorter answers, use a smaller model for easy jobs, and use caching so repeated work is cheaper. Each change should be checked with your evals so quality does not quietly drop.
Press Play on a diagram to walk through it one step at a time.
- Fewer input tokens
- Shorter prompts
- Retrieve fewer chunks
- Trim chat history
- Fewer output tokens
- Ask for concise answers
- Set max output tokens
- Cheaper model
- Smaller model for easy tasks
- Route by difficulty
- Caching
- Prompt caching for shared prefixes
- Response cache for repeats
- 1Log every call
Tokens, cost, TTFT, total time, feature
- 2Find the top spender
Group by feature, prompt and model
- 3Apply one lever
Shorter prompt, smaller model or caching
- 4Re-run evals
Quality must stay above the bar
- 5Ship and watch
Compare the new numbers with the old
- Back to step 1
In depth
Counting tokens before you send
Each model family has its own tokenizer, so the same text gives different counts on different models. Options for counting: a local tokenizer library for that model (for example tiktoken for OpenAI models, or the model's tokenizer loaded with Hugging Face transformers for open models), or a token counting endpoint if your provider offers one. Character-based estimates (about 4 characters per English token) are fine for rough planning but not for hard limits.
The usage numbers in each API response are the ground truth for billing. Record them on every call.
Before sending, check the budget: context window minus the max output tokens minus a safety margin must be at least your input count. If not, trim history or retrieved chunks first, rather than letting the API reject the call. Chat formatting and tool definitions add some tokens beyond your visible text, so keep a margin.
- Different model, different tokenizer, different count
- Usage in the response is what you are billed
- Input budget = window - max output - margin
- Trim history and context before sending, not after an error
Where the waiting time goes
A call's latency has three parts. First, network and queueing: reaching the provider and waiting for capacity. Second, prefill: the model reads your whole prompt; this is fast per token because it runs in parallel, but very long prompts still add noticeable time. The end of prefill is when the first token appears: time to first token (TTFT). Third, decode: the model writes the answer one token at a time at a roughly steady speed, measured in output tokens per second.
So total latency is roughly TTFT plus output tokens divided by speed. Cutting a 600-token answer to 200 tokens saves far more time than trimming the prompt by the same amount.
Measure with time.perf_counter() around each call, and record TTFT when streaming. Report p50 and p95, not the average: a few very slow calls hide in an average.
- 1Network and queue
Reach the provider, wait for capacity
- 2Prefill
Read the whole prompt in parallel
- 3First token
TTFT is measured here
- 4Decode
One token at a time, steady speed
- 5Done
Total = TTFT + output tokens / speed
Prompt caching: reuse the start of your prompt
Many requests start the same way: the same system prompt, tool definitions or reference document, followed by a different question. Prompt caching lets the provider keep the processed start (the prefix) for a short time. Later requests with exactly the same prefix are billed at a reduced input price and usually get a faster TTFT.
The key word is exactly. A cache hit needs an identical prefix, token for token. Put stable content first and changing content last. A timestamp or user name near the top of the system prompt breaks caching for everything after it.
Details vary by provider: some cache automatically, others need you to mark cache points; most need a minimum prefix length; caches expire after a few minutes without use; and some charge extra to write the cache. The response usage usually reports how many input tokens were read from cache, so you can confirm it works.
- 1System prompt
Same on every call
- 2Tool definitions
Same on every call
- 3Reference documents
Same for a session
- 4Conversation history
Grows, but its start stays the same
- 5New user message
Changes every call: keep it last
Smaller models, routing and other levers
Model choice is the biggest lever: small models can cost ten or more times less per token than the largest ones and respond faster. Routing sends each request to the cheapest model likely to handle it. Simple rules work (classification and extraction to the small model, long reasoning to the large one), or a small model can try first and pass low-confidence cases up.
Other levers: ask for concise answers and set max output tokens; send fewer retrieved chunks; trim or summarise chat history; cache full responses for exact repeated questions; and use the provider's batch API, which is often around half price, for work that can wait hours.
Watch hidden costs too. Retries, agent loops that call the model many times, reasoning tokens billed as output, and embedding calls all add up. Your logs should show cost per feature and per user, not just one monthly total.
- Route easy tasks to small models
- Cap max output tokens and ask for brevity
- Batch APIs for offline work
- Count retries, loops and reasoning tokens
Learn it in 4 short steps
About 30m each. Track them with a timer in your plan.
- 1Count tokens before sending~30m
- 2Estimate cost per request~30m
- 3Measure latency per call~30m
- 4Cut cost with caching and smaller models~30m
Key points
- Output tokens usually cost more than input tokens and dominate latency.
- Count tokens before sending to avoid overflowing the context window.
- Log tokens, cost and latency for every call so trends are visible.
- Route simple tasks to small models and reserve large ones for hard cases.
Key terms
Tap a card to flip it. 0/5 known
Examples
# Prices per million tokens (example numbers, check your provider)
PRICE_IN = 1.00
PRICE_OUT = 4.00
def cost_usd(tokens_in: int, tokens_out: int) -> float:
return tokens_in / 1e6 * PRICE_IN + tokens_out / 1e6 * PRICE_OUT
per_call = cost_usd(tokens_in=3000, tokens_out=500)
print(f'${per_call:.4f} per call')
print(f'${per_call * 10_000 * 30:.2f} per month at 10k calls/day')Estimate per-call and monthly cost from token counts.
Measuring TTFT and output speed
Users say answers feel slow. Step 1: wrap the streaming call with time.perf_counter(). Step 2: record the moment the first chunk arrives (TTFT). Step 3: count chunks and divide by the decode time to get the output speed. The fake stream waits 0.8 seconds, then sends 50 chunks at about 50 per second. Real chunks can hold more than one token, so use the token usage from the final event for exact speed. If TTFT is the problem, look at prompt length and queueing; if decode is, shorten the answers or use a faster model.
import time
def fake_stream():
time.sleep(0.8) # waiting for the first token
for _ in range(50):
time.sleep(0.02) # about 50 chunks per second
yield "tok "
start, ttft, n = time.perf_counter(), None, 0
for chunk in fake_stream():
if ttft is None:
ttft = time.perf_counter() - start
n += 1
total = time.perf_counter() - start
print(f"TTFT {ttft:.2f}s, total {total:.2f}s, {n / (total - ttft):.0f} chunks/s")What a 20-turn chat really costs
A support chat has a 2,000-token system prompt, and each turn adds about 200 tokens of history (question plus answer). The new question is about 50 tokens. Step 1: add up the input tokens for all 20 turns: because history is resent every time, it comes to 79,000 input tokens, not 20 x 2,250. Step 2: with prompt caching, the repeated prefix from turn 2 onward is billed at a discount. With an example rate of 10% of the normal price (and ignoring any cache-write fee), you pay the equivalent of about 10,600 tokens. Check your provider's real rates.
SYSTEM, PER_TURN, NEW_MSG, TURNS = 2000, 200, 50, 20
CACHED_RATE = 0.10 # example: cached input billed at 10%
full = cached = 0.0
for turn in range(1, TURNS + 1):
prefix = SYSTEM + PER_TURN * (turn - 1)
full += prefix + NEW_MSG
rate = CACHED_RATE if turn > 1 else 1.0
cached += prefix * rate + NEW_MSG
print(full, cached) # 79000.0 10600.0 (billed-equivalent input tokens)Quick reference
- Cost = input tokens x input price + output tokens x output price
- Latency is about TTFT + output tokens / tokens per second
- Report p50 and p95 latency, never only the average
- Count tokens with the model's own tokenizer or the API's usage numbers
- Prompt caching needs an identical prefix: stable content first, new message last
- Batch APIs are often around half price for work that can wait
- Set max output tokens and ask for concise answers to cut both cost and time
- Log cost per feature and per user, including retries and agent loops
Common mistakes
- Estimating cost from character counts instead of real token counts.
- Stuffing many retrieved chunks into every prompt just in case.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write cost_usd(tokens_in, tokens_out, price_in, price_out) with prices per million tokens, and compute the monthly cost of 2,000 calls a day with 1,500 input and 400 output tokens.
- Exercise 2medium
Write a decorator or context manager that logs model, tokens in, tokens out, cost and latency for every call as one JSON line.
- Exercise 3hard
Build a simple router: send each request to a small model first, and escalate to a large model only when the small model's structured reply has confidence below 0.7. Measure cost and accuracy on 50 eval examples versus always using the large model.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why are output tokens more expensive than input tokens?
- Input is processed in parallel in one pass, while output needs a separate step for each token. That makes output more expensive for the provider to serve.
- Is prompt caching the same as caching responses?
- No. Prompt caching reuses the provider's work on a repeated prompt start, and the model still writes a fresh answer. A response cache in your app returns a stored answer and skips the model completely.
- How can I see my LLM spend per feature?
- Tag every call with a feature name in your logs or tracing tool, record tokens and cost per call, and group by that tag. Provider dashboards usually only show totals per key or model.