AI Academy · Book
Engineering Managers · Module 08 · Chapter 003

Controlling Token and Inference Cost in Features

Most savings in an AI feature come from asking the model to do less, not from finding a cheaper price. Output limits, trimmed prompts, routing, caching and batching each cut the bill, and each can quietly cut quality too. A manager who fixes the order and demands a quality check after every step can approve the savings without gambling on the feature.

≈ 11 min read

After this chapter you can

  • Freeze a baseline of cost per request, a fixed evaluation set, its score and a gate before changing any feature.
  • Apply the five cost levers in order, from output limits to batching, and say what each can harm.
  • Keep or revert each step against the gate after one change and a rerun of the same cases.
  • Compute whether caching a repeated prefix pays, using write and read multipliers against the base input price.
  • Judge a result sitting near the gate by the noise in a 200-case set before approving it.

A cost line that rose last month gets a proposal on your desk: move the feature to a cheaper model. It may be a good idea. It may also be the most dangerous of the available changes, because it is the one most likely to change what users get. The engineering question is not whether any one lever works. It is which levers come first, how you will know that a step cut cost without cutting quality, and who decides when the evidence is thin.

Level 1 gave executives the principle: remove work and reshape the workflow before negotiating price, and check quality after each change. This chapter gives your team the practical sequence and the review questions for approving it.

Fix a baseline before touching anything

Every lever below changes cost, and several change outputs. You can only tell whether a change helped if you have four things written down first: the cost per request (and per finished task, including retries), a fixed evaluation set of real cases, the score on that set, and a gate, the lowest score you will accept. The evaluation set is the one built for the feature in the delivery module; do not rebuild it for the cost work, and do not tune prompts against it until it is useless.

Count tokens, do not guess them. Providers expose counts in each response and, in at least one case, a free endpoint that counts a prompt before you send it1. That documentation also warns that the same text can count about 30 percent higher on a newer model, which is one reason a change of model can move cost without any change in price per token.

The levers, in the order to apply them

The order below runs from the change least likely to alter answers to the one most likely to. It follows the usual practitioner sequence, remove work first and pay a lower rate last, and adds a quality risk rating so you can see why.

Five cost levers in order, limit output, trim prompt, route by difficulty, cache the repeated prefix and batch waiting work.Limit outputOutput costs more per tokenTrim promptRemove stale textRouteEasy requests, cheaper modelCache prefixPay once, read cheaplyBatchWaiting work at a discount
Figure 8.3.1 Five levers from least to most likely to change answers; negotiating a lower rate comes after all of them.

Here is what each one changes and what to check.

A table of five levers showing what each changes, the quality risk and what to check afterward.LeverWhat it changesQuality riskWhat to check afterOutput limitTokens the model writesTruncated or terse answersAnswers still complete; nocut-off sentencesPrompt trimTokens the model readsLost instruction or exampleScore on the fixed set, rarecases includedRoutingWhich model answersHard cases sent to a weak modelScore by difficulty class and ateach routed shareCachingPrice of the repeated prefixAlmost none; answers shouldbe identicalCache hit rate andunchanged scoreBatchingTiming and priceDelay; no change to answersWhether the user can wait thestated hours
Figure 8.3.2 What each lever alters and what to verify; the risk ratings are a planning judgment, not a measurement.

Limit the output. On the provider list used in this module, output tokens cost five times input tokens2. A feature that returns three paragraphs where a label and one sentence would do is paying a premium on every call. Set a maximum output length and ask for a defined format. The check is that answers are still complete, because a hard cap can cut a sentence in half.

Trim the prompt. Prompts grow by patching. Instructions for a bug fixed months ago stay, examples multiply, and conversation history is resent in full. Remove what the evaluation set shows you do not need, one removal at a time, and rerun the set. A prompt that drops a rare-case instruction may pass an average score and fail the cases that matter, so look at the rare cases separately.

Route by difficulty. Many requests are easy, and a smaller model can answer them at a fraction of the price. The research is encouraging and carefully bounded. FrugalGPT reported matching GPT-4 on its benchmarks with up to 98 percent lower cost in the authors’ experiments3, and RouteLLM reported cost reductions of over two times in some settings without compromising response quality4. These are research settings with defined benchmarks, not promises for your workflow. Treat routing as a hypothesis to test on your own set, and test it at several shares of traffic, as the example below does.

