Prompt Caching and Token Budgets
메뉴

AI Backend

Prompt Caching and Token Budgets

Cost and latency controls for prompts that grow with product complexity.

Prompt Caching and Token Budgets hero image

Operational strategies to reduce costs and delays

In this article, we summarize how to manage the cost and delay of LLM services as operational indicators using prompt caching and token budget.

LLM costs are not fixed like server CPU costs. Each request depends on the input token, output token, model, and whether or not it is cached. The same goes for response delays. Even within the same API, the length of the prompt and the number of documents retrieved can vary greatly.

Therefore, in LLM services, “how to manage prompts as an operable cost unit” is more important than “how to write prompts well.”

Analysis date: 2026-05-12 Practice environment: OpenAI API, FastAPI, Redis, Prometheus Main reference materials: OpenAI prompt caching Docs, OpenAI Rate Limits Docs, OpenAI Cookbook

Key takeaways

  • token budget is the input/output token limit allowed for one request.
  • prompt caching helps reduce the cost and delay of repeated prompt prefixes.
  • Placing static content at the front of the prompt and dynamic content at the back is advantageous for cache efficiency.
  • Cost optimization should be based on usage metrics, not intuition.
  • Cost and quality for each prompt version must be looked at together.

1. Why LLM costs are difficult to predict

For regular APIs, the cost can be somewhat estimated by looking at the number of requests and server resources. But with LLM, the length of the request creates a cost.

elementcost impact
system prompt lengthRecurring costs for every request
Number of documents retrievedIncrease RAG input token
conversation historyIncrease context length
output lengthIncreased output token cost
retrySame costs occur repeatedly
Cache or not?Input processing cost/delay can be reduced

Therefore, token usage should be viewed as an API metric.

2. What is token budget?

token budget is the token budget to allow for one request.

# This is an example.Total budget = system prompt + tool schema + retrieved context + user question + output reserve

example:

areabudget
system prompt1,000 tokens
tool/schema instruction800 tokens
retrieved context4,000 tokens
conversation history1,000 tokens
user question300 tokens
output reserve1,200 tokens

If you exceed your budget, you may need to reduce the number of search documents, summarize old conversation history, or limit output max tokens.

3. prompt caching basic concept

prompt caching is a method in which the provider reuses repeated prompt prefixes to reduce delays and costs.

What is important in practice is that “repeated parts should be at the front.”

# This is an example.Good structure:[fixed system prompt][Fixed tool schema][Fixed response rules][Dynamic Search Document][Dynamic User Questions] Bad structure:[User Question][Search Document][fixed system prompt][tool schema]

Cache prefix reuse may be less effective if the fix content is located later.

4. Cache-friendly Prompt Layout

The recommended layout is as follows.

# This is an example.System:- Role- Reply Policy- citation rules- Prohibitions- Schema description Developer:- Tool use rules- Output validation criteria Context:- retrieved chunks User:- question

Policies that do not change are placed first, and documents and questions that change with each request are placed last.

5. Divide token budget in RAG

For RAG, token budget management is especially important. Entering more search results does not always result in better answers. Rather, if the number of unrelated chunks increases, the model may become confused.

strategyexplanation
Top-k limitsLimit the number of search results
Chunk compressionSummarize long chunks and then enter them
metadata filterReduce candidates by permissions, document type, and date
rerankingLeave only highly relevant documents
Output reserveSecure token space required for response

6. Cost/delay indicator design

Be sure to leave metrics:

# This is an example.llm_input_tokens_totalllm_output_tokens_totalllm_cached_input_tokens_totalllm_cost_estimated_totalllm_latency_ms_bucketllm_prompt_version_usage_totalllm_rate_limit_error_totalllm_retry_total

Analysis criteria:

questionball indicators
Which prompt version is more expensive?Token usage by version
Is Cache Effective?cached token ratio
Where does the delay come from?latency p95/p99
Are retries expensive?retry count, retry token

7. Rate Limit and Backoff

Rate limits are not a problem that can be solved by simply using a higher rate plan. Combining burst traffic, retry storms, and bulk eval executions can lead to throttling.

Response principles:

# This is an example.[ ] Request unit rate limit[ ] User/Organizational Unit Quota[ ] eval batch separate restrictions[ ] exponential backoff[ ] retry budget[ ] provider fallback

8. Practical example

Budget check before calling prompt:

