{"slug": "prompt-caching-for-llms-cutting-latency-and-cost-without-rewriting-your-app", "title": "Prompt Caching for LLMs: Cutting Latency and Cost Without Rewriting Your App", "summary": "A developer who worked on an LLM product reports that enabling provider-side prompt caching cut per-request cost by 80% and latency from 2.5 seconds to 600ms on requests averaging 14,000 tokens of system prompt, tool definitions and retrieved context against just 50 tokens of user input. The writeup distinguishes three caching approaches — automatic provider prefix caching, application-level exact-match caching and semantic caching — and recommends prefix caching as the high-value, low-risk option, noting providers including OpenAI, Anthropic, Google and DeepSeek now discount cached prompt prefixes.", "body_md": "I worked on an LLM product last year where the average request had 14,000 tokens of system prompt, tool definitions, and retrieved context - and 50 tokens of actual user input. We were paying $0.21 per request for the privilege of re-reading the same 14,000 tokens every single time. Latency was 2.5 seconds because the model had to process all of that preamble before generating a single output token.\n\nThen we turned on prompt caching. Same outputs. Same quality. Cost dropped 80%. Latency dropped to 600ms. It was, frankly, embarrassing that we hadn't done it earlier.\n\nPrompt caching is one of those optimizations that sounds too good to be true and mostly is true. The catch - and there's always a catch - is that you have to understand what kind of caching your provider supports, structure your prompts to actually hit the cache, and instrument it well enough to know whether it's working. This article walks through all three.\n\nTwo numbers drive every LLM product: cost per request and time to first token. Both are dominated by input token processing for any non-trivial prompt.\n\nHere's the breakdown for a typical RAG request:\n\n```\nPlain TextCopy\n```\n\nRequest: 8,000 token system prompt + 4,000 token retrieved docs + 50 token user query\n\n ↓\n\nTotal input: 12,050 tokens\n\nOutput: 300 tokens: $0.006\n\nTotal: $0.042 per request, of which 99.5% is paying to re-process the same prompt\n\nAt 10,000 requests/day, that's $420/day you're burning on redundant computation. Prompt caching turns that $420 into $84, with no changes to your application logic beyond prompt structure.\n\nThe latency win is even more important than the cost win. Processing 12,000 input tokens takes the model ~1-2 seconds. Processing 50 tokens takes ~50ms. If 11,950 of those tokens are cached, your time-to-first-token drops from 2s to 100ms. That's the difference between a chatbot that feels snappy and one that feels broken.\n\nPeople use \"prompt caching\" to mean three different things. Conflating them causes most of the confusion in this area.\n\n**1. Provider-side prefix caching (automatic)**\n\nOpenAI, Anthropic, Google, and DeepSeek all now cache the model's internal KV (key-value) cache for repeated prompt prefixes. You don't do anything - if your request starts with the same tokens as a recent request, the provider reuses the cached KV state and bills you at a discount.\n\n`cache_control` markers. Caches prefixes ≥1024 tokens (Claude 3.5 Sonnet). Cache TTL: 5 min default, 1 hour with `extended-cache-ttl`. Discount: 90% on cached tokens, but you pay 25% extra to write them.\n**2. Application-level exact-match caching**\n\nYou hash the full prompt and store the response. Next time the same prompt comes in, return the cached response without calling the LLM at all. Cheap, fast (sub-ms), but only works when prompts are identical. Useful for deterministic tasks (classification, structured extraction) but useless for chat.\n\n**3. Semantic caching**\n\nEmbed the prompt, store it in a vector DB. Next request, embed and search for similar prompts. If similarity > threshold, return the cached response. Sounds great in theory, in practice produces subtle quality regressions because \"similar\" prompts can require different answers. Use with caution.\n\n| Type | Hit rate in practice | Quality risk | Implementation effort | Best for | \n|---|---|---|---|---|\n| Provider prefix | 30-90% | None | Low (just structure prompts) | RAG, chat, agents | \n| Exact match | 5-20% | None | Low | Classification, extraction | \n| Semantic | 10-40% | Medium-high | Medium | FAQ-style chat, low-stakes Q&A | \n\nThe rest of this article focuses on provider-side prefix caching (the high-value, low-risk option) and shows how to layer semantic caching on top when it makes sense.\n\nWhen an LLM processes a prompt, it doesn't recompute everything from scratch. The transformer layers produce a \"KV cache\" - the keys and values for every attention head, for every token. This cache is what makes autoregressive generation fast: each new token only attends to the cached states of prior tokens, not the raw tokens themselves.\n\n```\nPlain TextCopy\n```\n\nplaintext\n\nWithout caching:\n\nPrompt: [A B C D] [E]\n\nModel processes: A, B, C, D, E from scratch\n\nTime: O(n²) attention over all 5 tokens\n\nWith prefix caching:\n\nPrompt: [A B C D] [E]\n\nKV cache for A B C D exists → reuse\n\nModel processes: only E (attending to cached A B C D)\n\nTime: O(n) for the new token only\n\nplaintext\n\nThe KV cache is large - roughly 1MB per 1000 tokens for an 8B model. Providers don't cache everything; they cache recent prefixes and evict on a TTL. That's why you see \"cache hit rate\" drop if your traffic is bursty or your prompts vary in their prefix.\n\nThe key constraint: **the cache is prefix-based**. If your prompt is `[system] [docs] [user]` and you change anything in `[system]`, the entire cache is invalidated. If you change `[user]`, only `[system] [docs]` is cached. This is why prompt structure matters so much.\n\nThe rule: **static content first, dynamic content last**. Anything that varies per request goes at the end.\n\n```\nPlain TextCopy\n```\n\njson\n\nBad (cache never hits):\n\n[\n\n {\"role\": \"user\", \"content\": \"Question: {user_input}\"}, // varies\n\n {\"role\": \"system\", \"content\": \"{8k_token_system_prompt}\"}, // static\n\n {\"role\": \"user\", \"content\": \"Context: {retrieved_docs}\"} // varies\n\n]\n\nGood (cache hits on system prompt):\n\n[\n\n {\"role\": \"system\", \"content\": \"{8k_token_system_prompt}\"}, // static, cached\n\n {\"role\": \"user\", \"content\": \"Context: {retrieved_docs}\"}, // varies, not cached\n\n {\"role\": \"user\", \"content\": \"Question: {user_input}\"} // varies, not cached\n\n]\n\nBest (cache hits on system + docs):\n\n[\n\n {\"role\": \"system\", \"content\": \"{8k_token_system_prompt}\"}, // static, cached\n\n {\"role\": \"user\", \"content\": \"Knowledge base:\\n{static_kb_docs}\"},// static-ish, cached\n\n {\"role\": \"user\", \"content\": \"Question: {user_input}\"} // varies, not cached\n\n]\n\nThe third structure caches both the system prompt and the knowledge base docs. If your KB is the same for every request (or changes slowly), this can get you 80%+ cache hit rates. If retrieved docs vary per query (true RAG), you'll only cache the system prompt - usually 30-50% hit rate.\n\nFor Anthropic, you also need to add explicit cache breakpoints:\n\n```\nPythonCopy\n```\n\npython\n\nimport anthropic\n\nclient = anthropic.Anthropic()\n\nresponse = client.messages.create(\n\n model=\"claude-3-5-sonnet-20241022\",\n\n max_tokens=1024,\n\n system=[\n\n {\n\n \"type\": \"text\",\n\n \"text\": SYSTEM_PROMPT, # 8k tokens of static instructions\n\n \"cache_control\": {\"type\": \"ephemeral\"} # mark as cacheable\n\n },\n\n {\n\n \"type\": \"text\",\n\n \"text\": KB_DOCS, # 4k tokens of static knowledge base\n\n \"cache_control\": {\"type\": \"ephemeral\"}\n\n }\n\n ],\n\n messages=[\n\n {\"role\": \"user\", \"content\": user_query} # not cached\n\n ]\n\n)\n\nprint(response.usage)\n\nThe `cache_creation_input_tokens` is the write cost - you pay 25% extra to populate the cache, then 10% of normal on every subsequent read until TTL expires. The break-even is roughly 2 reads within the TTL window.\n\nFor OpenAI, there's no opt-in - just structure your prompts well and you'll see `cached_tokens` in the usage response:\n\n```\nPythonCopy\n```\n\nfrom openai import OpenAI\n\nclient = OpenAI()\n\nresponse = client.chat.completions.create(\n\n model=\"gpt-4o\",\n\n messages=[\n\n {\"role\": \"system\", \"content\": SYSTEM_PROMPT}, # static\n\n {\"role\": \"user\", \"content\": f\"Context: {kb_docs}\\n\\nQuestion: {query}\"}\n\n ]\n\n)\n\nmarkdown\n\nOpenAI caches automatically if your prefix is ≥1024 tokens and you've sent it recently. No code changes needed beyond prompt structure.\n\nProvider prefix caching is great for static prefixes, but it doesn't help when prompts vary semantically. \"What's the weather in Tokyo?\" and \"How's the weather in Tokyo?\" produce identical responses but never hit the prefix cache.\n\nSemantic caching closes that gap. Embed the prompt, store it in a vector store with the response. New request: embed, find nearest neighbor, if similarity > threshold return cached response.\n\n```\nPythonCopy\n```\n\nimport json\n\nimport hashlib\n\nimport time\n\nimport numpy as np\n\nimport redis\n\nfrom openai import OpenAI\n\nclass SemanticCache:\n\n def **init**(\n\n self,\n\n redis_url: str = \"redis://localhost:6379\",\n\n embedding_model: str = \"text-embedding-3-small\",\n\n similarity_threshold: float = 0.95, # cosine similarity required for a hit\n\n ttl: int = 3600, # 1 hour\n\n ):\n\n self.redis = redis.Redis.from_url(redis_url, decode_responses=False)\n\n self.openai = OpenAI()\n\n self.embedding_model = embedding_model\n\n self.similarity_threshold = similarity_threshold\n\n self.ttl = ttl\n\n # Ensure the Redis index exists\n\n self._ensure_index()\n\ndef _ensure_index(self):\n\n try:\n\n from redis.commands.search.field import VectorField, TextField\n\n from redis.commands.search.indexDefinition import IndexDefinition, IndexType\n\nschema = (\n\n TextField(\"prompt\"),\n\n VectorField(\n\n \"embedding\",\n\n \"FLAT\",\n\n {\n\n \"TYPE\": \"FLOAT32\",\n\n \"DIM\": 1536,\n\n \"DISTANCE_METRIC\": \"COSINE\",\n\n },\n\n ),\n\n )\n\n definition = IndexDefinition(index_type=IndexType.HASH)\n\n self.redis.ft(\"semantic_cache\").create_index(\n\n schema, definition=definition\n\n )\n\n except Exception:\n\n # Index already exists\n\n pass\n\ndef _embed(self, text: str) -> np.ndarray:\n\n resp = self.openai.embeddings.create(\n\n input=text, model=self.embedding_model\n\n )\n\n return np.array(resp.data[0].embedding, dtype=np.float32)\n\ndef get(self, prompt: str) -> str | None:\n\n \"\"\"Return cached response if a similar prompt exists, else None.\"\"\"\n\n embedding = self._embed(prompt).tobytes()\n\nfrom redis.commands.search.query import Query\n\nq = (\n\n Query(\"*=>[KNN 1 @embedding $vec AS score]\")\n\n .return_fields(\"score\", \"response\")\n\n .dialect(2)\n\n )\n\n results = self.redis.ft(\"semantic_cache\").search(\n\n q, query_params={\"vec\": embedding}\n\n )\n\nif not results.docs:\n\n return None\n\nscore = float(results.docs[0].score)\n\n # cosine distance is 0 (identical) to 2 (opposite)\n\n # convert to similarity: similarity = 1 - distance/2\n\n similarity = 1 - score / 2\n\nif similarity >= self.similarity_threshold:\n\n # Refresh TTL on hit\n\n self.redis.expire(results.docs[0].id, self.ttl)\n\n return results.docs[0].response.decode()\n\nreturn None\n\ndef set(self, prompt: str, response: str, metadata: dict | None = None):\n\n \"\"\"Store a prompt-response pair.\"\"\"\n\n embedding = self._embed(prompt).tobytes()\n\n key = f\"cache:{hashlib.sha256(prompt.encode()).hexdigest()[:16]}\"\n\nself.redis.hset(\n\n key,\n\n mapping={\n\n \"prompt\": prompt,\n\n \"response\": response,\n\n \"embedding\": embedding,\n\n \"metadata\": json.dumps(metadata or {}),\n\n \"ts\": int(time.time()),\n\n },\n\n )\n\n self.redis.expire(key, self.ttl)\n\nNow wrap your LLM call:\n\n```\nPythonCopy\n```\n\nimport os\n\nfrom openai import OpenAI\n\nfrom semantic_cache import SemanticCache\n\nclass CachedLLM:\n\n def **init**(self):\n\n self.client = OpenAI()\n\n self.cache = SemanticCache(\n\n redis_url=os.getenv(\"REDIS_URL\", \"redis://localhost:6379\"),\n\n similarity_threshold=0.97, # high threshold = conservative\n\n )\n\ndef chat(self, messages: list[dict], **kwargs) -> str:\n\n # Build a cache key from the user-facing portion of the prompt\n\n # Include system prompt so different system prompts don't collide\n\n cache_input = \"\\n\".join(\n\n f\"{m['role']}:{m['content']}\" for m in messages\n\n )\n\n# Check cache\n\n cached = self.cache.get(cache_input)\n\n if cached:\n\n return cached\n\n# Miss - call the LLM\n\n response = self.client.chat.completions.create(\n\n messages=messages,\n\n **kwargs,\n\n )\n\n result = response.choices[0].message.content\n\n# Store in cache (only cache non-empty responses)\n\n if result:\n\n self.cache.set(cache_input, result, metadata={\n\n \"model\": kwargs.get(\"model\", \"gpt-4o\"),\n\n \"prompt_tokens\": response.usage.prompt_tokens,\n\n })\n\nreturn result\n\nThe similarity threshold is the most important knob. Too low (0.85) and you start returning wrong answers for similar-but-different questions. Too high (0.99) and you never hit. Start at 0.95 and tune based on your data.\n\nI want to be honest about this: semantic caching is a footgun. Here are the failure modes I've seen in production:\n\n**Failure 1: \"What's the weather in Tokyo?\" cached for \"What's the weather in Paris?\"**\n\nBoth questions have nearly identical embeddings - they're the same template with one entity swapped. Cosine similarity 0.96. Your cache returns the wrong answer.\n\nFix: Pre-process prompts to detect entities (use NER) and include entities in the cache key. Or use a stricter threshold for templated queries.\n\n**Failure 2: Cached response becomes stale.**\n\n\"What's the latest news on X?\" cached yesterday. Today the user asks the same question and gets yesterday's answer.\n\nFix: Add a `max_age` field to cache entries and check it on read. For time-sensitive queries, set TTL to minutes, not hours.\n\n**Failure 3: Cached response includes a timestamp or session ID.**\n\nLLM output occasionally includes \"as of {date}\" or references to the conversation. Returning a cached response with yesterday's date breaks user trust.\n\nFix: Post-process responses to strip dynamic fields before caching, or don't cache responses that contain dynamic markers.\n\n**Failure 4: Embedding cost exceeds cache savings.**\n\nIf your cache hit rate is 5% and you're paying $0.0001 per embedding, you might be spending more on embeddings than you save on LLM calls. Run the numbers.\n\nFix: Add a cheaper exact-match cache layer in front. Most requests that would hit semantic cache have already hit exact-match cache.\n\nThe pattern I recommend: exact-match cache (cheap, fast) → semantic cache (medium) → provider prefix cache (free, automatic) → LLM call. Each layer filters out requests that can be served cheaper.\n\nYou can't optimize what you don't measure. Track these metrics per request:\n\n`cache_layer_hit`: which layer served the request (exact / semantic / provider / miss)`cache_hit_latency`: time saved by the cache hit` cache_cost_saved`: dollars saved` cache_creation_cost`: dollars spent writing to cache (Anthropic's 25% write premium)\nHere's a simple instrumentation wrapper:\n\n```\nPythonCopy\n```\n\nimport time\n\nimport logging\n\nfrom dataclasses import dataclass\n\nfrom contextlib import contextmanager\n\nlogger = logging.getLogger(\"cache_metrics\")\n\n@dataclass\n\nclass CacheMetrics:\n\n layer: str # \"exact\", \"semantic\", \"provider_prefix\", \"miss\"\n\n tokens_cached: int # tokens served from cache\n\n tokens_input: int # total input tokens\n\n tokens_output: int\n\n latency_ms: float\n\n cost_saved_usd: float\n\n cost_incurred_usd: float\n\n@property\n\n def hit_rate(self) -> float:\n\n if self.tokens_input == 0:\n\n return 0.0\n\n return self.tokens_cached / self.tokens_input\n\nclass CacheInstrumentedLLM:\n\n def **init**(self, inner_llm, cache):\n\n self.inner = inner_llm\n\n self.cache = cache\n\ndef chat(self, messages: list[dict], **kwargs) -> tuple[str, CacheMetrics]:\n\n start = time.monotonic()\n\n# Layer 1: exact match\n\n cache_key = self._exact_key(messages)\n\n cached = self.cache.exact_get(cache_key)\n\n if cached:\n\n elapsed = (time.monotonic() - start) * 1000\n\n return cached, CacheMetrics(\n\n layer=\"exact\", tokens_cached=0, tokens_input=0,\n\n tokens_output=0, latency_ms=elapsed,\n\n cost_saved_usd=0, cost_incurred_usd=0\n\n )\n\n# Layer 2: semantic cache\n\n semantic_input = self._semantic_input(messages)\n\n cached = self.cache.semantic_get(semantic_input)\n\n if cached:\n\n elapsed = (time.monotonic() - start) * 1000\n\n return cached, CacheMetrics(\n\n layer=\"semantic\", tokens_cached=0, tokens_input=0,\n\n tokens_output=0, latency_ms=elapsed,\n\n cost_saved_usd=0, cost_incurred_usd=0\n\n )\n\n# Layer 3: provider prefix cache (handled automatically)\n\n response = self.inner.chat(messages, **kwargs)\n\n elapsed = (time.monotonic() - start) * 1000\n\nusage = response.usage\n\n cached_tokens = getattr(\n\n usage.prompt_tokens_details, \"cached_tokens\", 0\n\n ) if usage.prompt_tokens_details else 0\n\n# Pricing - adjust for your model\n\n PRICE_INPUT = 0.0025 / 1000 # per token\n\n PRICE_CACHED = 0.00125 / 1000 # 50% discount\n\n PRICE_OUTPUT = 0.01 / 1000\n\ncost_incurred = (\n\n (usage.prompt_tokens - cached_tokens) * PRICE_INPUT\n\nmetrics = CacheMetrics(\n\n layer=\"provider_prefix\" if cached_tokens > 0 else \"miss\",\n\n tokens_cached=cached_tokens,\n\n tokens_input=usage.prompt_tokens,\n\n tokens_output=usage.completion_tokens,\n\n latency_ms=elapsed,\n\n cost_saved_usd=cost_saved,\n\n cost_incurred_usd=cost_incurred,\n\n )\n\n# Populate caches for next time\n\n self.cache.exact_set(cache_key, response.choices[0].message.content)\n\n self.cache.semantic_set(semantic_input, response.choices[0].message.content)\n\nreturn response.choices[0].message.content, metrics\n\ndef _exact_key(self, messages):\n\n import hashlib, json\n\n return hashlib.sha256(\n\n json.dumps(messages, sort_keys=True).encode()\n\n ).hexdigest()\n\ndef _semantic_input(self, messages):\n\n return \"\\n\".join(m[\"content\"] for m in messages if m[\"role\"] == \"user\")\n\nShip these metrics to Prometheus, Datadog, or your observability tool of choice. Build a dashboard that shows: cache hit rate by layer, average cost per request, p95 latency. When the dashboard goes red, you'll know.\n\nThe hardest part of any caching layer. With LLMs, invalidation triggers are:\n\n`gpt-4o-2024-08-06` to `gpt-4o-2024-11-20`, all cached responses are technically stale. Most teams just flush the cache on model upgrade.\nA clean pattern:\n\n```\nPythonCopy\n```\n\nimport os\n\nCACHE_VERSION = os.getenv(\"CACHE_VERSION\", \"v1\")\n\ndef build_system_prompt(base_prompt: str) -> str:\n\n \"\"\"Every system prompt gets a version prefix so cache invalidation\n\n is just bumping an env var.\"\"\"\n\n return f\"[{CACHE_VERSION}]\\n{base_prompt}\"\n\nWhen you ship a prompt change, bump `CACHE_VERSION`. Old caches become unreachable and expire naturally. No manual flushing needed.\n\n**1. Putting dynamic content at the start of the prompt.**\n\nThe single most common mistake. A timestamp in the system prompt. The user's name first. A \"current date\" header. Any of these invalidate the entire cache. Move dynamic content to the end of the message list.\n\n**2. Not checking the usage object.**\n\nYou enabled caching, but did it actually hit? Check `response.usage.cache_read_input_tokens` (Anthropic) or `response.usage.prompt_tokens_details.cached_tokens` (OpenAI). I've seen teams go three months thinking caching was working when their hit rate was 5% because of a prompt structure bug.\n\n**3. Caching the wrong things.**\n\nDon't cache streaming responses until you've fully buffered them. Don't cache tool-calling responses where the tool output changes between requests. Don't cache responses that include dynamic data.\n\n**4. Setting similarity thresholds too low for semantic cache.**\n\n0.85 sounds reasonable until you realize that \"summarize this article\" and \"summarize this article in 3 bullets\" have cosine similarity 0.93. Different intent, same embedding. Set the threshold to 0.95+ and only lower it if hit rate is too low.\n\n**5. Forgetting cache TTL.**\n\nProvider caches expire (5-10 min for OpenAI, 5 min default for Anthropic). If your traffic is bursty with >10 min gaps, your hit rate will be near zero. Either increase traffic or use the extended TTL (Anthropic's 1-hour option, billed slightly higher).\n\n**6. Not accounting for cache write cost.**\n\nAnthropic charges 25% extra for tokens written to cache. If your cache hit rate is <2 reads per write, you're losing money. Run the math before enabling.\n\n**Issue: Provider cache hit rate is 5% but should be 80%.**\n\nCause: Something in your prompt prefix is changing. Most likely a timestamp, request ID, or session token.\n\nDiagnosis: Log the first 200 characters of every prompt you send. Sort by frequency. Anything that should be static but varies is your culprit.\n\nFix: Find the dynamic element, move it to the end of the prompt.\n\n**Issue: Anthropic cache write costs exceed savings.**\n\nCause: Cache entries are being written but never read. Either TTL is expiring before next request, or your prompts aren't actually repeating prefixes.\n\nDiagnosis: Check `cache_creation_input_tokens` vs `cache_read_input_tokens` over time. Ratio should be ≥5:1 reads:writes for caching to pay off.\n\nFix: Either increase traffic, extend TTL to 1 hour, or stop caching prompts that don't repeat.\n\n**Issue: Semantic cache returns wrong answers.**\n\nCause: Threshold too low, or two semantically similar questions have different correct answers.\n\nDiagnosis: Sample 100 cache hits, manually check 20% for correctness. Calculate precision.\n\nFix: Raise threshold to 0.97. Add entity-based cache key pre-processing. Or disable semantic cache for high-stakes queries.\n\n**Issue: Latency increases after enabling caching.**\n\nCause: Embedding computation for semantic cache adds 50-100ms per request, but cache hit rate is low.\n\nDiagnosis: Measure end-to-end latency before and after. Look at cache miss path specifically.\n\nFix: Only run semantic cache check after exact-match cache misses. Use a faster embedding model (e.g., `text-embedding-3-small` instead of `large`).\n\n**Issue: Redis memory grows unbounded.**\n\nCause: TTL not being set on cache entries, or you're storing full prompt + response without size limits.\n\nFix: Always set TTL. Cap individual cache entries at 32KB. Use Redis eviction policy `allkeys-lru`.\n\nFor a real workload - 1M requests/month, average 8k token system prompt + 500 token user input + 300 token output, using GPT-4o:\n\n| Scenario | Input cost | Output cost | Total | Savings | \n|---|---|---|---|---|\n| No caching | $21,000 | $3,000 | $24,000 | - | \n| Provider prefix only (50% hit) | $13,125 | $3,000 | $16,125 | 33% | \n| Provider prefix + exact match (60% hit) | $9,450 | $2,400 | $11,850 | 51% | \n| All three layers (70% hit) | $6,615 | $2,100 | $8,715 | 64% | \n\nAdding semantic cache on top typically gets you another 5-10 percentage points but introduces quality risk. The provider prefix layer alone - which requires zero code beyond prompt structuring - gets you a third of the way. That's where to start.\n\nFor Anthropic with the same workload (Claude 3.5 Sonnet pricing):\n\n| Scenario | Cost | Savings | \n|---|---|---|\n| No caching | $45,000 | - | \n| Provider cache (90% read discount, 70% hit rate) | $18,900 | 58% | \n\nAnthropic's deeper discount (90% vs OpenAI's 50%) means caching matters even more. Worth the 25% write premium if your traffic is steady.\n\nPrompt caching is the single highest-leverage optimization for most LLM applications. The provider-side version is free, automatic (or near-automatic), and reduces cost by 30-60% with zero quality risk. The semantic version is more powerful but more dangerous - use it carefully, measure it relentlessly, and don't be afraid to disable it if quality regresses.\n\nThe order of operations: first, restructure your prompts so static content comes first. Second, enable Anthropic's explicit cache markers or rely on OpenAI's automatic caching. Third, instrument your usage so you can actually see hit rates. Fourth, only then consider semantic caching for specific high-volume, low-stakes query types.\n\nDon't skip step three. I've seen too many teams \"enable caching\" without measuring it, ship to production, and discover six months later that their hit rate was 8%. The models won't tell you. You have to look.\n\nOriginally published on [Mango Developer](https://mangodeveloper.com/articles/llm-prompt-caching).", "url": "https://wpnews.pro/news/prompt-caching-for-llms-cutting-latency-and-cost-without-rewriting-your-app", "canonical_source": "https://dev.to/mango7777/prompt-caching-for-llms-cutting-latency-and-cost-without-rewriting-your-app-2d6k", "published_at": "2026-11-27 20:30:00+00:00", "updated_at": "2026-11-27 20:44:54.106523+00:00", "lang": "en", "topics": ["large-language-models", "ai-infrastructure", "ai-tools", "mlops"], "entities": ["OpenAI", "Anthropic", "Google", "DeepSeek", "Claude 3.5 Sonnet"], "also_reported_by": [], "takeaway": "Restructuring prompts so the static system prompt, tool definitions and retrieved context form a stable cacheable prefix cut cost 80% and time-to-first-token from 2.5s to 600ms, with Anthropic's cache_control requiring prefixes of at least 1024 tokens and charging 25% extra to write cached tokens fo", "recommendation": {"advice": "Order prompts with static system text, tool definitions and retrieved context first and the user query last so provider prefix caching hits, then instrument cache hit rates to confirm the savings.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/prompt-caching-for-llms-cutting-latency-and-cost-without-rewriting-your-app", "markdown": "https://wpnews.pro/news/prompt-caching-for-llms-cutting-latency-and-cost-without-rewriting-your-app.md", "text": "https://wpnews.pro/news/prompt-caching-for-llms-cutting-latency-and-cost-without-rewriting-your-app.txt", "jsonld": "https://wpnews.pro/news/prompt-caching-for-llms-cutting-latency-and-cost-without-rewriting-your-app.jsonld"}}