🚀 One API for every frontier model on FastInfra

Browse models

Transparent per-token pricing → compare providers on FastInfra

View pricing

OpenAI-compatible chat completions → start in minutes

Read the docs

⚡ Server Auction → Enterprise bare metal from $78.15/mo (173 in stock)

Browse deals

Prompt Caching to Cut LLM API Cost

Prompt caching stores the Key-Value (KV) cache for repeated context, allowing models to skip recomputation. When a request shares a prefix with a cached entry, you get a cache hit and pay significantly less for input tokens. This guide explains how to structure your system prompt and conversation history to maximize cache hits and reduce inference costs on OpenAI-compatible APIs.

How KV Cache Works for Cost Reduction

Large language models process text sequentially, computing attention scores for every token in a sequence. Without caching, the model recomputes these scores for every new token generated, creating redundant work. The Key-Value (KV) cache stores the attention vectors for previously processed tokens, allowing the model to skip recomputation for unchanged input.

When you send a request with a long system prompt or conversation history, the model loads the KV cache from previous turns. It only computes new attention weights for the newly added tokens. This reduces the computational load from processing the entire context window to processing only the delta.

Cost savings come directly from reduced compute time. Input tokens that hit the cache require fewer GPU cycles than tokens that trigger a full recomputation. Since API pricing is tied to compute resources, caching lowers the effective cost per input token.

  • The model processes the initial prompt and stores the resulting key and value vectors.
  • On subsequent requests, the system checks if the input prefix matches a cached entry.
  • If a match is found, the model loads the cached vectors instead of recalculating them.
  • Only the new tokens are processed, and their vectors are appended to the cache.

This mechanism is most effective when the prefix of your request remains static across multiple calls. For example, a system prompt that defines the model's behavior does not change between user queries. By caching this static portion, you avoid paying for its recomputation on every turn.

FastInfra supports prompt caching across its OpenAI-compatible API. You can view supported models and pricing details on the models page. The platform automatically handles cache storage and retrieval, so you do not need to manage cache keys manually.

curl https://api.fastinfra.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "llama-3.1-70b-instruct",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is the capital of France?"}
    ]
  }'

Structuring Requests for Maximum Cache Hits

LLM providers charge for input tokens, but cached tokens are often free or heavily discounted. The cache only works when the prefix of your new request matches the prefix of a previous request exactly. Any deviation in whitespace, punctuation, or order invalidates the cache.

Structure your API payload to keep static content at the beginning. Place system prompts, instructions, and long context documents before the dynamic user query. This ensures the expensive static portion remains stable across multiple turns or requests.

  • Define the system prompt once and keep it identical in every request.
  • Append retrieved context or reference data immediately after the system prompt.
  • Place the variable user message at the very end of the array.

When the user asks a follow-up question, resend the entire history. The provider compares the new message list against the previous one. If the first N messages are identical, those tokens are served from the KV cache instead of being recomputed.

{
  "model": "llama-3.1-70b",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Here is the document: [LONG TEXT]"},
    {"role": "assistant", "content": "I have read the document."},
    {"role": "user", "content": "What is the main conclusion?"}
  ]
}

In this example, the system prompt and the long document are cached after the first turn. The second turn reuses that prefix. Only the new assistant response and the final user question require fresh computation. Check the response headers for cache usage metrics to verify hits. See the API documentation for specific header fields.

Avoid injecting timestamps, random IDs, or dynamic variables into the static prefix. Even a single character change at the start of the message array forces a full recomputation. Consistency is the only requirement for cost reduction.

The Cost Impact of Cache Misses

A cache miss forces the inference engine to process the entire prompt sequence from scratch. This means paying the full input token price for every request, regardless of how much context repeats across calls. For high-volume applications, this difference between a hit and a miss defines the baseline margin.

Consider a standard RAG workload where the system prompt and retrieved documents remain static while only the user query changes. Without caching, the server recomputes the key-value states for the static context on every inference. With caching, the engine reuses the existing states and only computes the new query tokens. The cost delta scales linearly with the length of the static context.

Cost comparison per 1,000 input tokens
Scenario Cost Factor Relative Expense
Full Computation (Miss) 100% Baseline
Cache Hit (Reuse) ~10-20% Significant Reduction

