Versions, and an honest limit. Spring Boot 4.2.0 and Spring AI 2.1.0 (both on Maven Central since 2026-11-19), Java 25 (Temurin 25.0.5.1). The code is theprompt-cachingmodule of asmhatre/spring-ai, and every console block below is quoted from a file under itsoutput/directory. I did not call Anthropic or OpenAI. There are no API keys in my build environment, so the vendors are a local server I wrote. The requests are real: the genuineAnthropicChatModelandOpenAiChatModelbuilt them. What is simulated is the vendor side: a token is characters divided by four, the answer is fixed text, and a cache hit follows the rules the vendors document, applied to the request that arrived. So the cost figures are a worked example of the price lists (read on 2026-11-24), not an invoice, and nothing here measures how often a real provider hits its cache or how much faster it answers. The title of the idea this article started from said “measured”; that part I cannot honestly promise, and a few traps below are the reason you should measure on your own traffic.
A prompt cache remembers a prefix, and the order is fixed
The mental model is small. The provider processes your prompt from the first token to the last. If it has already processed an identical start, it skips that part and bills it at a discount. “Identical start” is literal: the same bytes, in the same order, from the very first token. Anthropic builds the prompt as tool definitions, then the system prompt, then the messages. A change anywhere invalidates that block and everything after it, but nothing before it. Anthropic makes you say where to cut: a cache breakpoint marks the end of a prefix worth remembering. OpenAI does not; it caches long prefixes on its own. The price shape is similar on both. Writing a prefix into the cache costs a little more than a normal input token (Anthropic documents 1.25× for the 5-minute lifetime and 2× for the 1-hour one), and reading it back costs a lot less (0.05× the input price for Claude Sonnet 5.5 and Opus 5.5, 0.1× for Haiku 5.5, on the pricing page). So caching is a bet: you pay a small premium now to save a large amount on every later request that arrives before the entry expires.Going deeper: what Anthropic documents about breakpoints and lifetimes
Everything here is from the Anthropic prompt caching guide, read on 2026-11-24, not something I ran against Anthropic.
- At most four explicit breakpoints per request. Cache writes happen only at breakpoints; the system then looks back at most 20 positions from each breakpoint for an entry an earlier request wrote.
- Minimum cacheable prompt: 512 tokens for Claude Sonnet 5.5, Opus 5.5 and Haiku 5.5; 1,024 for Sonnet 5 and Sonnet 4.6; 2,048 for Opus 4.7; 4,096 for Opus 4.6, Opus 4.5 and Haiku 4.5. A shorter prompt is processed normally with no error.
- The default lifetime is 5 minutes and every read refreshes it at no extra charge. The lifetime is counted from the start of the request that wrote or read the entry.
"ttl": "1h"asks for an hour. - Usage reports
input_tokens(only what comes after the last breakpoint),cache_creation_input_tokensandcache_read_input_tokens. Total input is the sum of the three. - A cache entry becomes available only once the first response starts, so a burst of parallel first requests does not share. This module does not simulate that.
The smallest thing that works: one option on the Anthropic model
In Spring AI the switch isAnthropicCacheOptions, set on the model’s default options. The default strategy is NONE, which means no caching at all until you choose one. This builds the real AnthropicChatModel (full file: Models.java) and picks SYSTEM_AND_TOOLS, which marks the end of the tool definitions and the end of the system prompt:
public static ChatModel anthropic(String baseUrl, String model, AnthropicCacheOptions cache, boolean withTools) {
AnthropicChatOptions.Builder o = AnthropicChatOptions.builder().baseUrl(baseUrl).apiKey("test-key")
.model(model).maxTokens(1024).maxRetries(0).cacheOptions(cache);
if (withTools) {
o.toolCallbacks(ToolCallbacks.from(new SupportTools()));
}
static final AnthropicCacheOptions SYSTEM_AND_TOOLS = AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_AND_TOOLS).build();
Two calls with the same tools and system prompt and a different question each time (test: HitsTest.java). The second call reads the whole 6,628-token prefix from the cache:
A. The same tools and system prompt, a different question each time
call 1 getPromptTokens=6959 getCacheReadInputTokens=0 getCacheWriteInputTokens=6628
call 2 getPromptTokens=6957 getCacheReadInputTokens=6628 getCacheWriteInputTokens=0
call 2: 6628 of 6957 prompt tokens came from the cache; 329 were billed at the plain input price
(getPromptTokens() includes the cached tokens in 2.1.0)
Output from 02-hits-and-invalidation.txt.
getPromptTokens()changed meaning between 2.0 and 2.1. On call 2 it is 6,957, the whole prompt, of which 6,628 came from the cache. I read the 2.1.0 bytecode to be sure: the Anthropic model now addsinput_tokens, cache reads and cache writes together. Theprovidersmodule’s committed transcript from Spring AI 2.0.1 showspromptTokens=3next tocacheWrite=6011, so 2.0 code that adds the three numbers up now counts the cached part twice. (I took the 2.0.1 behaviour from that transcript; I did not rerun it on 2.0.1 for this article.) The bill is the plain part, the read part and the write part, and the module’sCallUsage.javasubtracts to get it.
public static CallUsage from(Usage u) {
long read = n(u.getCacheReadInputTokens());
long write = n(u.getCacheWriteInputTokens());
return new CallUsage(n(u.getPromptTokens()) - read - write, read, write, n(u.getCompletionTokens()));
}
Going deeper: configuring it from application properties
The Spring Boot starter binds an AnthropicCacheProperties object under spring.ai.anthropic.chat.options.cache-options (the autoconfigure metadata also lists the shorter spring.ai.anthropic.chat.cache-options). Reading the class in the 2.1.0 autoconfigure jar, it has four properties: strategy, message-type-ttl, message-type-min-content-lengths and multi-block-system-caching. The reference page documents only the first and last. There is no property for cacheToolResults or contentLengthFunction; those two exist only on the Java builder. I read this from the jar and did not boot an application with the starter, so treat the exact prefix as something to confirm in your own spring-configuration-metadata.json.
- Spring AI reference: Anthropic chat, prompt caching
Models.java, which builds the model the way a starter would, without the starter.
Where each strategy puts its breakpoints
The strategies differ only in what they mark. I sent one request (four tools, a system prompt, one user turn holding two retrieved passages and a question) under each strategy and read the JSON the model class produced (test:WireTest.java):
NONE breakpoints=0 []
TOOLS_ONLY breakpoints=1 [tools[3]] {"type":"ephemeral","ttl":"5m"}
SYSTEM_ONLY breakpoints=1 [system[0]] {"type":"ephemeral","ttl":"5m"}
SYSTEM_AND_TOOLS breakpoints=2 [tools[3], system[0]] {"type":"ephemeral","ttl":"5m"}
CONVERSATION_HISTORY breakpoints=3 [tools[3], system[0], messages[0].content[0]] {"type":"ephemeral","ttl":"5m"}
Output from 01-breakpoints-on-the-wire.txt. TOOLS_ONLY puts one breakpoint on the last tool, SYSTEM_ONLY one on the system block, SYSTEM_AND_TOOLS both, and CONVERSATION_HISTORY adds a third on the newest user message. Every breakpoint carries "ttl":"5m" explicitly, even though 5 minutes is the vendor default. The last strategy is the one to be careful with, and the next section shows why.
Going deeper: the breakpoint cap, tool results and citation documents
The Spring AI reference says Anthropic allows at most four breakpoints per request and the implementation stops adding them at the limit. CONVERSATION_HISTORY as I ran it used three (tools, system, last user message). The reference also describes cacheToolResults(true), which spends one more breakpoint on the latest tool result and only takes effect under CONVERSATION_HISTORY, and says citation documents compete for the same slots (with documents present, five candidates compete for four, and the tool-definition breakpoint is the one dropped). I did not run tool results or citation documents in this module; the simulated model never asks for a tool, so that part is the reference’s word, not mine.
Per-message-type lifetimes and minimum lengths are set with messageTypeTtl(MessageType.SYSTEM, ...) and messageTypeMinContentLength(...). Both appear again below.
What breaks a hit, one changed word at a time
A hit needs every byte left of the breakpoint to be identical. So after a warm-up call I changed one thing at a time and watched what the next call read and what it had to write again:B. After a warm-up call, what does each change do? (read = served from cache, write = stored again)
(the four tool definitions alone are 550 tokens; the whole prefix is 6628)
nothing changed read=6628 write=0 uncached=326
only the retrieved context changed read=6628 write=0 uncached=1007
one word of the system prompt changed read=550 write=6079 uncached=12
one word of one tool description changed read=0 write=6628 uncached=12
Changing the retrieved context did no harm: it sits right of the breakpoints, so it is simply the uncached part (1,007 plain tokens instead of 326). Changing one word of the system prompt kept the 550 tokens of tool definitions (they come first) and rewrote the 6,079 after. Changing one word of one tool description threw away everything, because tools come before the system prompt in the prefix. This is why tool definitions are the thing to freeze: dynamically generated tool lists, or a tool description with a version stamp in it, make the entire cache a miss.
The classic version of this mistake is a clock in the system prompt. Spring AI joins several system messages into one block by default, so the clock changes the one block. multiBlockSystemCaching(true) sends each system message as its own block and puts the breakpoint on the second-to-last one, which keeps the stable text cached and lets the clock vary after it (test: HitsTest.java):
private static Usage call(ChatModel m, String clock) {
return m.call(new Prompt(List.of(new SystemMessage(POLICY), new SystemMessage("Current time: " + clock),
new UserMessage("Where is my parcel?")))).getMetadata().getUsage();
}
multiBlockSystemCaching=false system blocks sent=1 breakpoints=[system[0]]
call 1: cacheWrite=6085 cacheRead=0
call 2: cacheWrite=6085 cacheRead=0 (the clock changed between the calls)
multiBlockSystemCaching=true system blocks sent=2 breakpoints=[system[0]]
call 1: cacheWrite=6078 cacheRead=0
call 2: cacheWrite=0 cacheRead=6078 (the clock changed between the calls)
Output from 03-clock-in-the-system-prompt.txt. With one joined block, call 2 rewrites all 6,085 tokens. With two blocks, it reads 6,078 and writes nothing, although the clock changed between the calls.
The fingerprint of a broken cache. Every request shows a largecacheWriteand acacheReadof zero. You are paying the write premium each time and getting nothing back. If you only watch total tokens or total cost per day you will not see it; watch the read and write columns.
Going deeper: other things that invalidate an Anthropic prefix
From the Anthropic guide (not run here). Besides the content itself, these change the prefix: toggling web search or citations invalidates the tools level; changing tool_choice invalidates tools and system; adding or removing images anywhere invalidates tools and system; thinking parameters and effort settings are model-specific. Content that changes on every request, such as timestamps, must go after the last breakpoint.
The test in this module changes a system word, a tool word and the retrieved context, and the tools-before-system ordering showed up exactly as the guide says. The other invalidations in the list I took from the guide and did not exercise.
The failures that make no noise
Prompt caching has no error for “I decided not to cache this”. You find out from two zeros in the usage, if you look. A prompt below the minimum. The vendor requires a minimum prefix (512 tokens for Sonnet 5.5 per the guide, and the simulation uses that). Spring AI sends the breakpoint regardless; the vendor ignores it. Spring AI also has its own client-side threshold,messageTypeMinContentLength, which decides whether the breakpoint is sent at all (test: MinimumLengthTest.java):
A. The breakpoint is sent either way; the vendor decides
system prompt 1,800 characters: breakpoint sent=true call 2 read=0 write=0
system prompt 2,400 characters: breakpoint sent=true call 2 read=625 write=0
B. messageTypeMinContentLength(SYSTEM, 2000) keeps the breakpoint off short prompts, client side
system prompt 1,800 characters: breakpoint sent=false []
system prompt 2,400 characters: breakpoint sent=true [system[0]]
Output from 04-minimum-length.txt. In part A the 1,800-character prompt sent a breakpoint and got back read 0 and write 0: no cache, no error. The client-side threshold in part B only avoids sending a useless marker; note that its unit is characters (it defaults to the string length), not tokens, so it is a rough guard, not the vendor’s rule.
An entry that expires. The cache is only worth anything if the next request arrives in time. I drove a virtual clock past the lifetimes. A read refreshes the entry, so a 5-minute entry survives a gap of 290 seconds after a read, and dies at 301 (test: ExpiryTest.java):
TTL FIVE_MINUTES (cache_control sent: {"type":"ephemeral","ttl":"5m"})
t= 0s (gap 0s) MISS write=6078
t= 240s (gap 240s) HIT read=6078
t= 530s (gap 290s) HIT read=6078
t= 831s (gap 301s) MISS write=6078
t= 931s (gap 100s) HIT read=6078
Output from 05-expiry.txt. The 1-hour setting (messageTypeTtl(MessageType.SYSTEM, AnthropicCacheTtl.ONE_HOUR)) survives all of those gaps in the same test, at the price of a dearer write.
Going deeper: reading the expiry result
The behaviour above is the simulation applying the guide’s rule (lifetime counted from the start of the request that wrote or read the entry, refreshed by every read). Two details are easy to miss. First, a request that takes four minutes to stream leaves you one minute to send the next, since the clock starts when the request starts. Second, if you mix lifetimes the guide says a 1-hour entry must come before any 5-minute entries. This module does not simulate either; both are the guide’s statement.
Chat history: one breakpoint that moves, and a 20-block window
For a multi-turn chat,CONVERSATION_HISTORY keeps a breakpoint on the newest user message, so each turn reads everything before it and writes only the new turn. I ran an 8-turn chat where each user turn pastes about 1,600 characters of log, under three strategies (test: ConversationTest.java):
strategy CONVERSATION_HISTORY
turn 1 breakpoints=[system[0], messages[0].content[0]] plain=0 read=0 write=6403
turn 2 breakpoints=[system[0], messages[2].content[0]] plain=0 read=6403 write=370
turn 3 breakpoints=[system[0], messages[4].content[0]] plain=0 read=6773 write=370
turn 4 breakpoints=[system[0], messages[6].content[0]] plain=0 read=7143 write=400
turn 5 breakpoints=[system[0], messages[8].content[0]] plain=0 read=7543 write=366
turn 6 breakpoints=[system[0], messages[10].content[0]] plain=0 read=7909 write=395
turn 7 breakpoints=[system[0], messages[12].content[0]] plain=0 read=8304 write=395
turn 8 breakpoints=[system[0], messages[14].content[0]] plain=0 read=8699 write=378
8 turns: plain=0 read=52774 write=9077 input+output cost $0.0312
Output from 06-conversation.txt. The system prompt alone (SYSTEM_ONLY) re-sends the growing history as plain tokens every turn, 13,227 plain tokens in all; the moving breakpoint reads each previous turn and writes only the new turn (366 to 400 tokens). For the same 8 turns at Sonnet 5.5 prices that came to $0.1269 with no caching, $0.0491 for SYSTEM_ONLY and $0.0312 for CONVERSATION_HISTORY.
There is a limit hiding in how the vendor finds an old entry: it looks back at most 20 positions from a breakpoint. If a turn adds more than that between two breakpoints, for example a tool-heavy turn with many messages, the old entry is out of reach and only the system prompt is read:
The 20-block lookback: the same chat, but 24 messages are added between two turns
next turn, 2 messages added since the last breakpoint: read=6773 write=370
next turn, 25 messages added since the last breakpoint: read=6078 write=1339
Output from 06-conversation.txt. With 2 messages added the turn read 6,773 tokens; with 25 added it fell back to 6,078 and rewrote 1,339. This part is the guide’s lookback rule in my simulation, so it shows the shape of the effect, not a measured one.
Going deeper: when CONVERSATION_HISTORY is the wrong choice
It is the right choice when each request extends the previous one. It is the wrong choice when the last user message is different every time and never repeated, as in a retrieval-augmented question answered once. There the breakpoint on the last user message is a write nobody reads. The cost table below puts a number on it (205k tokens written and never read in 300 requests).
ConversationTest.java- Semantic Caching for LLM Calls in Spring Boot, for the other kind of cache, which skips the call entirely.
OpenAI: nothing to switch on, so the work is in the order of your text
OpenAI’s caching guide describes automatic caching of long prefixes. In Spring AI there is no breakpoint to place. What you get ispromptCacheKey on OpenAiChatOptions (it is sent as prompt_cache_key, which the guide says helps route related requests to the same cache) and a cached-token count in Usage (test: OpenAiTest.java).
A. Same system prompt, different question (simulated rule: longest shared message-boundary prefix of at least 1,024 tokens)
request carried prompt_cache_key=support-assistant-v1 keys sent: [messages, model, prompt_cache_key]
call 1: getPromptTokens=6410 getCacheReadInputTokens=0 getCacheWriteInputTokens=null
call 2: getPromptTokens=6408 getCacheReadInputTokens=6080 getCacheWriteInputTokens=null
as a price-sheet bill: plain=328 read=6080 write=0
Output from 07-openai-automatic-caching.txt. Two things to notice. getCacheReadInputTokens() carries the cached count (6,080 of 6,408). And getCacheWriteInputTokens() is null for OpenAI in Spring AI 2.1.0, so if OpenAI bills a write premium for your model you cannot read it from Usage. The guide says writes cost 1.25× the plain rate for GPT-5.6 and later with the default 30-minute window; the cost table below does not include that surcharge for the OpenAI row, which makes that row optimistic by an amount I could not measure.
Order still decides the hit. In my simulation, which caches whole messages up to the longest earlier prefix of at least 1,024 tokens, a clock inside the one big system message lost the whole message; moving the volatile text to its own later message restored the hit:
B. A clock inside the one big system message (the simulation caches whole messages, the GPT-5.6-and-later rule)
call 2: 0 of 6097 prompt tokens cached
C. The clock moved to its own message after the stable one, so a message boundary falls where the text starts to change
call 2: 6080 of 6097 prompt tokens cached
Output from 07-openai-automatic-caching.txt.
Going deeper: retention, and what Spring AI cannot set
The OpenAI guide describes two eras. For GPT-5.6 and later it uses a prompt_cache_options.ttl setting (30m default, 12h on the Responses API), a minimum of 1,024 visible input tokens, and reads at 0.1× the plain rate (0.05× for GPT-6.2 Sol, which matches the $2.00 input and $0.10 cached prices on the pricing page). Earlier models use prompt_cache_retention (in_memory or 24h) and have no write charge. The guide documents the Responses API field names (input_tokens_details.cached_tokens); Spring AI’s chat model reads the Chat Completions field prompt_tokens_details.cached_tokens, and I did not check that real GPT-6.x Chat Completions responses still carry it. My stand-in returns it because that is what the Spring AI class parses.
Neither retention setting has a builder method on OpenAiChatOptions in 2.1.0 (I listed its builder with javap: promptCacheKey is there, retention is not). It can still be sent, because extraBody merges raw fields into the request. Test E sends prompt_cache_retention=24h that way and the field arrives at the top level of the body. Whether a given model accepts it is the vendor’s business; the stand-in accepts anything.
ChatModel withExtra = OpenAiChatModel.builder().options(OpenAiChatOptions.builder().baseUrl(fake.url() + "/v1")
.apiKey("test-key").model(MODEL).maxRetries(0).promptCacheKey("support-assistant-v1")
.extraBody(Map.of("prompt_cache_retention", "24h")).build()).build();E. Options that exist in Spring AI 2.1.0, and one that has to travel through extraBody
keys on the wire: [messages, model, prompt_cache_key, prompt_cache_retention]
prompt_cache_retention=24hOutput from 07-openai-automatic-caching.txt. The simulation does not model routing by prompt_cache_key: it records that the key was sent and nothing more, because the guide says keys do not pin requests to a machine or guarantee a hit.
The cost table, and the two cases where caching costs more than none
Now put prices on it. The workload is 300 requests, each with the 6,628-token prefix (tools plus system), two retrieved passages that vary from request to request, a short question and 150 output tokens, replayed at different gaps between requests on the virtual clock. Prices are the list prices read on 2026-11-24. Test:CostTest.java.
A. claude-sonnet-5-5: the same 300 requests, arriving every N seconds (cost per 1,000 requests)
gap setup plain read write dollars vs none
20 s no caching 2,187k 0k 0k $16.08
SYSTEM_AND_TOOLS, 5 minutes 198k 1,982k 7k $3.54 -78%
SYSTEM_AND_TOOLS, 1 hour 198k 1,982k 7k $3.57 -78%
CONVERSATION_HISTORY, 5 minutes 0k 1,982k 205k $3.87 -76%
240 s no caching 2,187k 0k 0k $16.08
SYSTEM_AND_TOOLS, 5 minutes 198k 1,982k 7k $3.54 -78%
SYSTEM_AND_TOOLS, 1 hour 198k 1,982k 7k $3.57 -78%
CONVERSATION_HISTORY, 5 minutes 0k 1,982k 205k $3.87 -76%
301 s no caching 2,187k 0k 0k $16.08
SYSTEM_AND_TOOLS, 5 minutes 198k 0k 1,988k $19.39 +21%
SYSTEM_AND_TOOLS, 1 hour 198k 1,982k 7k $3.57 -78%
CONVERSATION_HISTORY, 5 minutes 0k 0k 2,187k $19.72 +23%
3700 s no caching 2,187k 0k 0k $16.08
SYSTEM_AND_TOOLS, 5 minutes 198k 0k 1,988k $19.39 +21%
SYSTEM_AND_TOOLS, 1 hour 198k 0k 1,988k $29.33 +82%
CONVERSATION_HISTORY, 5 minutes 0k 0k 2,187k $19.72 +23%
08-cost.txt, shown as a chart above. With a request every 20 seconds, caching the prefix takes the 1,000-request bill from $16.08 to $3.54, which is 78% less. Three results are less obvious:
- The 5-minute entry is a trap when traffic is thin. At a request every 301 seconds the entry has always just expired, so every request writes at 1.25× and reads nothing: $19.39, 21% more than not caching. The 1-hour lifetime fixes that case ($3.57).
- The 1-hour entry has the same cliff, further out. At a request every 3,700 seconds even the hour is gone, and each request writes at 2×: $29.33, 82% more than not caching.
CONVERSATION_HISTORYon a one-shot RAG request costs more thanSYSTEM_AND_TOOLS($3.87 against $3.54 at 20 seconds), because the retrieved passages change every time, so the breakpoint on the user message writes 205k tokens that nobody reads.
OpenAiChatModel and its “no caching” case made by putting the request number on the first line so no prefix is shared:
B. The same requests every 20 seconds, per model (SYSTEM_AND_TOOLS with the 5-minute lifetime for Anthropic)
model no caching cached saving
claude-haiku-5-5 $0.80 $0.21 -74%
claude-sonnet-5-5 $16.08 $3.54 -78%
claude-opus-5-5 $32.15 $7.07 -78%
gpt-6.2-sol $16.35 $3.54 -78% (OpenAI: automatic; 'no caching' = every request sent with a changing first message)
Output from 08-cost.txt. Savings are about 74% to 78% in each row. The OpenAI figure is optimistic for the write-surcharge reason above. And break-even is easy to compute from the price list, because only two ratios matter:
C. How many hits inside the lifetime does a write pay back? hits = (write multiple - 1) / (1 - read multiple)
model write 5m read hits (5m) hits (1h)
claude-haiku-5-5 1.25x 0.100x 0.28 1.11
claude-sonnet-5-5 1.25x 0.050x 0.26 1.05
claude-opus-5-5 1.25x 0.050x 0.26 1.05
For Sonnet 5.5 a 5-minute write pays for itself after 0.26 hits, so a single read inside the lifetime is already a profit; the 1-hour write needs 1.05 hits, so one read is not quite enough and two are. That is the whole decision: caching a prefix is worth it if you expect a second request inside the lifetime, and the lifetime should match your real gap between requests.
Going deeper: how the numbers are made, and what they leave out
Each request is a real Spring AI call; the usage Spring AI reads back is what my stand-in produced from the documented rules. The arithmetic is plain: plain tokens at the input price, reads at the cache-read price, writes at the 5-minute or 1-hour write price, output at the output price (Cost.java). The 300-request totals are scaled to 1,000 for the table, which is exact because every request is the same size to within the retrieved passages.
What the table leaves out: real tokenisation (a real tokenizer will not give characters divided by four), concurrent requests that arrive before the first write is visible, latency (caching is also a speed feature and I measured none of it), the cost of the output, which is fixed at 150 tokens here and which caching does not touch, and the real hit rate, which depends on how your traffic is spread over time. Treat the shape (a premium, a cliff at the lifetime, the wasted write) as the finding, and the dollar amounts as arithmetic.
Cost.java,Prices.java,Rates.java- Observability for Spring AI, for recording token usage in production so you can see your real read and write counts.
- Anthropic Claude vs OpenAI vs Gemini in Spring AI 2.0, which covers prompt caching on all three providers from the 2.0 side.
Should you turn it on?
Yes if a second request usually arrives inside the lifetime; measure first if not. A stable prefix of a few thousand tokens that you send many times a minute is the clear win. Thin or bursty traffic, a prefix that changes (dynamic tool lists, a timestamp near the top), or a one-shot request whose last message is new every time are the cases where it costs more than it saves, and the cost table shows each of them. LoggetCacheReadInputTokens()andgetCacheWriteInputTokens()from day one and alert on a large write with a zero read.
What this module does not show. It never ran against a real provider, so hit rates, latency, real invoices, Anthropic’s concurrency behaviour, tool-result caching and citation documents are all outside what I can claim. Everything vendor-side is the documentation’s rule applied by a stand-in I wrote.
Further reading
- The code: prompt-caching in asmhatre/spring-ai, with output/ holding every transcript quoted above, regenerated by scripts/run-all.sh (no API key, no network to a model vendor).
- Anthropic Claude vs OpenAI vs Gemini in Spring AI 2.0
- Observability for Spring AI: Tokens, Latency and Cost
- Semantic Caching for LLM Calls in Spring Boot with Redis Vector Search
- The LLM Gateway Pattern for Java Microservices
- Spring AI 1.x to 2.0 migration guide
- Anthropic: prompt caching and pricing
- OpenAI: prompt caching and pricing
- Spring AI reference: Anthropic chat
No Comments yet!