LLM API Cost Optimization: How Context Caching Cut a Customer Service System's Monthly Bill from ¥61K to ¥34K
This article breaks down how LLM API pricing actually works — input vs. output token costs, generational price drops, cache-hit rates, cache-write TTLs, and premium "high-speed" tiers — and turns those rules into concrete savings. Using an illustrative pricing table and a customer-service case study, it walks through a per-request cost formula, a break-even analysis for context caching, a reusable Python estimation script, and a practical optimization checklist. Readers will learn how to structure stable prefixes, choose the right cache TTL, control output length, and route traffic between standard and high-speed tiers to cut a monthly bill from roughly ¥61K to ¥34K.
1. Introduction: Read the Pricing Table Before You Optimize
When developers connect to an LLM service, the first thing they usually see is a pricing table. It typically lists input, output, cache-hit, and cache-write prices for different time-to-live (TTL) windows; some platforms also offer a “high-speed” tier priced at double. On the surface, these numbers are just a list of “how much per million tokens.” But once you plug in real business traffic, you find that the same application can produce monthly bills that differ several-fold depending on the calling pattern.
This article uses a published LLM pricing table from a cloud vendor as its sample (for consistency, “Standard” and “High-speed” refer to different service tiers, and “Previous Gen” refers to the older version; the prices below are illustrative only):
| Model | Input | Output | Cache hit | Cache write (5min) | Cache write (1h) |
|---|---|---|---|---|---|
| kimi-k3.1-pro | ¥13.00 / MTok | ¥68.00 / MTok | ¥1.30 / MTok | ¥13.00 / MTok | ¥26.00 / MTok |
| kimi-k3.1-pro-highspeed | ¥26.00 / MTok | ¥136.00 / MTok | ¥1.30 / MTok | ¥26.00 / MTok | ¥52.00 / MTok |
| kimi-k3 | ¥20.00 / MTok | ¥100.00 / MTok | ¥2.00 / MTok | ¥20.00 / MTok | ¥40.00 / MTok |
At first glance this table looks simple, but it contains at least five pieces of information with a major impact on cost:
- Generational price drops: The Standard input and output prices are about 35% and 32% lower than the previous generation.
- Output premium: The output price is about 5.2× the input price.
- Cache dividend: The cache-hit price is only about 1/10 of the input price.
- Writes and TTL: A 5-minute write is billed at the input price; a 1-hour write doubles that, but is still far cheaper than an uncached input.
- Speed premium: The High-speed input, output, and cache-write prices are all 2× the Standard tier; the cache-hit price is unchanged.
The rest of this article unpacks the technical and business logic behind each rule and offers practical optimization methods.
2. Fundamentals: What Is the Billing Unit for an LLM?
2.1 One token is not one character
LLMs bill by token — the smallest unit of text the model processes. Most mainstream models use BPE (Byte-Pair Encoding) and its variants for tokenization: common characters and words may be encoded as a single token, while rare characters, long words, or code snippets may be split into several. As a result, the token count for the same Chinese text can differ across models, and the “compression rate” varies by language. English and other structured text such as code often use fewer tokens, which doesn’t match the intuitive notion of “character count.”
A few rules of thumb for estimation (for capacity planning only; the platform’s metering API is authoritative):
- Chinese text: roughly “1 Chinese character ≈ 1–2 tokens”
- English text: roughly “1 word ≈ 1–1.3 tokens”
To avoid budget surprises, sample real corpus during the design phase, measure the average input and output tokens per request, then multiply by the projected request volume to get a monthly usage range.
2.2 Input, output, and “inference asymmetry”
Take the Standard tier as an example: input at ¥13/MTok, output at ¥68/MTok — about a 5.2× difference. This isn’t just commercial pricing; it is determined by the two phases of LLM inference:
- Prefill phase: The model computes all input tokens in parallel once, mainly to produce the KV Cache (the key/value tensors needed for attention). This phase is compute-intensive but highly parallel, with high GPU (graphics processing unit) utilization, so the per-token cost is relatively low.
- Decode phase: The model generates output tokens one at a time; each step reads the entire history KV Cache and is limited by memory bandwidth. As the output grows longer, the context grows and each step gets heavier. Low parallelism and the memory-bandwidth bottleneck make the per-token cost of output significantly higher than that of input.
The practical takeaway: “making the model write 500 more words” usually costs far more than “having it read 500 more words.” When designing a solution, constrain output length through prompt constraints, structured output, and word limits, rather than betting the whole budget on input-side optimization.
2.3 Structural cost reduction from generational evolution
The Standard input and output prices are about 65% and 68% of the previous generation. This reflects a common trend in the LLM industry: improvements in model capability, inference-framework optimizations (continuous batching, quantization, speculative decoding, and so on), and hardware iteration together keep driving down the per-token cost.
For developers, this means two things:
- Review bills on a schedule: Sticking with an older model version long-term can quietly leave you paying a higher unit price.
- Migration isn’t only about price: Capability fit (long context, instruction following, structured-output stability) and migration cost matter too. A sound approach is to benchmark old and new versions side by side on a test set, and prefer the better price-to-performance version once quality is assured.
3. Context Caching: The Core Lever for Cost Reduction
3.1 What is context caching (prefix reuse)?
In LLM applications, many requests share an identical opening, for example:
- System prompts (role setup, output format, safety rules);
- Relatively stable knowledge snippets such as product manuals, API docs, and code repository indexes;
- History messages that keep accumulating across a multi-turn conversation.
Without caching, this content is re-prefilled on every request, and users pay repeatedly for the same content. Context caching (called prompt caching, prefix caching, and similar names on different platforms) lets the platform store the computed KV Cache for a piece of content for a period of time; as long as the prefix of a later request matches exactly, it can be reused directly, and those tokens are billed at the “cache hit” price.
To achieve a hit, the following conditions typically apply:
- Exact prefix match: Every character, space, and punctuation mark from the start of the request through the cached content must be identical. Dynamic content such as timestamps, random IDs, and usernames placed at the beginning will invalidate the cache.
- Accessed again within the TTL: If it isn’t used before the window expires, the cache is evicted.
- Platform rules take precedence: Different platforms may set thresholds for minimum cache length, call frequency, and more; check the official documentation before integrating.
3.2 Pricing breakdown: hits, writes, and TTL
The Standard cache prices in the sample can be summarized in three points:
| Billing item | Multiple of input price | Trigger condition |
|---|---|---|
| Cache hit | ~0.1 | Request prefix hits an existing cache |
| Cache write (5min) | 1.0 | Create or refresh a 5-minute cache |
| Cache write (1h) | 2.0 | Create or refresh a 1-hour cache |
- Cache hit: Only about 1/10 of the input price — the cheapest tokens in the entire pricing system.
- Write cost is a “warm-up cost”: Only writes that are actually reused by later requests pay off.
- Longer TTL, higher write cost: A 1-hour write costs 2× a 5-minute write — you pay more per write for a longer lifetime.
- High-speed doesn’t lower the hit price: The cache-hit price is the same as Standard, meaning the cost of speed is borne mainly by the uncached portion.
3.3 Four basic rules of cache hits
- Rule 1: A write is not a hit. If a prefix is unique and requested only once (for example, a one-off long-document summary), the write only adds cost and yields no savings.
- Rule 2: The hit rate depends on “request similarity,” not “request count.” 100 completely different requests each writing their own cache yield zero benefit; 100 requests sharing the same system prompt can achieve a high hit rate as long as the prefix is stable.
- Rule 3: The TTL should match the “reuse interval,” not the “business duration.” 5 minutes suits second-level, high-frequency interactions; 1 hour suits longer sessions or batch tasks concentrated during morning/evening peaks. Too long a TTL drives up write cost; too short, and the cache may expire before reuse.
- Rule 4: The longer the prefix, the larger the absolute savings per hit — but the higher the first-write cost. A break-even analysis is needed to decide (see Section 4).
4. Cost Modeling: From a Single Request to the Monthly Bill
4.1 The per-request cost formula
For any single request, its tokens can be split into five categories: uncached input, output, cache-hit read (cache_read), 5-minute cache write (cache_write_5m), and 1-hour cache write (cache_write_1h). Then:
Cost = (input × P_in + output × P_out+ cache_read × P_hit+ cache_write_5m × P_w5+ cache_write_1h × P_w60) / 1,000,000
where Pi is the “yuan/MTok” price of each billing item.
4.2 The break-even condition for a caching strategy
Take a complete task unit (such as one round of a customer-service session or one coding task) as an example. Suppose:
- There is a cacheable segment of length L;
- One cache write occurs, with H reuse requests within the TTL;
- The cache hit ratio is r (i.e., of the H reuse requests, H×r hit).
Define the price coefficient per input token:
- k_in = P_in / P_in = 1
- k_hit = P_hit / P_in ≈ 0.1
- k_w60 = P_w60 / P_in = 2 (1-hour write)
- k_w5 = P_w5 / P_in = 1 (5-minute write)
The input-side cost coefficients of the two schemes for this segment are:
No-cache scheme: k_base = (H + 1) × k_in = H + 1Cache scheme: k_cache = k_w× + (H + 1 − H×r) × k_in + H×r × k_hit
Expanding, the difference between the two is:
k_base − k_cache = H×r×(k_in − k_hit) − k_w×= H×r×0.9 − k_w× (Standard tier, approximate)
From this we can see:
- Cache savings come only from the “number of hits”, i.e., “reuse count × hit ratio”;
- Write cost depends only on the number of writes and the TTL tier, not on how many hits occur;
- As long as “hit count × per-hit savings” exceeds the write cost, using the cache pays off.
A few corollaries:
- When r = 0, the cache only adds cost — avoid caching one-off content.
- With a 5-minute TTL, k_w5 = 1: as long as there is at least 1 hit, the write cost is fully recovered.
- With a 1-hour TTL, k_w60 = 2: by the approximate formula, at least 3 hits are needed to break even (0.9×3 = 2.7 > 2); with exact calculation, since the first request may also hit, in practice about 2–3 hits are needed. So a 1-hour cache suits multi-turn interactions within a session, or scenarios with sustained calls over a period.
- In high-frequency, stable scenarios, cache savings scale linearly: the more hits, the more substantial the savings.
4.3 An example estimation script
Below is a reusable estimation script (illustrative). It decouples price configuration from the calling pattern: switching service tiers only requires changing the config, and evaluating new pricing or new versions can reuse it directly.
from dataclasses import dataclass@dataclass(frozen=True)class PriceConfig:"""Service tier price config (unit: yuan / million tokens)"""input: float # Uncached input price per tokenoutput: float # Output price per tokencache_hit: float # Cache hit price per tokencache_write_5m: float # 5-minute cache write price per tokencache_write_1h: float # 1-hour cache write price per token# Illustrative prices, only to demonstrate the calculation methodSTANDARD = PriceConfig(13.0, 68.0, 1.3, 13.0, 26.0)HIGHSPEED = PriceConfig(26.0, 136.0, 1.3, 26.0, 52.0)PREV_GEN = PriceConfig(20.0, 100.0, 2.0, 20.0, 40.0)TOKENS_PER_M = 1_000_000def estimate_monthly_cost(requests_per_day: int, # Average requests per daydays: int, # Number of daysinput_tokens: int, # Uncached input tokens per requestoutput_tokens: int, # Output tokens per requestcacheable_tokens: int, # Cacheable prefix length per requestcache_hit_ratio: float, # Cache hit ratio, in [0, 1]requests_per_session: int, # Average requests per task unit (session)ttl_hours: float, # Cache TTL (hours): pass 1/12 for 5min, 1 for 1hprice: PriceConfig = STANDARD,) -> dict:total_requests = requests_per_day * days# Estimate: total times the prefix enters the context = requests + cache writesprefix_slots = total_requests + total_requests / requests_per_sessioncache_hit_tokens = cacheable_tokens * cache_hit_ratio * prefix_slotsuncached_input_tokens = (input_tokens - cacheable_tokens + cache_hit_tokens) * total_requestsoutput_tokens_total = output_tokens * total_requests# Write cost is interpolated linearly between the 5min and 1h tiers by TTL overlap ratiottl_weight = min(max(ttl_hours * 12, 0.0), 1.0)cache_write_price = price.cache_write_5m * (1 - ttl_weight) + price.cache_write_1h * ttl_weightcache_write_tokens = cacheable_tokens * total_requests / requests_per_sessioncost = (uncached_input_tokens * price.input+ output_tokens_total * price.output+ cache_hit_tokens * price.cache_hit+ cache_write_tokens * cache_write_price) / TOKENS_PER_Mreturn {"total_cost": round(cost, 2),"input_cost": round(uncached_input_tokens * price.input / TOKENS_PER_M, 2),"output_cost": round(output_tokens_total * price.output / TOKENS_PER_M, 2),"cache_read_cost": round(cache_hit_tokens * price.cache_hit / TOKENS_PER_M, 2),"cache_write_cost": round(cache_write_tokens * cache_write_price / TOKENS_PER_M, 2),}if __name__ == "__main__":print("Customer service scenario:")for name, cfg in [("Standard", STANDARD), ("Highspeed", HIGHSPEED), ("Previous Gen", PREV_GEN)]:# 40K daily requests, system prompt + knowledge base ~1500 tokens,# other input ~1000 tokens, output ~300 tokensresult = estimate_monthly_cost(requests_per_day=40_000, days=30,input_tokens=2_500, output_tokens=300,cacheable_tokens=1_500, cache_hit_ratio=0.9,requests_per_session=8, ttl_hours=1, price=cfg,)print(f"{name}: monthly cost {result['total_cost']} yuan, breakdown {result}")print("\nCache savings vs. hit ratio (Standard, 1M monthly requests):")for ratio in [0.0, 0.3, 0.6, 0.9]:result = estimate_monthly_cost(requests_per_day=100_000 / 3, days=30,input_tokens=2_500, output_tokens=300,cacheable_tokens=1_500, cache_hit_ratio=ratio,requests_per_session=8, ttl_hours=1,)print(f"Hit ratio {ratio:.0%} -> monthly cost {result['total_cost']} yuan")
The script embodies three modeling principles:
- Separate price from usage: Price configuration is centrally managed, making it easy to compare costs across versions or tiers.
- Distinguish writes from hits: Cache writes are estimated by “number of task units,” while hit volume is estimated by “request count × hit ratio.”
- Support sensitivity analysis: By iterating over hit ratio, TTL, and service tier, you can find the most cost-sensitive variables.
5. A Practical Case: Where Do the Cost Differences Come From?
Using the customer-service scenario again: assume 40,000 requests/day over 30 days, 2,500 input tokens per request (of which 1,500 tokens are the system prompt and knowledge-base snippets), 300 output tokens, an average of 8 turns per session, a 1-hour cache on the knowledge-base prefix, and a hit ratio of about 90%. Running the script above yields:
| Configuration | Monthly cost (illustrative) | vs. baseline |
|---|---|---|
| Standard + no cache | ~¥61K | Baseline |
| Standard + cache hit | ~¥34K | About 45% lower |
| Highspeed + cache hit | ~¥69K | About 13% higher |
These numbers offer two insights:
- In this scenario, the savings from caching far exceed the extra cost of High-speed. The High-speed premium shows up mainly in uncached input and output; at the same time, cache hits can significantly reduce the prefill-driven time to first token (TTFT). If the hit ratio is high enough, Standard combined with sensible prefix design and queuing can already meet the needs of most online workloads.
- What truly needs High-speed is “output-heavy + latency-sensitive” interaction. In scenarios such as real-time voice dialogue and code completion, the extra cost of 2× output pricing often dominates, and you must weigh it against the experience benefit to decide whether it is worth it.
Note: The results above are computed from illustrative prices and assumed usage, and are only meant to demonstrate the analysis method — they do not represent the actual cost of any service.
6. A Cost Optimization Checklist: Minimize “Paying Twice”
6.1 Structure your prefix: put stable content up front
Principle: the more stable the content, the earlier it goes; the more dynamic, the later.
Recommended message order: platform-level instructions → fixed system prompt → stable knowledge/document content → conversation history → current user input. Note in particular that if a platform concatenates “system prompt + history + current input,” growth in history keeps changing the token sequence before the current input. If the current input itself forms the cache prefix, the later the turn, the further back its position and the harder it is to hit; whereas relatively stable history in earlier turns is easier to cache.
Illustrative counter-example (different every request, so the prefix can’t be reused):
# Counter-example: a timestamp and random request ID at the start make the prefix change every timemessages = [{"role": "system", "content": f"Current time: {now()}; request ID: {uuid4()}"},{"role": "system", "content": SYSTEM_PROMPT}, # Stable content gets "pushed" to the back]
Illustrative good example (stable content up front):
import timeSYSTEM_PROMPT = "You are an enterprise internal knowledge base assistant. Cite sources in your answers, and clearly tell the user when you are unsure."def build_messages(history, user_input):messages = [{"role": "system", "content": SYSTEM_PROMPT}, # Stable prefix]if knowledge_base:messages.append({"role": "system", "content": knowledge_base})messages.extend(history) # History messages# Place dynamic info like the current time close to the user inputmessages.append({"role": "system", "content": f"[Current time: {time.strftime('%Y-%m-%d %H:%M')}]"})messages.append({"role": "user", "content": user_input}) # Dynamic inputreturn messages
6.2 Compress cacheable content: a leaner prefix makes each hit worth more
Since the hit price is only about 1/10 of the input price, every 1,000 tokens removed from the cacheable prefix saves a considerable absolute amount across many requests. Specific approaches:
- Segment and reorder the knowledge base: Sort by retrieval hit rate, put the most-used snippets first, and control each segment’s length;
- Trim the prompt: Remove redundant examples and repeated phrasing;
- Structured output: Use a concise schema (a data-structure description) instead of lengthy natural-language format instructions.
6.3 Control system-prompt “drift”
System prompts are repeatedly modified during version iteration, and a common problem is that each change invalidates the cache until all requests re-warm up. It is advisable to put the system prompt under version control (such as Git), include prompt changes and cache invalidation in the release review, and watch the hit-ratio trend after release.
6.4 Choose a sensible TTL and caching strategy
- Interactive sessions: Give each session a stable session identifier and share one cache within the session; choose a 5-minute or 1-hour TTL depending on the user’s average thinking interval;
- Batch offline tasks: Group and schedule tasks that share the same prefix so the cache is reused quickly after being written — avoid “write once, sit cold all day”;
- One-off tasks: Turn off caching proactively, or use a lean input with no cacheable prefix, to avoid paying for writes with no return.
6.5 Fine-grained output control
Since the output price is about 5× the input price, controlling output length is one of the most direct cost levers:
- Explicitly ask the model to “lead with the conclusion and expand only as needed”;
- For summarization, classification, and extraction tasks, use structured output formats to cut small talk and explanatory text;
- Process long-text generation in segments to avoid producing overly long content in a single pass.
6.6 Build usage observability
Before optimizing, you need visibility. It is advisable to record the following metrics uniformly at the gateway or application layer:
- Per-request token usage: including uncached input, output, cache-hit, and cache-write token counts;
- Cache hit ratio: broken down by business line, model version, prefix type, and so on;
- Cost allocation: split by application, tenant, and environment;
- SLO metrics: TTFT, output tokens per second (throughput), and P95/P99 latency.
With this data, teams can answer key questions like “where is the money going,” “which requests are most worth optimizing,” and “is scaling out necessary.”
7. Selection Guidance: How to Pair Standard and High-speed
| Scenario | Recommended tier | Key considerations |
|---|---|---|
| Offline batch (document summarization, data labeling) | Standard | Controllable throughput and queuing; cost first |
| Enterprise internal knowledge base Q&A | Standard + cache | Stable prefix, high hit rate, significantly lower TTFT |
| Standard customer service | Standard + cache | High intra-session reuse, stable returns |
| Real-time voice dialogue | High-speed | Output-heavy, sensitive to end-to-end latency |
| Code completion / AI-assisted coding | High-speed (or tiered) | Frequent interaction, many output tokens; latency directly affects experience |
| High-frequency short input (classification, extraction) | Standard | Short input, limited hits; focus on controlling per-call cost |
In practice, a dynamic routing strategy is recommended: the gateway distributes requests to different tiers based on task type, SLO level, and real-time load, and uses rate limiting and degradation to protect high-priority traffic. This avoids the waste of a one-size-fits-all approach while reserving compute for critical workloads during peaks.
8. Summary
Around a seemingly simple model pricing table, this article has laid out seven rules with a far-reaching impact on cost:
- Output is far more expensive than input: Controlling output length is the most direct cost-cutting measure;
- Generational price drops are the norm: Periodically evaluate a new version’s price-to-performance, but don’t follow blindly;
- The cache-hit price is about 1/10 of the input price: Prefix reuse is the most effective lever for long-text and multi-turn scenarios;
- Cache writes are a “warm-up cost”: Writes should happen only on content that will be reused;
- Longer TTL means higher write cost: 5 minutes suits high-frequency short intervals; 1 hour suits session-based or centrally scheduled tasks;
- High-speed costs 2× Standard: Choose based on latency SLOs, not the “faster is better” intuition;
- Cost can be modeled and measured: Only by separating price from usage can you quickly answer “how much will this cost in a month.”
In real engineering, teams are advised to make “compress first, then cache, then select by scenario” the default cost workflow: first shrink the cacheable volume through prefix structuring and content trimming, then raise the hit ratio with a sound caching strategy, and finally choose the appropriate service tier based on business SLOs. Combined with solid usage observability, every dollar of an LLM application’s cost can be quantified, attributed, and optimized.
Whichever cloud vendor’s LLM service you use, the methodology above applies equally: understanding the billing model, mastering the caching mechanism, and making data-driven decisions is the fundamental way to control cost.
