agentic.dev

Prompt Caching: Save 90 Percent on Repeated LLM Calls

Published 2026-02-21

Prompt Caching: Save 90 Percent on Repeated LLM Calls

We’ve all been there. Building an agentic system that feels magical… until the cloud bill arrives. In 2026, with models like Gemini 1.5 Pro, Claude 3 Opus, and even increasingly capable open-source options like Mixtral 8x22B dominating the landscape, the cost of Large Language Model (LLM) inference has become a critical bottleneck. It’s not just about token usage anymore; it's the cumulative cost of repeated prompts, especially in applications with user interaction or iterative workflows. I’ve seen projects easily spend tens of thousands of dollars per month on LLM calls that, in retrospect, were largely redundant. The good news? Prompt caching, implemented strategically, can slash those costs – often by 90% or more – without significantly impacting performance. This isn't a new concept, but the scale of LLM cost makes it a necessity, and the sophistication of caching strategies has evolved rapidly.

Why is Prompt Repetition So Common?

Before diving into solutions, let's understand why we see so much prompt repetition. It's rarely malicious, more often a byproduct of how we architect agentic systems. Here are a few common culprits:

  • Retrieval-Augmented Generation (RAG): RAG is fantastic for grounding LLMs in specific knowledge. However, the core retrieval query often remains the same across multiple user interactions within a single context. Each time that query hits the vector database, the resulting context is re-prompted to the LLM.
  • Stateful Agents with Limited State Management: Agents that maintain "memory" frequently re-prompt the LLM with prior conversation turns to provide context. If the state isn't carefully managed – for example, summarizing long conversations – you're paying for the same information repeatedly.
  • Iterative Refinement Loops: Many agents use iterative loops, where the LLM generates an output, that output is analyzed, and a revised prompt is sent back to the LLM. Early iterations might produce very similar prompts, especially if the analysis step is conservative.
  • User-Driven Exploration: Users often rephrase the same question in slightly different ways, leading to functionally identical LLM calls. Think of a customer support bot – "How do I reset my password?" and "I forgot my password" are essentially the same request.
  • Parallel Processing Gone Wild: Using asynchronous task queues (like Celery or RQ) to speed up processing can inadvertently duplicate prompts if error handling isn't robust.
  • Implementing a Basic Prompt Cache with Redis

    The simplest form of prompt caching involves storing the prompt and the LLM's response in a key-value store. Redis is a popular choice due to its speed and in-memory nature. Here's a Python example using the redis and openai libraries (although the principle applies to any LLM provider):

    import redis
    import openai
    import hashlib
    

    Configure Redis connection

    redis_client = redis.Redis(host='localhost', port=6379, db=0)

    OpenAI API key (replace with your actual key)

    openai.api_key = "YOUR_OPENAI_API_KEY"

    def get_llm_response(prompt): """ Retrieves an LLM response, checking the cache first. """ # Generate a cache key based on the prompt prompt_hash = hashlib.sha256(prompt.encode('utf-8')).hexdigest() cache_key = f"llm_response:{prompt_hash}"

    # Check if the response is in the cache cached_response = redis_client.get(cache_key)

    if cached_response: print("Cache hit!") return cached_response.decode('utf-8') # Decode from bytes

    print("Cache miss. Calling LLM...") # Call the LLM (replace with your preferred model) response = openai.Completion.create( engine="gpt-3.5-turbo-instruct", #Or your preferred model prompt=prompt, max_tokens=150 ).choices[0].text.strip()

    # Store the response in the cache with a TTL (Time To Live) redis_client.set(cache_key, response, ex=3600) # Cache for 1 hour

    return response

    Example usage

    prompt1 = "What is the capital of France?" response1 = get_llm_response(prompt1) print(f"Response 1: {response1}")

    prompt2 = "What is the capital of France?" # Same prompt response2 = get_llm_response(prompt2) print(f"Response 2: {response2}")

    prompt3 = "What is the capital of Germany?" #Different prompt response3 = get_llm_response(prompt3) print(f"Response 3: {response3}")

    This code snippet hashes the prompt using SHA256 to create a unique cache key. This is crucial; you don't want slight variations in whitespace or punctuation to result in cache misses. The response is then stored in Redis with a Time To Live (TTL) of one hour. Adjust the TTL based on how frequently the underlying information changes.

    Tradeoffs:

  • Cache Invalidation: The biggest challenge. If the LLM's knowledge base is updated, or if the context changes, you need to invalidate the cache. A simple TTL isn't always sufficient.
  • Cache Size: Redis is in-memory, so you're limited by available RAM. You'll need to monitor cache usage and potentially implement eviction policies (e.g., Least Recently Used - LRU).
  • Hashing Cost: While SHA256 is fast, hashing every prompt adds a small overhead. This is usually negligible compared to the LLM call cost.
  • Serialization: You might need to serialize complex prompt structures (e.g., lists of instructions) before hashing them.
  • Beyond Basic Caching: Semantic Hashing and Fuzzy Matching

    A simple hash-based cache is effective for exact prompt matches. But what about the user who asks "Help me with my password" instead of "How do I reset my password?" That’s where more sophisticated techniques come into play.

    Considerations:

  • Embedding Model Choice: The quality of the sentence transformer significantly impacts the accuracy of semantic hashing. Choose a model that’s appropriate for your domain.
  • Similarity Threshold: Finding the right similarity threshold is crucial. Too low, and you'll get false positives. Too high, and you'll miss valid cache hits. Experimentation is key.
  • Computational Cost: Embedding prompts and performing similarity searches are more computationally expensive than simple hash lookups. Weigh the cost against the potential savings.
  • Advanced Caching Strategies for Agentic Systems

    For complex agentic systems, you need to go beyond simple prompt/response caching.

    Key Takeaways

  • Prompt caching is no longer optional. The cost of LLM inference demands it.
  • Start simple, then iterate. A basic hash-based cache can deliver significant savings with minimal effort.
  • Semantic hashing and fuzzy matching unlock further optimization. They handle variations in user input, but require careful tuning.
  • Contextual caching is essential for stateful agents. It avoids re-prompting for information that's already known.
  • Monitoring is your friend. Track cache performance to identify opportunities for improvement and ensure you're maximizing your ROI.

  • Published on agentic.dev.