Cutting LLM costs with Gemini Context Caching in Spring AI
Cache large documents on Gemini servers with Spring AI 2.0.1 GoogleGenAiCachedContentService to cut input token costs by 73.6% and latency by 76.9%.
Re-sending a 50,000-token handbook, legal corpus, or codebase inline on every chat turn wastes bandwidth, spikes time-to-first-token to several seconds, and runs up input token bills fast. Gemini Context Caching pins that static context in Google’s model memory so subsequent queries only send the short user question—discounting cached input tokens by 75%. This post shows how to manage cache lifecycles explicitly with Spring AI 2.0.1’s
GoogleGenAiCachedContentService.
Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, and
gemini-3.5-flash-lite. Source code is in spring-ai-examples (context-caching).
Inline prompts vs. server-side Context Caching
Without caching, every question re-uploads the entire document and forces the model to re-compute its KV cache from scratch. With Context Caching, you upload the document once, receive a cachedContents/<id> handle, and reference that handle on every follow-up turn until you delete it or its TTL expires.
sequenceDiagram
autonumber
actor User as User
participant App as Spring Boot (context-caching)
participant Gemini as Gemini Server Memory
Note over App,Gemini: Step 1 - Upload document once and pin cache
App->>Gemini: caches.create(48,210 tokens, systemInstruction, ttl 30m)
Gemini-->>App: cachedContents/abc123xyz
loop Step 2 - Send lightweight questions only
User->>App: "Summarize annual leave rollover policy" (18 tokens)
App->>Gemini: generateContent(cachedContentName, 18 tokens)
Note over Gemini: Reuse 48,210 cached tokens (75% input discount)
Gemini-->>App: Answer + usage(cachedContentTokenCount: 48,210)
App-->>User: Fast response (~1.1s)
end
Note over App,Gemini: Step 3 - Invalidate when done or document changes
App->>Gemini: caches.delete("abc123xyz")
Context Caching vs. RAG: when not to use caching
| Dimension | Gemini Context Caching | Vector RAG (pgvector) |
|---|---|---|
| Best corpus size | ~4,096 to 1M tokens (single large doc/codebase) | Millions of tokens across thousands of changing docs |
| Update frequency | Low (static handbooks, specs, transcripts) | High (continuous ingestion, per-record updates) |
| Cost driver | Cached token reads (75% off) + hourly storage fee | Embedding calls + vector DB hosting + retrieved chunk tokens |
| Cross-document reasoning | Reads full document with zero chunk-boundary loss | Limited to top-K retrieved chunks |
When not to use Context Caching: Don’t use it for one-off queries, small prompts under the minimum token threshold, or knowledge bases that change every minute. Because Gemini bills for storage time (tokens × hours) while a cache stays alive, caching a 100k-token document that only gets queried twice a day costs more than sending it inline or using pgvector RAG.
Four Gemini Context Caching constraints to plan around
Before writing any service code, design around these four API and framework rules:
- Minimum token threshold: Gemini rejects small caches. Gemini 2.5 Flash/Pro require at least 2,048 tokens, and Gemini 3.x Flash models require at least 4,096 tokens. Route shorter prompts through normal inline calls.
- System instruction and tool lock-in: Requests referencing a
cachedContentNamecannot overridesystemInstructionortools. You must bake the system prompt into theCachedContentRequestat creation time and avoid settingdefaultSystem(...)on theChatClientused for cached calls. - Storage billing and short TTLs: Cached input tokens get a 75% discount, but idle caches accrue storage charges per million tokens per hour. Keep TTLs tight (30–60 minutes) and explicitly
delete()caches when a user session ends or the source document is updated. - No working auto-cache in Spring AI 2.0.1: Even though
application.yamlexposes anauto-cache-thresholdproperty,GoogleGenAiChatModelin Spring AI 2.0.1 doesn’t forward it to the underlying SDK options. Explicit lifecycle management throughGoogleGenAiCachedContentServiceis the only reliable path today.
Project setup and configuration
Dependencies in build.gradle.kts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
plugins {
kotlin("jvm") version "2.3.21"
kotlin("plugin.spring") version "2.3.21"
id("org.springframework.boot") version "4.1.1"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
implementation("tools.jackson.module:jackson-module-kotlin")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}
Enabling extended usage metadata in application.yaml
Turn on include-extended-usage-metadata: true so Spring AI populates GoogleGenAiUsage.cachedContentTokenCount on every response. Without this flag, you can’t confirm in logs or metrics whether a request actually hit the server cache:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server:
port: 8095
spring:
application:
name: context-caching
ai:
google:
genai:
api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY}
chat:
model: gemini-3.5-flash-lite
options:
# Expose cachedContentTokenCount in response metadata
include-extended-usage-metadata: true
Managing cache lifecycle with GoogleGenAiCachedContentService
ContextCachingService wraps three operations: creating a cache with a bounded TTL, querying against it via GoogleGenAiChatOptions, and explicitly invalidating it. Notice normalizeCacheName: Gemini’s API expects the cachedContents/ prefix, so normalizing input IDs keeps your REST URLs clean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
@Service
class ContextCachingService(
private val cachedContentService: GoogleGenAiCachedContentService,
private val chatClient: ChatClient,
@Value("\${spring.ai.google.genai.chat.model}") private val model: String
) {
// 1. Create a server-side cache for a large document
fun createCache(displayName: String, content: String, systemInstruction: String?, ttlMinutes: Long): CachedContentMetadata {
val request = CachedContentRequest.builder()
.model(model)
.displayName(displayName)
.contents(content)
.apply { systemInstruction?.let { systemInstruction(it) } }
.ttl(Duration.ofMinutes(ttlMinutes))
.build()
val response = cachedContentService.create(request)
return CachedContentMetadata.from(response)
}
// 2. Query against the pinned cache using only the short question
fun askWithCache(cacheId: String, question: String): CachedAnswerResponse {
val cacheName = normalizeCacheName(cacheId)
val startTime = System.currentTimeMillis()
val options = GoogleGenAiChatOptions.builder()
.cachedContentName(cacheName)
.useCachedContent(true)
.build()
val chatResponse = chatClient.prompt()
.user(question)
.options(options)
.call()
.chatResponse()
val elapsed = System.currentTimeMillis() - startTime
val answer = chatResponse?.result?.output?.text ?: ""
val usage = extractUsage(chatResponse)
return CachedAnswerResponse(answer, usage, elapsed)
}
// 3. Explicitly delete (invalidate) the cache
fun deleteCache(cacheId: String) {
cachedContentService.delete(normalizeCacheName(cacheId))
}
private fun normalizeCacheName(id: String): String =
if (id.startsWith("cachedContents/")) id else "cachedContents/$id"
private fun extractUsage(response: org.springframework.ai.chat.model.ChatResponse?): TokenUsage {
val usage = response?.metadata?.usage
val cachedTokens = if (usage is GoogleGenAiUsage) usage.cachedContentTokenCount ?: 0 else 0
return TokenUsage(
promptTokens = usage?.promptTokens ?: 0,
completionTokens = usage?.completionTokens ?: 0,
totalTokens = usage?.totalTokens ?: 0,
cachedContentTokenCount = cachedTokens
)
}
}
Verification and benchmark results
Running unit and integration tests
Run the mock lifecycle tests and live Gemini cache integration tests:
1
./gradlew :context-caching:test
Figure 1. Passing tests for cache creation, TTL updates, and cachedContentTokenCount hit verification.
Creating a cache and querying via curl
Upload a 48,210-token handbook with a 30-minute TTL, then send a short follow-up question:
1
2
3
4
5
6
7
8
9
10
# 1. Create cache
curl -s -X POST http://localhost:8095/api/caches/upload \
-F "file=@./company-handbook.txt" \
-F "systemInstruction=You are an HR policy assistant. Answer strictly from the provided handbook." \
-F "ttlMinutes=30" | jq .
# 2. Query against the cache
curl -s -X POST http://localhost:8095/api/caches/abc123xyz/ask \
-H "Content-Type: application/json" \
-d '{"question": "Summarize the annual leave rollover policy"}' | jq .
Figure 2. Response JSON confirming cachedContentTokenCount: 48210 on a cached follow-up query.
1
2
3
4
5
6
7
8
9
{
"answer": "Under company policy, unused annual leave does not roll over to the next calendar year...",
"usage": {
"promptTokens": 48228,
"completionTokens": 94,
"cachedContentTokenCount": 48210
},
"elapsedMillis": 1120
}
Measured latency and cost savings (10 consecutive queries)
Running 10 consecutive questions against the same 48,210-token handbook compared inline calls against Context Caching:
Figure 3. Measured comparison showing a 76.9% latency reduction and 73.6% net cost savings over 10 queries.
| Metric | Inline Prompting | Context Caching | Change |
|---|---|---|---|
| Request payload | 185 KB | 120 Bytes | -99.9% |
| Average response latency | 4,850 ms | 1,120 ms | -76.9% |
| Net input token cost | 100% baseline | 26.4% (75% off 48,210 tokens) | -73.6% |
Production caveats and checklist
Model version pinning: A
cachedContentNameis bound to the exact model identifier passed duringcreate(). If you upgradespring.ai.google.genai.chat.modelduring a rolling deployment while old cache IDs are still stored in Redis or a database, requests referencing those old IDs will fail with a model mismatch error. Include the model name in your cache key (e.g.,handbook:v3:gemini-3.5-flash-lite) so deployments cleanly miss and rebuild caches.
Before enabling Context Caching in production, verify these four checks:
- Threshold gate: Only call
createCache()when estimated tokens exceed the model minimum (2,048for 2.5,4,096for 3.x); fall back to inline calls below that line. - No
defaultSystemconflict: KeepsystemInstructioninsideCachedContentRequestand use a cleanChatClientwithout conflicting default system prompts. - Extended usage enabled: Keep
include-extended-usage-metadata: trueon and monitorcachedContentTokenCountalongside Micrometer token metrics. - Bounded TTL + explicit cleanup: Cap TTLs to 30–60 minutes and delete caches on document edits so idle storage fees don’t accumulate.