Cache the repeated prefix. Many requests begin with the same long instruction block. Providers let you cache that prefix, at the cost of a higher price to write it and a lower price to read it. On the provider documentation cited here, a five-minute cache write costs 1.25 times the base input price and a read costs 0.1 times on most models, 0.05 times on Opus 5.5 and Sonnet 5.5, and 0.025 times on Fable 5.1 and Mythos 5.15. The break-even is easy to compute. With a write at 1.25 and a read at 0.1 (the least favorable multiplier above), a prefix used twice within the cache lifetime costs 1.25 + 0.1 = 1.35 in base-price units against 2.0 uncached; used once, it costs 1.25 against 1.0, a loss. Caching pays when a prefix repeats within the lifetime.

Three practical caveats come from the same documentation. Each model has a minimum prefix length that can be cached, which varies from 512 to 4,096 tokens across the listed models. The default lifetime is five minutes, with a one-hour option at a higher write price. And a cache is invalidated by changes such as altered tool definitions, so a team that edits its tool list often will see a lower hit rate. Check the hit rate from the usage fields, not from the invoice.

Batch the work that can wait. The provider’s batch interface processes requests asynchronously at a 50 percent discount on input and output, and the pricing page states that such multipliers stack with others2. Backlog triage, overnight summaries and bulk classification qualify. A user-facing chat does not.

Recheck quality after every step

The discipline is a loop, and you can ask for its evidence in a design review. Make one change, rerun the fixed set, compare the score and the cost with the previous step, and keep the change only if the score stays above the gate. Reverting is a normal outcome and is a sign the gate works.

Freeze the baseline, change one thing, rerun the fixed set, then keep or revert the change according to the gate.BaselineCost, score, gateOne changeOne lever ata timeRerunSame cases,same scorerDecideKeep or revert onthe gateRecord cost and score per step in a table the team can read
Figure 8.3.3 The recheck loop for each lever; skipping the rerun is how a cost saving turns into an incident.

A small evaluation set limits what you can claim. With 200 cases and a true accuracy near 92 percent, the usual 95 percent interval is roughly plus or minus 4 points (1.96 times the square root of 0.92 times 0.08 over 200, about 3.8 points). A change of one or two cases is noise. The gate is therefore a tripwire for large drops, and the manager’s questions when a result sits near the gate are whether to enlarge the set, rerun it several times, or look at the failures by hand. The chapter on designing for variation covers repeated runs.

Two measurement habits that protect the savings

Measure cost per finished task, not per call. A change that cuts the price of each call but raises the number of retries, tool calls or human corrections can leave the finished-task cost flat or higher, and the invoice will not show you why. Log the number of model calls per completed task next to the cost, and treat a rise in that count as an early warning.

Track the savings after the change, too. Prompts regrow, traffic mixes shift and vendors revise prices and tokenizers, so the arithmetic that justified a lever last quarter may no longer hold. Put the baseline table in a place the team will see, add a row each time a lever changes, and set a recheck date for each kept change. A saving that nobody re-measures is an assumption again within a few months.

A team-sized worked example

The example reuses the ticket-triage feature from the cost model: 30,000 requests a month, 3,000 input and 400 output tokens each, on a mid-tier model at 2 per million input and 10 per million output, a baseline of 300 a month. The figures that follow were invented for this chapter and are placeholders; no team measured them, and every amount is in any currency. The evaluation set has 200 cases, the baseline scores 184 correct (92 percent), and the gate is 180 (90 percent).

An invented feature falls from 300 a month to about 69 across five kept steps and one reverted trial, with the score staying at or above 180 of 200.StepMonthly costCorrect of 200DecisionBaseline300184FreezeOutput limit, 400 to250 tokens255183KeepPrompt trim, 3,000 to2,400 tokens219182KeepRoute 60% to small modelabout 94176Revert, below gateRoute 30% to small model157181Keep, near the gateCache the 1,800-tokenfixed prefixabout 86181KeepBatch the 40% thatcan waitabout 69181Keep
Figure 8.3.4 Invented staged optimization of one feature, amounts in any currency per month, rounded to whole units; every step was rechecked on the same 200 cases.

