◢ build log

Effective Caching Strategies for LLM API Calls

Implement caching for LLM API calls to reduce costs and improve application latency in production environments.

LLM API calls are a bottleneck for many applications. They incur direct costs for every token processed and introduce significant latency. Implementing an effective caching strategy addresses both these issues. You pay less, and your users wait less. This is a fundamental optimization for any production LLM application.

Why Cache LLM API Calls?

Caching LLM API responses directly benefits your application in two main ways:

  1. Cost Reduction: Each API call to an LLM provider costs money. By serving a cached response, you avoid making the API call entirely. For frequently repeated queries, this can lead to substantial savings.
  2. Latency Improvement: Network round trips and LLM inference times add up. A cached response can be served from a local cache or a fast key-value store in milliseconds, drastically reducing response times compared to waiting for the LLM API.

Beyond these core benefits, caching also helps with rate limiting. Fewer calls to the LLM API mean you are less likely to hit your provider's rate limits, improving application stability under load.

Designing Your Cache Key

The most critical part of an LLM cache is the cache key. It must uniquely represent the exact LLM request. If any part of the request changes, the key must change, otherwise you risk serving an incorrect or irrelevant response. Your cache key should incorporate:

  • The full prompt or messages array: This is the core input.
  • Model identifier: Different models (even different versions of the same model) will produce different outputs.
  • Sampling parameters: Temperature, top_p, frequency_penalty, presence_penalty, seed, etc. These directly influence the output.
  • Tool definitions: If your agent uses tools, their definitions are part of the request context and affect the LLM's reasoning.
  • Function call names: If you constrain the LLM to call a specific function.

A robust approach is to serialize the entire request payload (or a canonical representation of it) into a string and then hash that string. This ensures that any change, no matter how small, generates a new key.

Consider this hypothetical Python example using a simple in-memory cache:

import json
import hashlib

## Hypothetical cache store
_cache = {}

def _generate_cache_key(request_payload: dict) -> str:
    """Generates a unique cache key from the LLM request payload."""
    # Ensure consistent serialization for hashing
    # Sort keys to handle different dict orderings producing same JSON
    serialized_payload = json.dumps(request_payload, sort_keys=True)
    return hashlib.sha256(serialized_payload.encode('utf-8')).hexdigest()

def get_llm_response_cached(llm_api_call_func, request_payload: dict):
    key = _generate_cache_key(request_payload)
    if key in _cache:
        print("Cache hit!")
        return _cache[key]

    print("Cache miss. Calling LLM API...")
    response = llm_api_call_func(request_payload)
    _cache[key] = response
    return response

## Hypothetical LLM API call function
def mock_llm_api_call(payload: dict):
    # Simulate network latency and processing
    import time
    time.sleep(0.5)
    return {"id": "chatcmpl-123", "choices": [{"message": {"content": f"Response for: {payload['messages'][0]['content']}"}}]}

## Example usage
request_1 = {
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "What is the capital of France?"}],
    "temperature": 0.7
}

request_2 = {
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "What is the capital of France?"}],
    "temperature": 0.7
} # Identical to request_1

request_3 = {
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "What is the largest city in France?"}],
    "temperature": 0.7
} # Different prompt

print(get_llm_response_cached(mock_llm_api_call, request_1))
print(get_llm_response_cached(mock_llm_api_call, request_2)) # Should be a cache hit
print(get_llm_response_cached(mock_llm_api_call, request_3)) # Should be a cache miss

For production, use a dedicated key-value store like Redis, Memcached, or even a database table for persistence. These offer better performance, scalability, and persistence than an in-memory dictionary.

Cache Invalidation and Staleness

LLM responses can be somewhat stochastic, even with identical inputs and parameters. Models are also updated over time. This means a cached response might not always be exactly what the LLM would return right now. You need a strategy for dealing with stale data.

  1. Time-to-Live (TTL): The simplest and most common approach is to set an expiration time for cached items. After this duration, the item is considered stale and will be re-fetched on the next request. A TTL of a few minutes to a few hours is often appropriate for many LLM use cases. This balances freshness with cache hit rate.
  2. Explicit Invalidation: Less common for LLMs, but possible if your application has specific events that would definitively make certain LLM responses invalid. For example, if an internal knowledge base used by RAG changes, you might invalidate all RAG-related caches. This requires careful management.

Decide what level of staleness your application can tolerate. For a chatbot answering common questions, a slightly stale answer might be acceptable for the cost and latency benefits. For critical data transformation, you might need a shorter TTL or no caching at all.

When to Cache (and When Not To)

Caching is not a silver bullet. Apply it strategically:

  • Good Candidates:

    • Idempotent requests: Queries that should always yield the same logical result.
    • Common user queries: Frequently asked questions in a chatbot.
    • Static content generation: Summaries of unchanging documents, code snippets for common patterns.
    • Internal data processing: LLM calls that transform internal data where the input data does not change frequently.
  • Poor Candidates:

    • Highly dynamic, unique user inputs: Prompts that are unlikely to be repeated exactly.
    • Real-time, sensitive interactions: Where absolute freshness is paramount.
    • Requests involving volatile external data: If the LLM's response depends on constantly changing external APIs that you don't control, caching might lead to consistently stale data.

Always consider the trade-off between the cost/latency benefits and the potential for serving slightly stale or less-than-perfectly-fresh data.

Monitoring and Optimization

Once caching is in place, monitor its effectiveness. Key metrics include:

  • Cache hit ratio: The percentage of requests served from the cache. A high hit ratio (e.g., 70% or more) indicates effective caching. A low ratio suggests your keys or TTLs might need adjustment.
  • Average response time (cached vs. uncached): Confirm the latency benefits.
  • API call volume reduction: Track the actual number of LLM API calls saved.

Use your logging and monitoring tools to track these metrics. If your hit ratio is low, analyze your cache keys and the types of requests being made. You may find that certain parameters (like seed) are preventing hits and can be omitted from the key if their impact on the response is acceptable to vary.

For more ways to manage LLM API costs, see our article on /blog/llm-api-cost-optimization-chaining-models.

Where to go from here

Start by identifying the most frequently called LLM endpoints in your application. Implement a basic TTL-based caching layer for these, and then monitor the impact on your costs and latency. If you need help designing and implementing robust caching for your AI applications, consider our AI consulting services: /ai-consulting.

  • LLM caching
  • API cost optimization
  • reduce LLM latency
  • LLM production
  • cache invalidation
  • LLM API performance
  • prompt caching
  • AI application optimization
05 — execute

Ready to build
the future?

Join the developers learning to build with AI. New tutorials, tools and breakdowns every week — straight to your feed.

$ aidevguy --start --now_