# This is example code.def enforce_token_budget(parts: dict, max_input_tokens: int):    estimated = sum(estimate_tokens(value) for value in parts.values())    if estimated <= max_input_tokens:        return parts     parts["retrieved_context"] = trim_context(parts["retrieved_context"])    estimated = sum(estimate_tokens(value) for value in parts.values())     if estimated > max_input_tokens:        raise ValueError("TOKEN_BUDGET_EXCEEDED")     return parts

In actual services, tokenizer-based estimation and provider usage results must be recorded together.

9. Practical checklist

# This is an example.[ ] Have you set an input/output token budget per request?[ ] Do you record token usage by prompt version?[ ] Did you place the static prompt prefix in front?[ ] Are the RAG context top-k and maximum tokens limited?[ ] Have you secured the output reserve?[ ] Do you measure the cached input token ratio?[ ] Are rate limit errors and retry costs recorded?[ ] Have you separated quotas for eval execution and user traffic?

Failure case: Cache is turned on but costs are not reduced

There are cases where prompt caching is applied but costs and delays are hardly reduced. This is usually because the repeated prefix is ​​short, the beginning of the system prompt changes for each request, or the search document is inserted into the beginning of the prompt. Even if the provider supports cache, the effect will be small if the prompt layout does not fit the cache.

Another failure is to only look at the average token. LLM fees vary greatly with p95 and p99 requests. Most requests are short, but if some requests include 20 long documents and generate long responses, the monthly cost estimate will be wrong. The token budget is not an average optimization, but rather an operational policy that sets per-request upper limits and exception handling.

Implementation example: Dividing the prompt layout into cache-friendly

[stable prefix]- product role- response policy- tool contract- safety and citation rules [semi-stable]- tenant policy version- prompt template version [dynamic suffix]- user question- retrieved chunks- conversation summary

Put static policies at the front, and questions and search results at the back. When the template version changes, the decrease in cache hits is considered a normal event and recorded in the metrics. If the dynamic suffix exceeds the budget, the retrieval top-k should be reduced or replaced with a summary context.

Checklist application results

characteristicReason for collectionCorrespondence example
input tokensBase unit of request costLimit number of retrieval chunks
cached input tokensCheck caching effectstable prefix relocation
output tokensManage answer length and costAdjust answer policy and max token
prompt versionComparison before and after changesregression eval connection
p95 latencyLong request detectionTimeout and fallback design

Having this metric allows you to say the cause, not like "the prompts are long and that's expensive", but something like "the cached input rate dropped in version 7 and the retrieval suffix pushed up p95". Cost optimization is more about measurable budget management than it is about statement sense.

Example of failure response: Budget exceeded for long document question

Let's say a user uploads an 80-page policy document and asks, "Summary everything and find exceptions." A good backend doesn't immediately put the entire document into the prompt. First, create a budget plan by looking at the document length, number of chunks, and question types.

Choicemeritdanger
Enter the entire documentSimple implementationCost surge, context exceeded
Enter only top-k chunkcost controlPossible omission of important provisions
map-reduce summaryCapable of processing long documentsStep by step increase in delay
retrieval after rewriting the questionImproved relevancerewrite quality depend

In operations, budgets are set differently for each question type. For simple definition questions, keep top-k small and output reserve small. Comparative analysis or exception clause exploration broadens the retrieval candidates, but creates intermediate summaries and includes only source chunks in the final answer. In this case, prompt caching is helpful for fixed policies and schemas, but may not have much effect on the upload document itself.

A borderline case is a retry storm. When a rate limit error occurs, retrying the same long prompt multiple times increases both cost and delay. You should set a separate retry budget, and if it exceeds the budget, you should inform the user that “the documents will be processed separately” or “a narrower question is needed.” token budget is not a simple optimization, but a device that turns failure into a product experience.

10. Q&A

Q1. Does prompt caching alone solve the cost problem?

no. prompt caching is advantageous for repetitive prefixes. Areas that change every time, such as RAG context or user questions, require improvement in token budget and retrieval quality.

Q2. Is it okay to use the system prompt for a long time?

If it is repeated and cached well, the cost burden can be reduced. However, long system prompts create maintenance and quality regression risks, so versioning and eval are necessary.

Q3. Are output tokens also cached?

prompt caching is primarily concerned with input prefix reuse. The output length must be managed separately with max token and response policy.

11. References and uncertainty

References

uncertainty

  • Cache application terms, support models, and pricing may vary from time to time.
  • Token estimation may differ from actual provider usage.

댓글

GitHub 계정으로 로그인하면 댓글을 남길 수 있습니다. 댓글은 GitHub Discussions를 통해 운영됩니다.

TOP