{"slug": "prompt-caching-can-raise-your-bill", "title": "Prompt Caching Can Raise Your Bill", "summary": "Prompt caching, which typically cuts 70% or more off the input side of an LLM bill, can raise costs by 20% when a prompt's shared prefix is not byte-for-byte identical across requests, according to an analysis of a production workload sending roughly 4,600 tokens per request and receiving about 200 back. The author found about 4,500 of those input tokens were identical on every request, and that a timestamp or request ID placed at the top of the system prompt breaks the cache prefix, forcing the provider to write a new cache entry on every call at a 25% premium that is never read. The fix is ordering prompts so static content comes first and variable content last, since the cache only hits when the beginning of the request matches exactly, down to the character.", "body_md": "Prompt caching is about as close to free money as infrastructure work gets. It’s also the only optimization I know that can quietly make your bill bigger.\n\nThe first time I really looked at an LLM bill, the number that bothered me wasn’t the total. It was the ratio.\n\nWe were sending roughly 4,600 tokens per request and getting back about 200. Twenty-three to one. And of those 4,600, about 4,500 were byte-for-byte identical on every single request: the same system prompt, the same product docs, the same tone-of-voice rules somebody wrote in the first month and nobody has opened since.\n\nSo we were paying, several thousand times a day, for a model to read a document it had already read several thousand times that day.\n\nEvery major provider will stop charging you full price for that. It’s called prompt caching, it takes about ten minutes to switch on, and it usually knocks 70% or more off the input side of the bill.\n\nThere’s a catch, though, and it’s a genuinely funny one. Done slightly wrong, prompt caching makes your bill go *up*. And it does it without a single error, warning, or failed request. Your answers stay correct, your latency stays fine, and your invoice quietly grows by 20%. It is the only bug I know of that reports itself exclusively through your finance team.\n\nGetting it right comes down to one rule about the order of your prompt. Everything else in this article is a consequence of that rule.\n\nPicture a new hire who, every single morning, is handed the same fifty-page onboarding manual and asked one question. And every morning they read all fifty pages from the top. Very thorough. Extremely expensive.\n\nPrompt caching is that person finally remembering the manual, so they can skip to your question.\n\nUnder the hood it’s not memory in any interesting sense. The model chews through your request left to right, token by token, and the intermediate state it builds up along the way can be saved. If your next request starts with exactly the same tokens, the provider loads that saved state instead of recomputing it, and picks up where the new content begins.\n\nThree requests to a support bot. All three start with the same system prompt and the same knowledge base. Only the customer’s question is different. The first request pays to save that shared beginning, the next two get it nearly free.\n\nOne thing worth being clear about, because it trips people up: the cache does not store answers. Ask the same question twice and the model generates a fresh answer both times, and it can be a different answer. What’s cached is the *reading*, not the *thinking*. So no, this won’t make your bot repeat itself, and no, you don’t need to worry about a stale answer leaking between two customers.\n\nHere’s the rule, and it’s the only thing in this article you actually need to remember:\n\n**The cache only hits when the beginning of the request is exactly the same.**\n\nNot similar. Not mostly the same. Identical, down to the character. One extra space at position 12 and everything after position 12 counts as brand new work.\n\nWhich gives you a build order for prompts:\n\nSounds too obvious to write down. And yet, in nearly every codebase I’ve poked at, sitting right at the top of the system prompt, there it is:\n\n```\nToday is September 28, 2026, 10:01 UTC.Request ID: a1f3c9e2-...\n```\n\nSomebody added that line to be helpful. The model *should* know what day it is. Reasonable instinct, genuinely useful information, and it detonates your entire cache, because now no two requests have ever started the same way.\n\nLook at the top half of that diagram. Every request begins with a fresh timestamp, so nothing matches, so the provider dutifully saves a brand new cache entry every time. Saving costs 25% more than just reading normally. Nobody ever reads those entries. You are now paying a 25% premium for a feature you are not using.\n\nThe bottom half is the same content, rearranged. Same information reaches the model. But now the first 4,500 tokens are identical across every request, and the timestamp lives down at the bottom next to the question, where it can change as much as it likes.\n\nIn code the fix is about two lines. Here are the two versions side by side:\n\n```\nexport function badPrompt(q: Question): Prompt {  return {    instructions: [      { role: 'system', content: `${dynamicContext(q)}\\n\\n${SYSTEM_PROMPT}` }, // different every time      { role: 'system', content: KNOWLEDGE_BASE, providerOptions: CACHE },    ],    messages: [      { role: 'user', content: q.text },    ],  };}\nexport function goodPrompt(q: Question): Prompt {  return {    instructions: [      { role: 'system', content: SYSTEM_PROMPT }, // same for everyone      { role: 'system', content: KNOWLEDGE_BASE, providerOptions: CACHE },    ],    messages: [      { role: 'user', content: `${dynamicContext(q)}\\n\\n${q.text}` }, // dynamic data goes last    ],  };}\n```\n\nOn the top, the dynamic context is glued onto the front of the system prompt. On the bottom, it’s been moved into the user message, right before the question. That’s the whole diff. Same tokens, same information, one of them saves you 70%.\n\nThe marker that tells Anthropic where to cut is two lines:\n\n```\n// Cache marker: \"cache everything from the start of the request up to this block\".export const CACHE = { anthropic: { cacheControl: { type: 'ephemeral' } } };\n```\n\nYou hang it on the last static block, which in my case is the knowledge base. Everything from the start of the request up to and including that block goes in the cache. Everything after it is treated as fresh.\n\nOnce caching is on, an input token stops having one price and starts having three. For Anthropic:\n\nCurrent OpenAI models use the same ratios, they just turn it on for you. More on that later.\n\nTwo consequences fall straight out of those three numbers.\n\nThe first is that caching pays for itself on the second request and never looks back. One request costs 1.25x instead of 1x, so you’ve lost a little. Two requests cost 1.35x instead of 2x, and you’re ahead. Ten requests cost 2.15x instead of 10x.\n\nThe second is the flip side, and it’s the one that catches people: a cache entry that never gets read is a straight 25% loss. There’s no partial credit. You either reuse the prefix or you paid extra for nothing.\n\nLet’s put actual money on it. Claude Sonnet 5.5, priced as of September 2026: $2 per million input tokens, $2.50 to write to cache, $0.20 to read from it, $10 per million output. My support bot request is 4,500 tokens of static prefix, 100 tokens of question and context, 200 tokens of answer.\n\nCached requests are 3.6x cheaper. But look closer at that $0.0031, because something interesting happened: $0.002 of it is the *answer*. Two thirds of the cost is now output. The input, all 4,600 tokens of it, has shrunk to a rounding error.\n\nThat’s the real shift. Once your prefix is cached, you stop optimizing input and start optimizing output, which is a much nicer problem to have.\n\nPer-request prices are easy to nod along to, so let’s follow one small batch of traffic through a support bot and watch what happens to the bill.\n\nThe bot is called Nova, and it works for Nimbus Drive, a cloud storage company I made up so I wouldn’t have to anonymize anything. Nova gets a system prompt with the usual rules (tone, don’t leak account data, when to escalate to a human), plus about 4,000 tokens of documentation covering plans, refunds, sync error codes, file recovery windows, and team admin.\n\nThen eight real-ish customer questions, arriving a minute or two apart. “I bought the annual Plus plan nine days ago, can I still get a refund.” “The desktop app shows E777 on my new laptop.” “Someone deleted a project folder four months ago, can we get it back.”\n\nThe same eight questions, built three different ways:\n\nHere’s the part I like: you don’t need to run anything to know how each of these will go. Whether the cache hits isn’t a probabilistic thing you discover in production, it’s a string comparison. Line the requests up, see where they stop matching, and apply the price list.\n\nThe middle line is the one to sit with. Same marker, same model, same information sent to the model. One string in the wrong position, and an optimization turns into a 20% surcharge.\n\nThe 61% is lower than the 72% you’ll see later for a busy service, and the reason is that single write. Across eight requests it’s still a noticeable slice of the total. Across thousands it disappears into the average.\n\nAnd notice how differently the two cached versions behave in terms of tokens, because that’s the whole diagnostic. The healthy one writes once and then reads seven times. The broken one writes eight times and reads nothing. Every API response reports both numbers, and if you take one practical habit away from this article, make it that: get those two numbers somewhere you can see them.\n\nCaching gets sold as a cost optimization, but latency comes along for free. The model isn’t reprocessing thousands of prefix tokens, so the first token of the answer shows up sooner.\n\nI’m not going to quote you a number here, because time to first token depends on your prefix length, your region, and how busy the provider is that afternoon. What I can tell you is the shape. At 4,500 tokens of prefix the gain is real but not life-changing. It scales with how much prefix you’re skipping, though, and prefixes in production have a habit of growing. Long documents, agents with a dozen tool definitions, conversations forty messages deep: that’s where providers start quoting multi-fold speedups.\n\nFor anything with a human waiting on the other end, this is the difference between a bot that feels like it’s thinking and a bot that feels like it already knew.\n\nOne-off questions are the easy case: static block, then dynamic block, done.\n\nConversations are more interesting, because the request grows. Every turn drags the entire previous exchange along with it. By message thirty, your chat history can easily outweigh the system prompt that seemed so bloated in chapter one.\n\nGood news: history is static too. Past messages don’t get edited, they just accumulate. Which means they’re cacheable, and the trick is almost embarrassingly simple. Put a marker on the *last* message in the history. Next turn, everything up to that point, including the entire conversation so far, comes out of the cache. Only the newest exchange gets written.\n\nThe boundary walks forward with the conversation. One line of code:\n\n``` js\nexport function chatPrompt(history: ModelMessage[]): Prompt {  const last = history.length - 1;  return {    instructions: [      { role: 'system', content: SYSTEM_PROMPT },      { role: 'system', content: KNOWLEDGE_BASE, providerOptions: CACHE },    ],    // Mark the newest message: the next turn reads the whole history from cache.    messages: history.map((m, i) => (i === last ? { ...m, providerOptions: CACHE } : m)),  };}\n```\n\nTwo markers in there, doing different jobs. The one on the knowledge base means a brand new conversation gets the shared prefix cheaply from its very first message. The one on the last message means each turn after that reads its own accumulated history. Anthropic gives you up to four markers per request, so there’s room.\n\nIf you log the token counts, you can watch it happen: reads grow turn by turn as the history gets longer, while writes stay about the size of the newest exchange.\n\nProviders disagree about how much of this you should have to think about.\n\n**Anthropic, marker by hand.** You pick the cut point. Maximum control, minimal magic, and for one-off questions it’s exactly right: boundary sits after the docs, questions after it can be anything at all.\n\n**Anthropic, automatic.** Instead of marking individual blocks you can flip caching on for the whole request, and the boundary lands on the last block. For conversations this is lovely, because the boundary follows the history without you doing anything.\n\nFor one-off questions it’s a trap, and a subtle one. The boundary now *includes the question*. So request two goes looking for a cache entry that ends with “how do I recover a deleted folder”, and the entry on file ends with “can I get a refund”. Different ending, no match, no hit, and you pay the write premium forever. Everything looks configured. Nothing works.\n\n**OpenAI.** On current models caching is simply on, no markup required, as long as your request clears 1,024 tokens. Lovely. But notice what automation does and doesn’t buy you: it finds the matching prefix for you, it does not *create* one. Put a timestamp at the top and OpenAI’s automatic cache misses just as reliably as a hand-placed marker would. You’re excused from the plumbing, not from the rule.\n\n**Vercel AI Gateway.** If you route through the Gateway there’s a caching: 'auto' option that places Anthropic’s markers for you, which is handy when you’re switching providers and don’t fancy writing the markup twice. One limitation: entries live five minutes, and you can’t get the one-hour variant this way.\n\nWorth flagging, because it’s where the nice clean rule meets reality and loses a round.\n\nIf you’re doing retrieval, your prompt has a chunk in the middle that’s different on every query by design. That’s the entire point of retrieval. And a block that changes in the middle of your prefix poisons everything after it.\n\nYou can’t cache the retrieved chunks. What you can do is stop them from taking the rest of your prefix down with them: put every static thing (system prompt, rules, examples, tool definitions) before the retrieved context, and mark your boundary right at the end of the static part. You lose caching on the chunks, you keep it on everything else.\n\nAnd if your corpus is genuinely small, a few thousand tokens, there’s a slightly heretical option: skip retrieval and paste the whole thing in as a cached prefix. At 0.1x on reads, stuffing 8,000 cached tokens into every request can cost less than the vector database you built to avoid doing that. Worth pricing out before you assume otherwise.\n\nEvery one of these produces correct answers, zero errors, and a bill that refuses to go down.\n\n**1. A date, a time, or an ID at the top.** The classic. Go read the first ten lines of your system prompt right now. It’s not always a timestamp, either. User’s name, their plan tier, their locale, a session ID, an A/B test bucket. Anything that varies per request belongs at the bottom.\n\n**2. JSON key order.** If you’re interpolating objects into the prompt, remember that JSON.stringify preserves insertion order, not alphabetical order:\n\n```\nJSON.stringify({ plan: 'Plus', region: 'EU' }); // {\"plan\":\"Plus\",\"region\":\"EU\"}JSON.stringify({ region: 'EU', plan: 'Plus' }); // {\"region\":\"EU\",\"plan\":\"Plus\"}\n```\n\nSame data, two different strings, two different prefixes. Sort the keys, or build the object in exactly one place and never touch it again.\n\n**3. Tools live at the very front.** Anthropic assembles the request in a fixed order: tool definitions, then system prompt, then messages. Tools are first, which means changing them invalidates *everything*, docs included.\n\nThis bites hardest when tools are conditional. Admin users get an extra function, so admin traffic and regular traffic each need their own cache. Or the tools object gets assembled across a few modules and the key order shifts when someone reorders an import. The AI SDK has a toolOrder option for pinning this down, and it’s worth using before you need it.\n\n**4. Your prefix is under the minimum.** Every model has a floor for what it’ll bother caching. Newer Anthropic models sit at 512 or 1,024 tokens; Claude Haiku 4.5 wants 4,096. Below the floor, nothing is cached and nothing is reported. The marker is just ignored.\n\nThis one has a special flavour of irony: it usually bites while you’re switching to a cheaper model to save money. Your 2,000-token prefix cached beautifully on Sonnet and is invisible on Haiku, and the cheap model ends up costing you more than the expensive one did.\n\n**5. Five minutes is not very long.** Anthropic entries expire five minutes after their last use, and every read pushes the clock back another five. Under steady traffic the cache never gets cold. Under bursty traffic it’s ice half the time, and every cold request pays the write premium.\n\nThere’s a one-hour TTL if you need it, but the write costs 2x instead of 1.25x, so it needs at least three requests in the hour to break even. OpenAI holds entries for a minimum of 30 minutes and doesn’t charge extra for the privilege.\n\n**6. Model routing splits your cache.** Caches are per model. If you’re routing cheap questions to a small model and hard ones to a big one, that’s two caches to keep warm, each seeing a fraction of the traffic. Sometimes still worth it. Just know you’re paying for it.\n\n**7. A marker that silently does nothing.** In the AI SDK, providerOptions is keyed by provider name. Drop the key and the types still pass, the request still succeeds, and the provider ignores you completely:\n\n```\n// Silently ignored: no provider key{ providerOptions: { cacheControl: { type: 'ephemeral' } } }\n// Works{ providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } } }\n```\n\nSame outcome if Anthropic options end up under an openai key, which is a thing that happens to everyone exactly once, usually after a copy-paste, usually about twenty minutes before the deploy.\n\nThere’s exactly one reliable answer to all seven, and it’s to stop reasoning about it and read the numbers the API hands back. In the AI SDK they’re right here:\n\n``` js\nconst usage = await result.totalUsage;const { noCacheTokens = 0, cacheWriteTokens = 0, cacheReadTokens = 0 } = usage.inputTokenDetails;\n```\n\nReads stuck at zero means the cache is not working, no matter how carefully you placed the markers. Writes above zero on every single request means something up front is still changing.\n\nLog those two numbers. Graph them. Alert when reads fall off a cliff. Because this will break again, and it won’t break loudly, it’ll break three sprints from now when somebody adds one helpful line to the top of the system prompt.\n\nDepends entirely on your traffic, and the answer flips harder than you’d expect.\n\n**10,000 requests a day.** A request every few seconds, so the cache never gets a chance to cool off and essentially everything is a hit.\n\nThat’s $2,430 a month, 72%, for moving one string from the top of a prompt to the bottom. It’s the best hourly rate I’ve ever been paid.\n\nAnd look at that middle number again, because that’s the whole point of this article. The broken configuration costs $675 a month *more* than doing nothing at all. Somebody shipped a caching optimization, watched the bill go up 20%, and had no error message anywhere to explain why.\n\n**100 requests a day.** One request every quarter hour, so with a five-minute TTL roughly 70% of requests find nothing in the cache and pay the write premium. Savings collapse to about 7%. Still positive, barely worth the pull request.\n\nThis is where the one-hour TTL earns its keep: at that arrival rate almost every request lands within an hour of the previous one, so despite writes costing 2x you’re back to around 70% savings. The expensive cache is the cheap one here, which is not intuitive until you do the arithmetic.\n\nThe general shape: caching pays off in proportion to how long your static prefix is and how often it repeats. Long and busy is a jackpot. Short and quiet, don’t bother. And the cost of getting it *wrong* is roughly constant either way, which is a good argument for checking.\n\nPin this somewhere near whoever edits prompts:\n\nPrompt caching is unusually good value for the effort. No model swap, no architecture change, no quality tradeoff. You rearrange your prompt and add a marker, and the input side of your bill drops by most of itself.\n\nBut it’s a silent feature, and silent features rot. It will never tell you it stopped working. One helpful line at the top of a system prompt turns a 72% saving into a 20% penalty, and every test still passes, and every answer is still correct, and the only artifact of the whole disaster is a slightly larger number on an invoice nobody reads closely.\n\nSo: the cache only hits on an identical beginning. Everything else is a footnote. And log the token counts, because hope is not a caching strategy.\n\n*Prices as of September 28, 2026, from* *Anthropic* *and* *OpenAI**. Check current rates before running these numbers on your own workload.*\n\n*Code samples are TypeScript on the Vercel AI SDK.*\n\n[Prompt Caching Can Raise Your Bill](https://pub.towardsai.net/prompt-caching-can-raise-your-bill-dbae2e5f1d27) was originally published in [Towards AI](https://pub.towardsai.net) on Medium, where people are continuing the conversation by highlighting and responding to this story.", "url": "https://wpnews.pro/news/prompt-caching-can-raise-your-bill", "canonical_source": "https://pub.towardsai.net/prompt-caching-can-raise-your-bill-dbae2e5f1d27?source=rss----98111c9905da---4", "published_at": "2026-11-28 05:13:13+00:00", "updated_at": "2026-11-28 05:42:43.298846+00:00", "lang": "en", "topics": ["large-language-models", "ai-infrastructure"], "entities": [], "also_reported_by": [], "takeaway": "Put static content (system prompt, product docs, tone rules) first and variable content (timestamps, request IDs, user questions) last, because a single changed character at position 12 invalidates the cached prefix and turns a 70% input discount into a 25% write premium.", "recommendation": {"advice": "Reorder prompts so the static prefix is byte-identical across requests and move timestamps, request IDs and user input to the end; a timestamp at the top forces a 25% cache-write premium on every call that is never read.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/prompt-caching-can-raise-your-bill", "markdown": "https://wpnews.pro/news/prompt-caching-can-raise-your-bill.md", "text": "https://wpnews.pro/news/prompt-caching-can-raise-your-bill.txt", "jsonld": "https://wpnews.pro/news/prompt-caching-can-raise-your-bill.jsonld"}}