<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hardik Sonetta on Medium]]></title>
        <description><![CDATA[Stories by Hardik Sonetta on Medium]]></description>
        <link>https://medium.com/@hsonetta?source=rss-72163d762b88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SHw2FmeJc7082bQyBzmuBQ.jpeg</url>
            <title>Stories by Hardik Sonetta on Medium</title>
            <link>https://medium.com/@hsonetta?source=rss-72163d762b88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:09:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hsonetta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Prompt Caching: The Secret to 60% Cost Reduction in LLM Applications]]></title>
            <link>https://medium.com/tr-labs-ml-engineering-blog/prompt-caching-the-secret-to-60-cost-reduction-in-llm-applications-6c792a0ac29b?source=rss-72163d762b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c792a0ac29b</guid>
            <category><![CDATA[prompt-caching]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[optimisation]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[thomson-reuters]]></category>
            <dc:creator><![CDATA[Hardik Sonetta]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 21:38:26 GMT</pubDate>
            <atom:updated>2025-09-30T21:38:26.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWpJcmTFDZGc7nZZ-JP-Xg.jpeg" /></figure><p><em>How a simple architectural change transformed our LLM economics and cut response times by 20%</em></p><h3>Introduction: Why LLMs Need Prompt Caching</h3><p>Large Language Models (LLMs) have transformed the way we build applications — enabling everything from chatbots and document analyzers to content generators. But as powerful as these models are, they come with two big challenges: <strong>cost</strong> and <strong>latency</strong>.</p><p>Every prompt you send to an LLM incurs a cost for every token it processes. In practical scenarios, users often ask multiple questions about the same document or engage in multi-turn conversations with persistent context. Without optimization, the model reprocesses the same context repeatedly, resulting in unnecessary expenses and slower responses.</p><p>Imagine a research paper analysis tool: a researcher uploads a 40-page scientific paper consisting of approximately 30,000 tokens and asks ten different questions about methodology, results, and implications. If the model has to re-read and re-analyze all 30,000 tokens for each question, you’re paying for 300,000 tokens — when, in reality, the paper itself hasn’t changed.</p><p><strong>Prompt caching</strong> addresses this inefficiency. It enables the LLM to “remember” the computational work it’s already done on repeated or static content. Instead of recalculating everything from scratch, the model can reuse its previous work, dramatically reducing both costs and response times.</p><p>Here’s the surprising part: most teams either don’t use prompt caching at all, or use it incorrectly — missing out on major efficiency gains. In this article, we’ll explain what prompt caching is, why it matters, and how to implement it for maximum impact in your LLM-powered applications.</p><p><strong>Important</strong>: Different model providers implement prompt caching with varying features, pricing models, and constraints. Anthropic uses integrated API caching with 5-minute TTLs, while other providers may offer different approaches. Always consult the specific documentation for your chosen provider (see references at the end for details).</p><h3>What is Prompt Caching?</h3><p>Prompt caching is an advanced optimization technique for Large Language Models (LLMs) that strategically stores and reuses the heavy computational work performed on repeated or static content. Rather than making the model “start from scratch” every time you send a similar prompt, prompt caching lets it pick up where it left off — saving both time and money.</p><p><strong>How does it work under the hood?</strong></p><p>When an LLM processes a prompt, it generates internal representations — called attention states — that capture the relationships between different parts of the input text. Traditionally, these attention states are computed for every request, even if large portions of the prompt are identical to previous ones. Prompt caching changes this by allowing the model to reuse these internal states for recurring or shared elements across prompts.</p><p><strong>Think of it like this:</strong> Imagine you’re reading a long book and taking notes as you go. If someone asks you a question about Chapter 1, you don’t reread the whole book — you just refer to your notes. Prompt caching works the same way: the LLM “remembers” its previous work so it doesn’t have to redo it.</p><h3>Key Principles of Prompt Caching</h3><p>• <strong>Modularity:</strong> Prompts are broken down into smaller, reusable units (“prompt modules”). The model can cache and later retrieve the attention states for these modules, rather than recomputing them each time.</p><p>• <strong>Selective Caching:</strong> Not every part of a prompt is cached — only those components likely to recur in future requests, such as a static document or persistent conversation context.</p><p>• <strong>Efficient Retrieval and Assembly:</strong> When a new prompt arrives, the system quickly retrieves precomputed states for any reusable modules and only computes new states for unique or changed parts. This enables rapid assembly of the full context needed for inference.</p><p>• <strong>Memory-Latency Trade-off:</strong> By storing these intermediate states, prompt caching uses more memory but dramatically reduces computation time and cost for repeated content.</p><p>This approach is fundamentally different from simple result caching (which stores final outputs) or embedding-based retrieval (which finds similar prompts based on overall similarity). Prompt caching operates at a more granular level, managing and reusing the internal computational states of the LLM, which allows for flexible composition and efficient handling of a wide variety of prompts.</p><h3>How It Works in Practice</h3><p>When you enable prompt caching, here’s what happens:</p><p>1. <strong>Cache Creation:</strong><br> The first time you send a large chunk of text (like a document or conversation history), the LLM processes it and stores the resulting attention states in a high-speed memory cache.</p><p>2. <strong>Cache Retrieval:</strong><br> The next time you send a prompt that includes the same chunk of text, the LLM quickly loads the cached states and only processes the new or changed parts.</p><p>3. <strong>Cache Expiration:</strong><br> Cached content isn’t stored forever. Most providers set a “time-to-live” (TTL), such as 5 minutes. If you reuse the same content within that window, you benefit from caching.</p><p><strong>Example:</strong><br> Let’s say you have a 30,000-token research paper and you want to ask ten different questions about it.<br> — <strong>Without caching:</strong> The LLM processes all 30,000 tokens for each question — so you pay for 300,000 tokens.<br> — <strong>With caching:</strong> The LLM processes the 30,000 tokens once, then reuses that work for each question — so you only pay for the new question tokens each time.</p><h3>Cache Limitations and Constraints</h3><p>Understanding the technical constraints of prompt caching helps set realistic expectations:</p><p>• <strong>Cache Duration</strong>: 5 minutes default (up to 1 hour with some providers)</p><p>• <strong>Breakpoints</strong>: Maximum 4 cache breakpoints per prompt (provider-dependent) — markers that designate which sections can be cached independently</p><p>• <strong>Minimum Size</strong>: 1024+ tokens required for caching eligibility</p><p>• <strong>Isolation</strong>: Caches are private to your organization</p><p>• <strong>Memory Allocation</strong>: Not publicly specified by providers</p><p>• <strong>Perfect Matching</strong>: Requires 100% identical content for cache hits — even minor changes invalidate caches</p><h3>When to Use Prompt Caching</h3><p>Prompt caching works best when you have <strong>large, reusable content</strong> that gets queried multiple times — like research papers, technical documentation, or conversation history. Perfect candidates include document analysis tools, conversational AI with persistent context, and multi-step workflows where the same content is processed repeatedly. Avoid caching for highly dynamic content that changes frequently, experimental applications with constantly evolving prompts, or single-use scenarios. Your application is a good fit if you process static content over 2,000 tokens, make multiple related queries against the same material, or support multi-turn conversations.</p><h3>The Most Common Mistake: Parallel Calls and Redundant Cache Creation</h3><p>Here’s where most developers get prompt caching wrong. The natural instinct when building high-performance applications is to make parallel LLM API calls to reduce overall latency. However, this approach introduces a hidden inefficiency that can devastate your cost savings: <strong>redundant cache creation</strong>.</p><h4>Why Parallel Calls Backfire with Prompt Caching</h4><p>Imagine a system that needs to perform multiple operations on the same large context (e.g., a document or conversation): — Extract key themes — Identify potential risks — Generate an executive summary — Answer specific questions</p><p>A naive approach might look like this:</p><pre>import asyncio<br>import anthropic<br><br>async def analyze_document_naive(document_text, questions):<br>    client = anthropic.AsyncAnthropic()<br>    <br>    # Create all tasks in parallel<br>    tasks = []<br>    for question in questions:<br>        task = client.messages.create(<br>            model=&quot;claude-3-5-sonnet-20241022&quot;,<br>            messages=[<br>                {<br>                    &quot;role&quot;: &quot;user&quot;, <br>                    &quot;content&quot;: [<br>                        {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: document_text, &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}},<br>                        {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: f&quot;Question: {question}&quot;}<br>                    ]<br>                }<br>            ]<br>        )<br>        tasks.append(task)<br>    <br>    # Execute all tasks in parallel<br>    results = await asyncio.gather(*tasks)<br>    return results</pre><p><strong><em>Note:</em></strong><em> LLM provider’s official documentation often presents prompt caching as simply adding the parameter “cache_control”: {“type”: “ephemeral”} to your request. While this does technically enable caching, it is not enough to achieve accurate or efficient prompt caching in your application. Without careful prompt design and workflow management, you risk redundant cache creation and missed cache hits — especially in parallel or high-throughput scenarios.</em></p><h4>Visualizing the Problem</h4><pre>Timeline: Parallel Execution (INEFFICIENT)<br> <br> t=0ms Call #1 starts  ──┐<br> t=5ms Call #2 starts  ──┼── All calls start nearly simultaneously<br> t=10ms Call #3 starts ──┘<br> <br> Each call independently:<br> ├── Processes research_paper (30,000 tokens)<br> ├── Creates cache for research_paper <br> ├── Processes question (100 tokens)<br> └── Returns result<br> <br> Result: 3x cache creation, 0x cache reuse<br> Cost: 3 × (30,000 × $0.00375) = $0.34</pre><p>What actually happens in this scenario is:</p><p>1. <strong>Call #1</strong> starts processing and begins creating a cache for the research paper.</p><p>2. <strong>Call #2</strong> starts before Call #1’s cache is available, so it creates its own cache.</p><p>3. <strong>Call #3</strong> also starts independently and creates yet another cache.</p><p>4. <strong>Result:</strong> You pay for cache creation three times but get zero cache reuse.</p><p>In real-world testing, this pattern resulted in: — <strong>Cache Hit Rate:</strong> 4.2% (essentially zero) — <strong>Redundant Cache Creation:</strong> Hundreds of thousands of tokens — <strong>Wasted Cost:</strong> Up to 60% higher per session</p><p>The irony is that by trying to optimize for speed through parallelization, you can actually make your application slower (due to redundant processing) and dramatically more expensive.</p><h4>Why Does This Happen?</h4><p>The root cause is <strong>timing</strong>. Cache creation takes time — typically 2–4 seconds for large research papers or documents. When you fire off parallel requests immediately, none of them can benefit from caches created by their siblings because those caches don’t exist yet. This is a classic race condition: instead of causing bugs, it causes cost explosions and wasted compute.</p><p><strong>Key Takeaway:</strong> &gt; With prompt caching, parallel LLM calls on the same context will each create their own cache if no cache exists yet. This defeats the purpose of caching and can multiply your costs.</p><h3>The Solution: Cache Warming Strategy</h3><h3>Solution Architecture</h3><p>The solution is elegantly simple: <strong>cache warming</strong>. Instead of hoping that parallel calls will somehow share caches, you proactively create the cache with a dedicated call before starting any parallel processing.</p><p>Here’s the architectural pattern:</p><pre>Timeline: Cache Warming Strategy (EFFICIENT)<br> <br> t=0ms Cache warming call starts<br> t=3000ms Cache warming completes ── Cache now available<br> t=3001ms Call #1 starts ──┐<br> t=3002ms Call #2 starts ──┼── All calls use existing cache<br> t=3003ms Call #3 starts ──┘<br> <br> Cache warming call:<br> ├── Processes research_paper (30,000 tokens)<br> ├── Creates cache for research_paper<br> └── Returns minimal response<br> <br> Subsequent calls:<br> ├── Retrieves research_paper from cache (30,000 tokens)<br> ├── Processes question (100 tokens) <br> └── Returns result<br> <br> Result: 1x cache creation, 3x cache reuse<br> Cost: (30,000 × $0.00375) + 3 × (30,000 × $0.0003) = $0.14<br> Savings: 59% cost reduction</pre><h3>Implementation Details with Code Examples</h3><p>Here’s how to implement cache warming correctly:</p><pre>import asyncio<br>import anthropic<br>from typing import List<br><br>class ResearchPaperAnalyzer:<br>    def __init__(self, api_key: str):<br>        self.client = anthropic.AsyncAnthropic(api_key=api_key)<br>        self.sync_client = anthropic.Anthropic(api_key=api_key)<br>    <br>    def warm_cache(self, research_paper: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Synchronous cache warming call.<br>        Creates cache without waiting for full response.<br>        &quot;&quot;&quot;<br>        try:<br>            # Minimal prompt designed just to establish cache<br>            self.sync_client.messages.create(<br>                model=&quot;claude-3-5-sonnet-20241022&quot;,<br>                max_tokens=10,  # Minimal response needed<br>                messages=[<br>                    {<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: [<br>                            {<br>                                &quot;type&quot;: &quot;text&quot;, <br>                                &quot;text&quot;: research_paper,<br>                                &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}<br>                            },<br>                            {<br>                                &quot;type&quot;: &quot;text&quot;,<br>                                &quot;text&quot;: &quot;Research paper loaded. Respond with &#39;Ready.&#39;&quot;<br>                            }<br>                        ]<br>                    }<br>                ]<br>            )<br>            print(&quot;Cache warmed successfully&quot;)<br>        except Exception as e:<br>            print(f&quot;Cache warming failed: {e}&quot;)<br>            # Non-critical failure - parallel calls will still work<br>    <br>    async def analyze_paper_optimized(<br>        self, <br>        research_paper: str, <br>        questions: List[str]<br>    ) -&gt; List[str]:<br>        &quot;&quot;&quot;<br>        Optimized research paper analysis with cache warming.<br>        &quot;&quot;&quot;<br>        # Step 1: Warm the cache (synchronous)<br>        print(&quot;Warming cache...&quot;)<br>        self.warm_cache(research_paper)<br>        <br>        # Step 2: Execute parallel analysis (all will use cache)<br>        print(&quot;Starting parallel analysis...&quot;)<br>        tasks = []<br>        for i, question in enumerate(questions):<br>            task = self._analyze_single_question(research_paper, question, i)<br>            tasks.append(task)<br>        <br>        results = await asyncio.gather(*tasks)<br>        return results<br>    <br>    async def _analyze_single_question(<br>        self, <br>        research_paper: str, <br>        question: str, <br>        question_id: int<br>    ) -&gt; str:<br>        &quot;&quot;&quot;<br>        Analyze a single question against the research paper.<br>        This will use the warmed cache.<br>        &quot;&quot;&quot;<br>        response = await self.client.messages.create(<br>            model=&quot;claude-3-5-sonnet-20241022&quot;,<br>            max_tokens=1000,<br>            messages=[<br>                {<br>                    &quot;role&quot;: &quot;user&quot;,<br>                    &quot;content&quot;: [<br>                        {<br>                            &quot;type&quot;: &quot;text&quot;,<br>                            &quot;text&quot;: research_paper,<br>                            &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}<br>                        },<br>                        {<br>                            &quot;type&quot;: &quot;text&quot;,<br>                            &quot;text&quot;: f&quot;Question {question_id + 1}: {question}&quot;<br>                        }<br>                    ]<br>                }<br>            ]<br>        )<br>        <br>        # Log cache utilization for monitoring<br>        usage = response.usage<br>        cache_read = getattr(usage, &#39;cache_read_input_tokens&#39;, 0)<br>        cache_write = getattr(usage, &#39;cache_creation_input_tokens&#39;, 0)<br>        <br>        print(f&quot;Q{question_id + 1}: Cache read: {cache_read:,}, Cache write: {cache_write:,}&quot;)<br>        <br>        return response.content[0].text<br><br># Usage example<br>async def main():<br>    analyzer = ResearchPaperAnalyzer(api_key=&quot;your-api-key&quot;)<br>    <br>    # Sample research paper (in practice, this would be much larger)<br>    research_paper = &quot;&quot;&quot;<br>    [Large research paper content here - 30,000+ tokens]<br>    This could be a scientific paper on machine learning, climate science, <br>    medical research, etc. The key is that it&#39;s substantial content that <br>    will be referenced multiple times with different analytical questions.<br>    &quot;&quot;&quot;<br>    <br>    questions = [<br>        &quot;What is the main research methodology used in this paper?&quot;,<br>        &quot;What are the key findings and results?&quot;, <br>        &quot;What limitations or potential biases are acknowledged?&quot;,<br>        &quot;What are the implications for future research?&quot;<br>    ]<br>    <br>    results = await analyzer.analyze_paper_optimized(research_paper, questions)<br>    <br>    for i, result in enumerate(results):<br>        print(f&quot;\n--- Answer {i + 1} ---&quot;)<br>        print(result)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p><em>Note: The following example is generic and simplified for clarity, but the pattern is directly inspired by optimizations implemented in real-world enterprise LLM systems.</em></p><h4>Best Practices for Cache Warming</h4><p>• <strong>Minimal Prompts:</strong> Use the smallest possible completion to trigger cache creation (e.g., “Ready.”).</p><p>• <strong>Synchronous Call:</strong> Ensure the cache warming call completes before launching parallel requests.</p><p>• <strong>Error Handling:</strong> If cache warming fails, proceed with parallel calls, but log and monitor for issues.</p><p>• <strong>Timeouts:</strong> Set reasonable timeouts for cache warming to avoid blocking your application.</p><p>• <strong>Monitor Cache Metrics:</strong> Track cache hit rates and cache creation tokens to verify your optimization is working.</p><h3>Results: Cost, Performance, and Business Impact</h3><h3>Cost Reduction Metrics</h3><p>Our implementation delivered dramatic improvements across all key metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*2qArQNra7SNz_2rWkoM8Ng.png" /></figure><h3>Latency Improvements</h3><p>Performance gains were equally impressive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*73qQjrrUswfYqs6nggj2Pg.png" /></figure><p><strong><em>Note on Scalability</em></strong><em>: The cache warming overhead becomes increasingly negligible as you ask more questions. With 4 questions, the 3.98s overhead represents ~5% of total session time. With 20 questions, it drops to ~1% while the 19% per-query savings compound. This makes cache warming even more compelling for high-volume analytical sessions or applications with many related queries.</em></p><p>The ROI on implementing cache warming is immediate and substantial.</p><h3>Conclusion and Key Takeaways</h3><h3>The Bottom Line</h3><p>Prompt caching is one of the most powerful levers for optimizing both cost and performance in LLM-powered applications. But the difference between a naive implementation and a strategic approach — especially with cache warming — can mean the difference between marginal gains and transformational savings.</p><p>Done right, prompt caching can: — Slash your LLM costs by more than half — Dramatically reduce response times for repeated or context-heavy queries — Enable your application to scale efficiently as usage grows</p><h3>Key Takeaways</h3><p><strong>1. Proactive Cache Warming is Essential</strong> — Never rely on parallel LLM calls to create their own caches — this leads to redundant work and wasted spend — Always establish the cache with a dedicated, minimal synchronous call before launching parallel analysis — The small upfront cost of cache warming pays for itself almost immediately</p><p><strong>2. Monitor and Measure Your Caching</strong> — Track cache hit rates, not just response times — high cache utilization is the real sign of success — Set up alerts for low cache effectiveness (&lt;80%) so you can catch regressions early — Quantify your cost savings and performance improvements to demonstrate ROI</p><p><strong>3. Design Prompts and Workflows for Caching</strong> — Structure prompts so that the largest, most reusable content is clearly separated and marked for caching — Use minimal, targeted prompts for cache warming calls — Build workflows that maximize cache reuse across related queries and user sessions</p><h3>The Bigger Picture</h3><p>As LLM applications become more sophisticated and context-heavy, efficient caching will only grow in importance. Mastering prompt caching — and especially cache warming — gives you a sustainable competitive advantage: delivering more value to users at a fraction of the cost.</p><p>The patterns and principles in this article are proven in production and will serve you well as the technology and your use cases evolve. Start optimizing today, and turn prompt caching into your secret weapon for LLM success.</p><h3>References and Further Reading</h3><p>• <a href="https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching">Anthropic Prompt Caching Documentation</a></p><p>• <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html">AWS Bedrock Prompt Caching Guide</a></p><p>• <a href="https://platform.openai.com/docs/guides/prompt-caching">OpenAI Caching Best Practices</a></p><h3>💬 Let the Conversation Begin!</h3><p>Have you implemented prompt caching in your applications? What challenges did you face, and what results did you achieve? Share your experiences in the comments below.</p><p>Join our community of AI practitioners in our <a href="https://www.linkedin.com/groups/8168422/">LinkedIn Group</a> to continue the discussion and connect with others who share your passion for pushing the boundaries of AI research and innovation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c792a0ac29b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tr-labs-ml-engineering-blog/prompt-caching-the-secret-to-60-cost-reduction-in-llm-applications-6c792a0ac29b">Prompt Caching: The Secret to 60% Cost Reduction in LLM Applications</a> was originally published in <a href="https://medium.com/tr-labs-ml-engineering-blog">Thomson Reuters Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>