Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

An AI feature's monthly cost is ten times the estimate. How would you reduce cost without hurting quality badly?

First we measure where the tokens go, per request and per part of the prompt, because the bill is almost always dominated by one or two contributors such as a long system prompt, too much retrieved context or an ever-growing chat history. Then we cut those: fewer and better chunks, a window or summary for memory, a smaller model for the easy steps, provider prompt caching for the repeated prefix, and an answer cache for repeated questions. Each change is checked against an evaluation set so quality does not quietly drop.

Why this question is asked

AI features are priced per token, so cost grows with every word we send and every word the model writes back. A feature that looked cheap in a demo with three short questions can become expensive in production when real users bring long conversations and the retrieval step pulls in ten pages of context. Interviewers ask this question to see whether we diagnose before we cut, and whether we know the levers that save money without making answers worse. In this answer, we will see how to measure where the tokens go, then go through the four big levers: less context, smaller models for easy work, prompt caching and answer caching, and finally how to prove quality held.

1A Quick Recap of How an AI Call Is Billed

Every call to a hosted model is billed in tokens. A token is a piece of a word, roughly four characters of English text, so 1,000 tokens is about 750 words. Providers charge separately for input tokens (everything we send: system prompt, chat history, retrieved documents, the user's question) and output tokens (what the model writes). Output tokens usually cost three to five times more per token than input tokens, but input is often far larger in volume.

So the cost of one request is roughly input tokens times the input price plus output tokens times the output price, and the monthly bill is that times the number of requests. If the bill is ten times the estimate, one of three things is ten times bigger than we planned: tokens per request, the price per token (a bigger model than planned), or the number of requests (retries, loops, or more traffic). Measuring tells us which one.

2Measure Tokens Per Request and Per Part

Spring AI returns token usage on every response, so we can record it with Micrometer and tag it by feature and model. That gives the total, but to find the culprit we also need to know how the input is made up. A simple way is to count the tokens of each part when we build the prompt and log them together.

Java
ChatResponse response = chatClient.prompt()
.system(systemPrompt)
.user(question)
.call()
.chatResponse();
Usage usage = response.getMetadata().getUsage();
log.info("prompt={} completion={}", usage.getPromptTokens(), usage.getCompletionTokens());
// prompt=9120 completion=310
// Breakdown we logged while building the prompt for the same request:
// system prompt 1800 tokens
// retrieved chunks 5600 tokens (8 chunks of about 700)
// chat history 1600 tokens (last 30 messages)
// user question 120 tokens
Where 9,120 input tokens came from
Part of the promptTokensLever
Retrieved chunks5,600fewer, better chunks; a reranker
System prompt1,800shorten it; provider prompt caching
Chat history1,600message window or summary
User question120nothing to cut
The question is the smallest part. The context around it is where the money goes.

Notice what this one request tells us. The question itself is 120 tokens out of 9,120, and the answer is only 310. More than 60 percent of the input is retrieved context, and the system prompt is sent unchanged on every call. Once we see numbers like these across a few thousand requests, the plan writes itself: we work on the biggest part first. We also check the request count, because a retry loop or a client that calls twice per page view can multiply the bill without any change in tokens.

3Lever 1: Send Less Context

Retrieval usually sends too much because topK was set high in development to be safe. If we retrieve eight chunks but the answer almost always comes from the first two, we pay for six chunks of noise, and that noise can even make answers worse. We lower topK, add a similarity threshold so weak matches are dropped, and, if quality needs it, retrieve twenty candidates and let a cheap reranker keep the best three. Smaller, cleaner chunks also help: a 300-token chunk that holds one idea beats a 1,000-token chunk that holds five.

Chat memory is the second source. A window of the last 30 messages grows to thousands of tokens in a long session. A window of 10 messages, or a short running summary of older turns plus the last few messages verbatim, keeps the context the model needs at a fraction of the size. The system prompt is the third: many system prompts collect instructions over months, and a review often removes a third of them without any change in behaviour.

4Lever 2: Use a Smaller Model for Simple Steps

Not every step needs the strongest model. Classifying the intent of a message, extracting a date or rewriting a query for search can be done by a small model that costs ten to twenty times less per token. We route by task: the small model handles the easy steps, and only the final answer for hard questions goes to the large model. A common pattern is to let the small model answer first and escalate when it reports low confidence or when the question matches categories we know are hard.

Java
String intent = smallClient.prompt().user(question).call().content(); // "billing" (cheap call)
ChatClient answerer = HARD_INTENTS.contains(intent) ? largeClient : smallClient;
String answer = answerer.prompt().user(question).call().content();
meterRegistry.counter("ai.route", "model", answerer == largeClient ? "large" : "small").increment();

The counter matters: if the router sends 90 percent of traffic to the large model, we have saved nothing, and we only learn that from the metric.

5Lever 3 and 4: Prompt Caching and Answer Caching

Prompt caching is a provider feature. When many requests start with the same long prefix, such as the same system prompt and tool definitions, the provider can keep that prefix processed and charge much less for it on later calls, often a tenth of the normal input price. Some providers do it automatically above a minimum length, others need us to mark the cacheable part; Spring AI exposes this in the provider options for some models, so check your provider and Spring AI version. The rule that makes it work is to put the stable text first and the changing text (history, retrieved chunks, question) last.

Answer caching is ours. Support assistants see the same questions again and again: how do I reset my password, what are your opening hours. We can store the final answer keyed by a normalised question, or by an embedding with a high similarity threshold, and return it without calling the model at all. We give cached answers a short lifetime and clear them when the source documents change, so we do not serve outdated answers.

Step throughOrder of work when the bill is too high
  1. Measure tokens and callsper feature, model and prompt part
  2. Fix runaway callsretries, loops, duplicate requests
  3. Cut the biggest prompt partchunks, memory or system prompt
  4. Route easy steps to a small model
  5. Turn on prompt cachingstable prefix first
  6. Cache repeated answers
  7. Did the evaluation score hold?
    YesShip and keep watchingNoUndo the last change

7 steps in order. Play them, or step through them one at a time.

6Keeping Quality While Cutting

Every lever can hurt quality if we push it too far, so we measure before and after. We keep an evaluation set of a few hundred real questions with expected answers or a grading rubric, and we run it after each change. If cutting topK from eight to three keeps the score within a point, we keep it; if routing to the small model drops the score on billing questions, we send billing questions to the large model.

7Follow-up questions

Which lever would you try first?

Measurement first, then whichever part of the prompt is largest. In most systems that is retrieved context or chat history, and reducing them is cheap to try and easy to undo. Model routing takes more work because it needs an evaluation per task, so it comes after.

How do you stop one bug from creating a huge bill again?

Set budgets with alerts per feature, cap retries and tool-calling loops, and rate-limit per user. A daily cost alert would have caught a ten-times overrun in the first day instead of at the end of the month.

Does a smaller model always mean lower quality?

No. For narrow tasks such as classification or extraction, a small model often scores the same as a large one on our own evaluation set. The only way to know is to test the specific task, not to rely on general benchmarks.

8Conclusion

In this answer, we saw that cost follows tokens, so we first measure tokens per request and split them into system prompt, retrieved context, memory and question. Then we cut the largest parts, route simple steps to cheaper models, use provider prompt caching for the stable prefix, and cache answers to repeated questions. An evaluation set run after each change keeps quality from slipping while the bill comes down.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start by measuring, not cutting. I would record prompt and completion tokens for every call with Micrometer, tagged by feature and model, and log how the input splits between system prompt, retrieved chunks, chat history and the question.

Then, if they want more

I would also check the call count, because retries or duplicate calls can multiply the bill. Usually one part dominates. If retrieval sends eight chunks and the answer comes from two, I lower topK, add a similarity threshold, maybe a reranker, and use smaller chunks. For memory I use a message window or a summary of older turns.

Then I route simple steps like intent classification or query rewriting to a small model and keep the large model for hard answers, and I count how traffic splits. Where the provider supports it, I turn on prompt caching and make sure the stable prefix comes first. For support-style features I cache answers to repeated questions with a short lifetime.

After each change I run our evaluation set, so I can show the cost went down and the quality score stayed within a point or two. Finally I add budget alerts so an overrun shows up in a day, not a month.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring AI reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An AI feature's monthly cost is ten times the estimate. How would you reduce cost...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/66024af29e/