Lesson 8.1: Cost and latency optimisation
Cut the cost and delay of an AI feature: where tokens go, model routing and cascades, shorter prompts and answers, streaming, parallel calls and the trade-offs.
A prototype that costs ₹1.50 a request and takes eight seconds feels fine when ten colleagues use it. The same feature at 200,000 requests a month costs ₹3 lakh, and users who wait eight seconds for an answer will not wait again. Cost and delay are not afterthoughts for an AI product. They decide whether the feature can be offered to everyone, at what price and with what experience. The good news is that most systems have large savings available, often a half to three quarters of the bill, and the methods are mostly arithmetic and common sense. The bad news is that cutting without measuring can quietly damage quality. This lesson shows where the money and time go, the handful of levers that matter most, how to route easy requests to cheaper models without hurting quality, how to make an answer feel and be faster, and how to decide when a bigger project such as fine-tuning pays for itself. By the end you will be able to break a request's cost into its parts and find the biggest, compute cost per successful outcome and not only per call, use a cascade of models and work out the saving and the quality effect, shorten prompts and answers sensibly, split a delay into the time to the first word and the time to finish, apply streaming, parallel calls and shorter outputs to cut waiting, and work out the break-even point of a fine-tuning project. You should have read Lessons 3.3, 5.2, 6.1 and 7.2. No programming is needed, and the arithmetic is multiplication and division.
Where the cost goes
A language-model call is billed by tokens, with separate prices for tokens sent in and tokens written out, and output tokens usually cost several times as much per token as input tokens. A request's cost is therefore:
cost = input tokens × input price + output tokens × output price.
For a RAG question, Lesson 5.1 found about 3,740 input tokens and 300 output tokens, costing about ₹0.15 at example prices. For an agent run, Lesson 7.2 showed that cost grows faster than the number of steps. For a tool-using turn, Lesson 7.1 showed that tool definitions and results add to the input. Apart from the model itself, there are other costs: embedding, reranking, vector storage, servers, logging and the people who review outputs. Start by writing down, for your feature, the cost per request split into these parts, since the largest part is where to look first.
Measure the right thing
Before you change anything, fix the measurement.
Cost per task, not per call. If a task needs three calls, the unit that matters is the cost of all three. Track cost per resolved question, per summarised document or per completed booking.
Cost per success. A cheap model that fails often is not cheap. If a small model costs ₹0.05 per attempt and succeeds 70% of the time, each success costs about ₹0.05 ÷ 0.70 = ₹0.071, before counting the cost of the failures: a retry, an escalation to a bigger model or a human. If a large model costs ₹0.30 and succeeds 92% of the time, each success costs ₹0.30 ÷ 0.92 = ₹0.326. The small model still wins on this crude measure, but the gap is smaller than the sticker prices suggest, and if a failure costs a person's time, it can reverse.
The distribution, not only the average. A few very long requests can account for much of the bill, and the slowest requests drive complaints, as Lesson 6.4 showed.
Quality alongside cost. Every saving should be checked against your eval set, by slice. A cost cut that lowers quality in one slice is not free.
Predict first: a feature handles 200,000 requests a month using a large model at ₹0.30 a request. About 70% of requests are simple. If a small model at ₹0.02 could handle those simple ones as well as the large one does, and you send every request to the small model first and only the rest to the large one, what would the monthly bill be? Work it out before you read on.
Lever 1: do less
The cheapest call is the one you do not make.
Use rules where rules work. A request to "reset my password" or "what are your hours" may be handled by a fixed reply or a lookup, with no model at all.
Cache repeated work. If the same question or the same long prompt prefix appears again and again, store the answer or reuse the processed prefix, as Lesson 8.2 explains. A response cache with a 25% hit rate removes a quarter of the calls.
Avoid redundant steps. An agent that searches three times for the same thing, a pipeline that rewrites a query that is already clear, a reranker on a list of three: each is waste. Read traces for repeated or useless calls.
Stop early. If a task can be answered after one search, do not run ten steps. Use stop rules from Lesson 7.2.
Do not call a model on empty or invalid input. Check inputs first.
Lever 2: send fewer tokens
Input tokens are often the larger part of the bill, because prompts carry instructions, history, tool definitions and retrieved text.
Trim the instructions. Long prompts accumulate rules over time. Remove duplicates and rules that no test depends on. A prompt cut from 1,200 to 700 tokens saves 500 tokens on every call.
Send fewer, better chunks. As Lesson 5.2 showed, a reranker lets you send four chunks, not ten, saving 3,000 tokens a request.
Trim the history, by dropping old turns, summarising or keeping notes, as in Lesson 7.3.
Send only the tools that could be needed. Ten tools of 150 tokens each add 1,500 tokens to every call.
Compress tool results, returning a few useful fields and not a whole record.
Shorten examples, or use fewer. Keep the ones that your evals show matter.
Each cut should be tested. A shorter prompt may change behaviour in ways you do not expect, and your eval set is the guard.
Lever 3: write fewer tokens
Output tokens cost more per token and also take time to generate, so shortening answers saves both.
Ask for the format you need. "Answer in two sentences" or "return only the order status as a short phrase" is cheaper than a long, friendly paragraph.
Use structured output with short fields, as in Lesson 3.2, and not free text that must be parsed.
Set a maximum output length as a safety net.
Do not ask the model to repeat the input or restate the question.
Keep reasoning short where a task does not need long reasoning. Models that "think" at length use many tokens, and you should use that only where it improves your eval scores.
If an answer falls from 300 tokens to 150, at ₹120 per million output tokens the saving is 150 × 120 ÷ 1,000,000 = ₹0.018 per request, or ₹3,600 a month at 200,000 requests. It also saves three seconds at 50 tokens a second.
Lever 4: right-size the model
Models differ widely in price and power. A large model may cost ten times as much per request as a small one. For many tasks, such as classification, extraction, simple questions and formatting, a small model is as good. Use the larger model where it is needed.
Routing. A cheap classifier, or a rule, decides which model handles a request: simple requests go to the small one, hard ones to the large one.
A cascade. Every request goes to the small model first. If its answer passes a check, such as a confidence rule, a validity test or a quick judge, it is returned. If not, the request is escalated to the large model. You pay for the small attempt on every request, and for the large model only on those that escalate.
Work through the opening question. Every request goes to the small model at ₹0.02. The 30% that it cannot handle go on to the large model at ₹0.30. The expected cost per request is 0.02 + 0.30 × 0.30 = ₹0.11. At 200,000 requests a month the bill falls from 200,000 × 0.30 = ₹60,000 to 200,000 × 0.11 = ₹22,000, a saving of ₹38,000 a month, 63%.
The saving is real only if quality holds. The small model must really handle the 70% that it keeps, and the check must really catch the failures. Suppose the small model is right 94% of the time on the requests it keeps, the large model is right 85% of the time on the harder escalated ones and the large model alone would be right 92% of the time on everything. The cascade's accuracy is 0.70 × 94 + 0.30 × 85 = 65.8 + 25.5 = 91.3%, against 92% for the large model alone. You give up about 0.7 points to save 63% of the cost. That may be an excellent trade, or not, depending on what a mistake costs. This is a decision to make with eval numbers on each slice, not by feel.
Lever 5: batch and cache
Two further levers are covered in the next lesson, and are worth knowing about here.
Prompt caching lets a provider reuse the processed form of a long, unchanging prefix, such as instructions and tool definitions, at a lower price and a lower delay. Put the fixed material first and the changing material last.
Batching sends many non-urgent requests together for processing later, often at a lower price. It suits overnight jobs such as classifying a backlog or summarising documents, and does not suit a user waiting for a reply.
Latency: two numbers, not one
A user's wait has two parts that matter in different ways.
Time to first word: how long until something appears. This sets the feeling of responsiveness.
Time to finish: how long until the whole answer is there. This matters when the user cannot act until it is complete, such as a parsed form.
For a RAG answer, the time to the first word is the sum of the steps before generation begins: retrieval, reranking and the model's own start-up delay. Take example figures: retrieval 80 milliseconds, reranking 150 and the model's time to first token 600. The user sees the first word after 830 ms. Then the model writes the answer at, say, 50 tokens a second. A 300-token answer takes 6 seconds, so the total is 6.83 seconds. Most of the wait is the writing.
Making things faster
Stream the answer, as Lesson 3.3 explained. The user starts reading at 0.83 seconds and does not feel the next six. Streaming does not shorten the total, but it greatly improves how fast it feels.
Write less. A shorter answer finishes sooner. Cutting 300 tokens to 150 saves three seconds at 50 tokens a second.
Choose a faster model where the task allows. Smaller models usually start sooner and write faster.
Run independent steps in parallel. If a question needs a search of two sources, do both at once. Total time is the longer of the two, not the sum.
Cut sequential hops. Each model call in an agent adds a full round trip. Merge steps, reduce tool calls and keep the number of sequential calls low, as Lesson 7.2 showed.
Start early. Begin retrieval while the user is still typing, or prepare common context ahead of time.
Cache the results of repeated lookups and the processed prompt prefix.
Mind the network. Place your servers near the model provider and the user, and reuse connections.
Set timeouts and fallbacks. If a step is slow, give up on it, return a partial answer or use a backup, so that the tail does not grow. Lesson 6.4 showed why the tail matters.
Show progress. A line such as "Searching your documents..." makes a wait feel shorter and tells the user that something is happening.
When a bigger project pays: fine-tuning and distillation
Sometimes a small model, trained on examples of the task, can match a large model on a narrow job. You can collect the large model's good answers, or human-checked answers, and use them to fine-tune a small model. The inference cost then falls permanently, but the project has costs: collecting and cleaning data, training, evaluating, hosting and maintaining the model as the task changes.
The test is the break-even point. Suppose the project costs ₹2,00,000 once, and the fine-tuned small model saves ₹0.15 on each request. The break-even volume is 2,00,000 ÷ 0.15 = about 1.33 million requests. At 100,000 requests a month that takes 13 months, and at 500,000 a month under 3. A volume that low may not justify the effort, particularly if the task changes often and the model needs retraining. At high, stable volume, it is attractive. Always check against simpler levers first, such as prompt trimming, caching and a cascade, which often deliver most of the saving for a fraction of the work.
An order of work
1. Measure. Cost per task, cost per success, delay at the median and the tail, and quality by slice.
2. Find the biggest part. Input, output, retrieval, agent steps or something else?
3. Do less. Remove redundant calls, use rules and cache.
4. Send and write fewer tokens.
5. Right-size the model, with routing or a cascade, checked on your evals.
6. Speed up the experience: stream, parallelise and cut hops.
7. Consider a bigger project only if the volume justifies it.
8. Guard. Run the evals after each change, and monitor cost and delay in production.
Three worked examples
Example 1: a support cascade. A support assistant handles 200,000 requests a month with a large model at ₹0.30, a bill of ₹60,000. Reviewing the logs, the team finds that 70% are simple: order status, hours, resetting a password. They add a cascade with a small model at ₹0.02, with an escalation rule when the model says it is unsure or its answer fails a format check. The bill falls to about ₹22,000. On their eval set, accuracy drops from 92% to 91.3%, and in the refunds slice, it falls 4 points. They route refund questions straight to the large model, which restores the slice and costs a few thousand rupees more. The final saving is about ₹33,000 a month.
Example 2: a faster answer. A document assistant takes 6.8 seconds to finish and users complain. The trace shows 830 ms to the first token and six seconds of writing 300 tokens. The team does three things: it asks for a concise answer format of about 150 tokens, it streams the response and it runs the two searches in parallel, saving about 100 ms. The time to the first word is about 730 ms, and the total falls to about 3.7 seconds, nearly half. Satisfaction scores rise, and the cost per request also falls because the output is shorter.
Example 3: whether to fine-tune. A team of a legal-tech firm classifies contract clauses into 40 types, 600,000 times a month, using a large model at ₹0.12 a call. A fine-tuned small model would cost ₹0.02 a call, saving ₹0.10, and the project would cost about ₹4,00,000. The break-even volume is 4,00,000 ÷ 0.10 = 4 million calls, which is under 7 months of traffic at 600,000 a month. The clause types are stable, and the eval set exists. The team goes ahead, and checks that accuracy on every clause type matches the large model before switching.
A cost and latency worksheet
1. The unit. What is one task, and what does it cost now, split into parts?
2. The delay. Time to first word and to finish, at the median and the 95th percentile.
3. The biggest part. Where do most of the tokens and most of the seconds go?
4. Do less. Calls that could be rules, caches or removed.
5. Fewer tokens in. Instructions, chunks, history, tools, results.
6. Fewer tokens out. Format, length, structure.
7. The model. Where a smaller model or a cascade would do, with the quality check.
8. The speed. Streaming, parallel calls, fewer hops, timeouts.
9. The big project. Break-even volume for any fine-tune.
10. The guard. Evals by slice and production monitoring after each change.
Common mistakes
Optimising before measuring.
Looking at cost per call and not per task or per success.
Cutting tokens or switching models without running the evals.
Using a large model for everything, including easy requests.
Using a cascade without a reliable check, so that errors pass through.
Looking only at average delay.
Ignoring output length, which drives both cost and time.
Fine-tuning when simpler levers would do.
Treating a saving as permanent when prices, models and traffic keep changing.
Key takeaways
Cost is input tokens times the input price plus output tokens times the output price, and output tokens cost more per token. Break a request's cost into parts and attack the largest.
Measure cost per task and per success, the tail and quality by slice. A cheap model that fails often is not cheap.
The levers, roughly in order: do less, send fewer tokens, write fewer tokens, right-size the model, batch and cache, and only then consider bigger projects.
A cascade sends everything to a small model and escalates the rest. In the example it cuts the cost per request from ₹0.30 to ₹0.11, a 63% saving, for a loss of about 0.7 points of accuracy.
A wait has a time to first word and a time to finish. In the example 830 ms to start and 6 seconds writing 300 tokens, so most of the wait is the writing.
Stream, shorten answers, run steps in parallel, cut sequential hops, set timeouts and show progress.
A fine-tuning project pays when volume is high and the task is stable. A ₹2,00,000 project saving ₹0.15 a call breaks even after about 1.33 million calls.
Check yourself
1. A request has 4,000 input tokens at ₹30 per million and 200 output tokens at ₹120 per million. What does it cost?
4,000 × 30 ÷ 1,000,000 = ₹0.12, and 200 × 120 ÷ 1,000,000 = ₹0.024. The total is ₹0.144.
2. A cascade sends all requests to a model costing ₹0.04, and 25% go on to a model costing ₹0.40. What is the expected cost per request?
0.04 + 0.25 × 0.40 = ₹0.14.
3. An answer of 400 tokens is written at 40 tokens a second. How long does the writing take, and how long if the answer is cut to 200 tokens?
400 ÷ 40 = 10 seconds, and 200 ÷ 40 = 5 seconds.
4. Why does streaming not reduce the total time but still help?
The answer takes as long to finish, but the user starts reading after the first words arrive, so the wait feels much shorter.
5. A model costs ₹0.10 an attempt and succeeds 80% of the time. What is the cost per success?
0.10 ÷ 0.80 = ₹0.125.
6. Why check each saving against the eval set?
A cut in tokens, a smaller model or a cascade can lower quality in some slices without any sign in the cost figures.
Try this
Find the savings in an AI feature. Set aside 60 minutes.
1. Choose a feature you run or plan, and write its typical request: input tokens, output tokens, tools or retrieval, and the number of model calls.
2. Work out the cost per request at your provider's current prices, and per month at your expected volume.
3. Write the delay: time to the first word and to finish, using the second simulator with your own numbers.
4. List the three biggest parts of the cost and the three biggest parts of the delay.
5. For each biggest part, write one change from this lesson, with an estimate of the saving.
6. Use the first simulator to test a cascade for your traffic, with honest guesses of the share a small model could handle and the accuracy of each model, and note what eval check would confirm it.
7. Write the order in which you would try the changes, and the quality guard for each.
A good result is a cost breakdown, a delay breakdown, three prioritised changes with savings estimated, a cascade estimate with its quality check and a written plan for guarding quality.
Tags: AI Engineering Cost optimisation Latency LLM applications Production