The median input price for chat models on the platform is 0.2794. When you multiply this rate by large context windows, the savings from avoiding redundant computation become immediate. A single cache miss on a 100k-token context window costs ten times more than the same request if the context is cached.

Output tokens are generally priced higher than input tokens, with a typical 3.3. However, caching primarily impacts the input side. If your application generates long outputs, the input cost savings from caching still represent a substantial portion of the total bill, especially when the input context is large.

To maximize efficiency, ensure your API integration preserves the exact string format of the system prompt and history. Minor variations in whitespace or formatting can invalidate the cache key, triggering a full recomputation. Review the caching implementation details in the API documentation to ensure your request structure aligns with the cache key generation logic.

Choosing Models That Support Caching

Not every model on the platform implements key-value (KV) caching. The capability depends on the underlying inference engine and the model architecture. If you route traffic to a model that does not support caching, the system must recompute the entire prefix for every request, negating any potential cost savings. Before optimizing your prompt structure, verify that your target model actually supports this feature. FastInfra maintains a catalog of 722 models, but only a subset exposes KV cache functionality via the API. Using an unsupported model means you pay full input token prices regardless of how static your context is. Check the model details page to confirm caching support. Look for explicit documentation or metadata flags indicating KV cache availability. If the documentation is silent, assume caching is disabled. This verification step prevents wasted engineering effort on optimization strategies that the model cannot utilize. You can filter the available models by feature support in the catalog. Use the model browser to identify which architectures provide this optimization. Common large language models often support it, but smaller or specialized models may not. When building your routing logic, prioritize models with confirmed caching support for high-volume, repetitive tasks. This ensures that your cost reduction strategy relies on a stable technical foundation rather than assumptions about model behavior. { "model": "supported-model-v1", "prompt": "System: ... User: ..." } Ensure your API client sends the full context in a single request. Splitting the context across multiple calls without proper caching support will result in redundant computation. Always validate the model's capabilities before deploying caching-dependent workflows to production.

Cheapest Models for High-Volume Caching

Caching delivers the highest absolute dollar savings on models with large context windows and high input token prices. When a prefix is cached, you avoid paying the input price for those tokens on subsequent requests. The financial benefit scales directly with the length of the shared prefix and the frequency of requests.

For high-volume applications, prioritize models that offer competitive input pricing while maintaining strong performance. FastInfra provides access to 722 models, allowing you to select the most cost-efficient option for your specific workload. The platform automatically routes requests to the lowest-cost provider that meets your latency requirements.

The table below outlines the cheapest models available for high-volume caching scenarios. These models are optimized for cost efficiency when combined with effective prompt caching strategies.

Cost-effective models for high-volume prompt caching
Model Family Context Window Input Price (per 1M tokens) Output Price (per 1M tokens) Cache Efficiency
The 10 cheapest paid chat models on FastInfra by combined input and output price (USD per 1M tokens)
ModelInput $/1MOutput $/1MRoutes
Solar Mini 4.5
upstage/solar-mini-4-5
$0.0108$0.04321
Mistral Nemo
mistralai/mistral-nemo
$0.0313$0.03241
L3 Lunaris 8B
sao10k/l3-lunaris-8b
$0.04$0.051
Ling 3.0 Flash
inclusionai/ling-3.0-flash
$0.0227$0.0681
Llama 3.2 3B Instruct
meta-llama/llama-3.2-3b-instruct
$0.0648$0.06482
Mistral Small 24B Instruct 2501
mistralai/mistral-small-24b-instruct-2501
$0.054$0.08642
Command R7B 12.2024
cohere/command-r7b-12-2024
$0.0375$0.151
Nova Micro V1
amazon/nova-micro-v1
$0.0378$0.15121
Schematron V2 Turbo
inference-net/schematron-v2-turbo
$0.0324$0.1621
Trinity Mini
arcee-ai/trinity-mini
$0.0486$0.1621

Models with longer context windows provide more opportunity for caching large system prompts or conversation histories. However, longer contexts also increase the base cost if caching is not utilized effectively. Always verify that the model supports KV cache persistence across requests.