The arithmetic, step by step. The output limit takes output from 30,000 requests of 400 tokens, or 12 million tokens at 10 per million (120), to 250 tokens each, 7.5 million tokens (75): cost 180 + 75 = 255. The prompt trim cuts input from 90 million tokens to 72 million, so input falls from 180 to 144: 144 + 75 = 219. The small model is priced at one-twentieth of the mid-tier on both input and output (0.10 against 2, and 0.50 against 10, on the provider list cited above), so routing a share s of traffic multiplies cost by 1 minus s plus s over 20. At 60 percent that factor is 0.43, giving about 94, but the score of 176 falls below the gate, so the trial is reverted. At 30 percent the factor is 0.715, giving 156.6, or 157, with a score of 181.

Caching: the fixed 1,800 tokens of each 2,400-token prompt are cached. Assume 1,000 writes and 29,000 reads a month; both counts and the prefix size are assumptions of the example, not measurements. Writes cost 1.8 million tokens at 2.50 per million (4.5). Reads cost 52.2 million tokens at 0.10 per million (5.22), because the cited price list gives Sonnet 5.5 a read price of 0.05 times base input, or 0.10; the 600 tokens of each ticket stay uncached, 18 million tokens at 2 (36). Input becomes 4.5 + 5.22 + 36 = 45.72, against 144, a factor of about 0.3175. Applied to the routed input (144 times 0.715, which is 102.96) it gives 32.69, and with the routed output of 53.6 the monthly cost is about 86. This applies the mid-tier cache factor to all routed input, a simplification: the small model has its own cache prices, so a real bill would differ somewhat. Batching moves 40 percent of requests, the overnight backlog, to half price: the factor is 1 minus 0.4 times 0.5, or 0.8, giving about 69. That flat 0.8 assumes cache hits survive batching; batched requests may not reuse a cache as often, so treat 0.8 as an optimistic bound and check the hit rate on batched traffic before counting the saving. Had the example used a Fable-class model, the read price would be 0.025 times base and the cache step would save more.

Three readings. The total saving is 231 of 300, or 77 percent, but it was bought in five kept steps. Caching was the largest single step (about 70), routing the second (62), and routing carried most of the risk. The 30 percent routing result of 181 sits only one case above the gate, and at 200 cases that margin is inside the noise, so the manager’s decision is to approve the change conditionally: enlarge the set before widening the share. And the cache saving depends on the assumption of 29,000 reads; if traffic is thin enough that a prefix rarely repeats within five minutes, the saving shrinks and a low-traffic feature could even pay more for writes.

What this means for engineering managers

Check yourself

  1. Switching a feature to the cheapest available model is the safest first cost step.
  2. Caching a repeated prompt prefix can cost more than not caching if the prefix is rarely reused.
  3. Research shows model routing cuts cost by 98 percent for any application.
  4. With 200 evaluation cases, a one-case change in score is meaningful.
  5. Reverting an optimization that drops the score below the gate is a normal outcome.

What comes next

Savings only stick if you can see which feature and which person generates the spend. The next chapter, Cost Visibility and Attribution for Teams, covers tagging usage by team, feature and environment, and a dashboard that shows cost per outcome.

References

  1. Anthropic. Token counting (Claude Platform documentation). Anthropic. 2026.
  2. Anthropic. Pricing (Claude Platform documentation). Anthropic. 2026.
  3. Lingjiao Chen, Matei Zaharia and James Zou. FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance. arXiv:2305.05176. 2023.
  4. Isaac Ong, Amjad Almahairi, Vincent Wu, Wei-Lin Chiang, Tianhao Wu, Joseph E. Gonzalez, M Waleed Kadous and Ion Stoica. RouteLLM: Learning to Route LLMs with Preference Data. arXiv:2406.18665. 2024.
  5. Anthropic. Prompt caching (Claude Platform documentation). Anthropic. 2026.

Further reading

Sources last verified 2026-10-13.