To maximize savings, structure your prompts to place static information at the beginning. This ensures the largest portion of the input is cached. Dynamic content should be placed at the end to minimize cache misses. For detailed guidance on prompt structure, see the AI API guides.

Integrating with OpenAI-Compatible APIs

Most modern LLM providers expose prompt caching through standard OpenAI-compatible headers or parameters. You do not need to rewrite your inference logic to adopt this feature. The mechanism relies on the provider detecting repeated prefixes in your request payload and serving the pre-computed key-value states from memory. To enable caching, inspect the `usage` object in the API response. Most implementations return a `prompt_tokens_details` field containing `cached_tokens`. This metric tells you exactly how many tokens were served from the cache versus processed fresh. If this value is zero, your requests are missing the cache entirely. Structure your API calls to maximize prefix stability. Place static system prompts, long context windows, and few-shot examples at the beginning of the message array. Keep user-specific inputs at the end. This ensures the expensive prefix computation happens once and is reused across multiple turns or batched requests. Here is how a typical request looks when targeting a caching-enabled endpoint:
curl https://api.fastinfra.com/v1/chat/completions \
  -H "Authorization: Bearer $FASTINFRA_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Analyze this document..."}
    ]
  }'
Monitor the `cached_tokens` count in your application logs. A high ratio indicates efficient routing. If you see frequent misses, check for subtle variations in your system prompt, such as trailing whitespace or dynamic timestamps that break the prefix match. FastInfra routes these requests to providers that support this optimization. You can view available models and their specific caching capabilities on the model list. By combining stable prefixes with automatic routing, you reduce input token costs without sacrificing latency.

Combining Caching with Low-Cost Routing

Caching reduces the volume of tokens you pay for, but routing determines the price per token. Automatic routing combines these mechanisms by selecting the lowest-cost model instance that satisfies your latency and quality constraints for every request. This dual approach ensures you pay the minimum rate for both cached and uncached tokens. Without routing, you might pin a request to a specific provider or region that charges a premium, even if identical models are available elsewhere at a lower rate. FastInfra’s routing engine evaluates real-time availability and pricing across hundreds of models. It directs traffic to the cheapest endpoint that supports the required context length and caching behavior. To maximize savings, ensure your API client does not hardcode a specific model ID. Instead, use the generic endpoint and let the platform handle selection. The following request demonstrates how to send a prompt while allowing the system to choose the optimal backend:
curl https://api.fastinfra.net/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "auto",
    "messages": [{"role": "user", "content": "Summarize this document..."}],
    "temperature": 0.2
  }'
When the system selects a model, it applies the current market rate for input tokens. For high-volume applications, this can reduce costs significantly. The base price for input tokens on the cheapest available chat model is currently 0.0108. This rate applies to the tokens that are not covered by the KV cache. For the tokens that are cached, you typically pay nothing or a minimal fraction of the standard rate, depending on the provider's policy. By routing to the cheapest model, you minimize the cost of the uncached portion of the request. This is critical for long-context applications where only the final few tokens are new. Review the full list of supported models and their caching capabilities at /models. You can also configure routing preferences and cost caps in your account settings to prevent unexpected spikes. Combining precise prompt structure with aggressive low-cost routing creates a compounding effect on total API spend.

Related FastInfra resources

Frequently asked questions

Does prompt caching work for output tokens?

No. Prompt caching only applies to input tokens. Output tokens are generated sequentially and cannot be cached in the same way. You pay the standard output rate for all generated text.

How long does the cache last?

Cache duration depends on the provider and model. Typically, entries expire after a short period of inactivity or when memory pressure forces eviction. Design your app to handle cache misses gracefully without assuming persistence.

Can I force a cache hit?

You cannot force a hit, but you can increase the probability by ensuring the prefix of your request matches a recent request exactly. Any change in the system prompt or earlier messages breaks the prefix.

Which models support prompt caching?

Many modern models support caching, but availability varies. Check the model documentation or use the FastInfra catalog to filter for caching support. Proprietary and open-weight models both offer this feature.

Last reviewed November 1, 2026 by FastInfra. Prices and counts on this page are refreshed from the live catalog on every load.