Gemini API context caching lets you pay a small fraction of the normal input price when you send the same big prompt again and again. Google now runs two kinds: implicit caching, which is automatic, and explicit caching, which you control from code.
This guide shows both with the google-genai Python SDK. You get working code to create, use, list, update and delete a cache, plus the real prices and a worked cost example.
- Implicit caching: on by default for Gemini 2.5 and newer models. No code needed. Savings are passed on when a request hits the cache.
- Explicit caching: you create a cache object with
client.caches.create()and pass its name. Works on Gemini 3 and 2.5 models only. - Gemini 4 Argon and newer: implicit caching only. Explicit caching is not supported.
- Minimum size: 4,096 tokens for Gemini 4 Argon, 3.8 Flash, 3.6 Flash and 3.1 Pro Preview. 2,048 tokens for Gemini 2.5 Flash and 2.5 Pro.
- Price: cached tokens cost about 10% of the input price (5% on Gemini 4 Argon), and explicit caches also pay hourly storage.
What Context Caching Is and When to Use It
In many apps you send the same large block of input with every request. Think of a long system prompt, a 300-page PDF, a video, or a whole code repository. Without caching, you pay full input price for those tokens every single time.
Context caching stores that repeated part once. Later requests reuse it at a much lower token rate, and responses can also start faster. Google’s docs list these as the best fits:
- Chatbots with long system instructions: the same rules and examples on every turn.
- Repeated video or audio analysis: many questions about one long file.
- Recurring queries over big document sets: contracts, manuals, research papers.
- Code repository analysis: asking many questions about the same codebase.
If you are new to the SDK itself, start with my Gemini API Python tutorial and come back here.
Implicit vs Explicit Caching
Gemini gives you two caching modes. They solve the same problem but trade effort for certainty.
| Feature | Implicit caching | Explicit caching |
|---|---|---|
| Setup | None, on by default | You create a cache object in code |
| Models | Gemini 2.5 and newer, including Gemini 4 Argon | Gemini 3 and 2.5 models (not Gemini 4 Argon and onward) |
| Savings | Passed on when a request happens to hit the cache; not guaranteed | Guaranteed discount on the cached tokens |
| Storage fee | No | Yes, per million tokens per hour |
| Lifetime | Managed by Google | You set it with ttl or expire_time (default 1 hour) |
| API status | Automatic, nothing to call | Beta, under v1beta |
| Works in Interactions API | Yes | No (generateContent only) |
How to get more implicit cache hits
Implicit caching works on matching prefixes. Google recommends two habits:
- Put large, shared content first: the document or system prompt goes at the start, and the changing question goes at the end.
- Send similar requests close together: requests with the same prefix in a short window are more likely to hit.
Note: On Gemini 4 Argon and newer, in multi-turn chats and agent loops, the full previous request is cached only if the new request adds at least 2,050 tokens. Model output, thoughts and function results count toward that total. Smaller additions reprocess the last 2,050 tokens at the standard input rate.
Supported Models and Minimum Token Counts
A prompt shorter than the model’s minimum will not be cached. These are the minimums from Google’s caching page (last updated 23 Oct 2026):
| Model | Model ID | Minimum tokens | Implicit | Explicit |
|---|---|---|---|---|
| Gemini 4 Argon | gemini-4-argon |
4,096 | Yes | No |
| Gemini 3.8 Flash | gemini-3.8-flash |
4,096 | Yes | Yes |
| Gemini 3.6 Flash | gemini-3.6-flash |
4,096 | Yes | Yes |
| Gemini 3.1 Pro Preview | gemini-3.1-pro-preview |
4,096 | Yes | Yes |
| Gemini 2.5 Flash | gemini-2.5-flash |
2,048 | Yes | Yes |
| Gemini 2.5 Pro | gemini-2.5-pro |
2,048 | Yes | Yes |
The maximum cache size equals the model’s context window. Google’s newer Gemini 4 releases fall under the “Gemini 4 Argon and onward” rule, so plan for implicit caching only on them and check the caching page before you build.
Prerequisites and Setup
You need three things: Python 3.11 or newer (the SDK requires it), a Gemini API key, and the google-genai package. I checked the code in this post against google-genai 3.6.1, released on PyPI on 18 Nov 2026.
- Get an API key. Open Google AI Studio, go to the API keys page and create a key. Explicit caching on most models needs a paid (billing-enabled) project.
- Install the SDK. Run
pip install -U google-genaiin your terminal or virtual environment. - Store the key as an environment variable. On macOS or Linux run
export GEMINI_API_KEY="your-key". On Windows PowerShell run$env:GEMINI_API_KEY="your-key". - Test the client.
genai.Client()readsGEMINI_API_KEYautomatically, so you never put the key in code. - Prepare a large file. Pick a PDF, transcript or video that is well above 4,096 tokens, so it can be cached.
Warning: Never commit your API key to Git or paste it into a script. Explicit caches also cost money every hour they exist, so always delete test caches when you are done.
Example 1: Check Implicit Cache Hits
This script sends two questions about the same long document. The document comes first in both prompts, so the second request has a good chance of hitting the implicit cache.
import os
from google import genai
client = genai.Client() # reads GEMINI_API_KEY
MODEL = "gemini-3.8-flash"
with open("handbook.txt", encoding="utf-8") as f:
handbook = f.read() # should be well over 4,096 tokens
def ask(question):
response = client.models.generate_content(
model=MODEL,
contents=[handbook, question], # big shared part first
)
usage = response.usage_metadata
print("Prompt tokens:", usage.prompt_token_count)
print("Cached tokens:", usage.cached_content_token_count)
return response.text
print(ask("Summarize the leave policy in 5 bullets."))
print(ask("What does the handbook say about remote work?"))
Look at cached_content_token_count. On the first call it is usually empty. If the second call hits the cache, it shows how many tokens were billed at the cached rate.
Tip: Count your prompt first with client.models.count_tokens(model=MODEL, contents=[handbook]). If total_tokens is below the model minimum, caching will never kick in.
Example 2: Create and Use an Explicit Cache
Explicit caching gives you a named cache object. You upload a file, cache it with a system instruction, then point requests at the cache.
import time
from google import genai
from google.genai import types
client = genai.Client()
MODEL = "gemini-3.8-flash" # explicit caching: Gemini 3 and 2.5 models
# 1. Upload the large file
doc = client.files.upload(file="annual_report.pdf")
while doc.state.name == "PROCESSING":
time.sleep(2.5)
doc = client.files.get(name=doc.name)
# 2. Create the cache (TTL is a string in seconds)
cache = client.caches.create(
model=MODEL,
config=types.CreateCachedContentConfig(
display_name="annual-report-cache",
system_instruction="You are a financial analyst. Answer only from the report.",
contents=[doc],
ttl="3600s",
),
)
print("Cache name:", cache.name)
print("Cached tokens:", cache.usage_metadata.total_token_count)
# 3. Use the cache in a request
response = client.models.generate_content(
model=MODEL,
contents="List the three biggest risks mentioned in this report.",
config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)
print("Cached tokens billed:", response.usage_metadata.cached_content_token_count)
Three details matter here:
- Same model: use the cache with the same model you created it for.
- Prefix only: cached content acts as a prefix to your prompt. The model treats it like normal input.
- Tools too:
CreateCachedContentConfigalso acceptstoolsandtool_config, so long function lists can be cached.
Example 3: List, Get, Update TTL and Delete
You cannot read back the cached content. You can only see metadata: name, model, display_name, usage_metadata, create_time, update_time and expire_time.
import datetime
from google import genai
from google.genai import types
client = genai.Client()
# List every cache in the project
for c in client.caches.list():
print(c.name, c.display_name, c.model, c.expire_time)
cache_name = "cachedContents/your-cache-id"
# Get one cache
cache = client.caches.get(name=cache_name)
print(cache.usage_metadata)
# Extend the TTL by setting a new ttl
client.caches.update(
name=cache_name,
config=types.UpdateCachedContentConfig(ttl="7200s"),
)
# Or set an exact expiry time (must be time zone aware)
in_30_min = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=30)
client.caches.update(
name=cache_name,
config=types.UpdateCachedContentConfig(expire_time=in_30_min),
)
# Delete it to stop storage charges
client.caches.delete(name=cache_name)
Note: In SDK 3.6.1, caches.delete() and caches.get() take name as a keyword argument. Calling client.caches.delete(cache.name) without name= raises a TypeError.
Only ttl or expire_time can be changed. To change the content, system instruction or model, delete the cache and create a new one.
Using Caching With curl (REST)
The REST endpoint is https://generativelanguage.googleapis.com/v1beta/cachedContents. This creates a cache from inline text, uses it, then deletes it.
# request.json
# {
# "model": "models/gemini-3.8-flash",
# "systemInstruction": {"parts": [{"text": "Answer only from the document."}]},
# "contents": [{"role": "user", "parts": [{"text": "PASTE LONG DOCUMENT HERE"}]}],
# "ttl": "600s"
# }
curl -X POST "https://generativelanguage.googleapis.com/v1beta/cachedContents" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d @request.json > cache.json
CACHE_NAME=$(grep '"name":' cache.json | cut -d '"' -f 4 | head -n 1)
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"contents": [{"role": "user", "parts": [{"text": "Summarize the document."}]}], "cachedContent": "'$CACHE_NAME'"}'
curl -X PATCH "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME" \
-H "x-goog-api-key: $GEMINI_API_KEY" -H "Content-Type: application/json" \
-d '{"ttl": "1200s"}'
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME" \
-H "x-goog-api-key: $GEMINI_API_KEY"
A GET on the same cachedContents URL lists your caches. If you use the OpenAI-compatible endpoint, Google says you pass cached_content inside extra_body.
Cache Pricing and a Worked Cost Example
Explicit caching has three cost parts: cached tokens at a reduced rate, storage per hour based on the TTL, and normal charges for non-cached input and output. Here are the paid Standard tier rates per 1M tokens from Google’s pricing page, checked 28 Nov 2026:
| Model | Input | Cached input | Storage (per 1M tokens per hour) | Output |
|---|---|---|---|---|
| Gemini 4 Argon | $2.00 to 30 Nov 2026, then $4.00 | $0.10, then $0.20 (implicit only) | Not applicable | $10.00, then $20.00 |
| Gemini 3.8 Flash / 3.6 Flash | $0.75 to 31 Dec 2026, then $1.50 | $0.075, then $0.15 | $0.50, then $1.00 | $3.75, then $7.50 |
| Gemini 3.5 Flash-Lite | $0.30 | $0.03 | $1.00 | $2.50 |
| Gemini 3.1 Pro Preview | $2.00 (up to 200k), $4.00 (over) | $0.20 / $0.40 | $4.50 | $12.00 / $18.00 |
| Gemini 3.1 Flash-Lite | $0.25 text/image/video | $0.025 | $1.00 | $1.50 |
| Gemini 2.5 Pro | $1.25 (up to 200k), $2.50 (over) | $0.125 / $0.25 | $4.50 | $10.00 / $15.00 |
| Gemini 2.5 Flash | $0.30 text/image/video | $0.03 | $1.00 | $2.50 |
| Gemini 2.5 Flash-Lite | $0.10 text/image/video | $0.01 | $1.00 | $0.40 |
On the Free tier, context caching is listed as free of charge for Gemini 3.8 Flash and 3.6 Flash, and Gemini 4 Argon is not available. For the full price list and free tier limits, see my Gemini API pricing and free tier guide.
Worked example: 100 questions about a 200,000-token report
Say you ask 100 questions about one 200,000-token report within one hour on Gemini 3.8 Flash. Each question adds 500 new tokens and gets a 400-token answer. I use the rates from 1 Jan 2027 ($1.50 input, $0.15 cached, $1.00 storage, $7.50 output).
| Cost line | No caching | Explicit cache (1 hour) |
|---|---|---|
| Report tokens | 20,000,000 x $1.50/M = $30.00 | Creation: 200,000 x $1.50/M = $0.30 (assumed full rate) Reuse: 20,000,000 x $0.15/M = $3.00 |
| Storage | $0 | 200,000 x $1.00/M x 1 hour = $0.20 |
| Questions (50,000 tokens) | $0.075 | $0.075 |
| Answers (40,000 tokens) | $0.30 | $0.30 |
| Total | about $30.38 | about $3.88 |
That is roughly 87% cheaper. The creation line is a safe assumption: I billed the first pass at the full input rate. Until 31 Dec 2026 the promo rates halve every number in this table.
The storage fee is why TTL matters. Keeping the same cache for 24 hours with no traffic would add $4.80 of storage for nothing, so set a short TTL and extend it only when needed.
Limits You Should Know
| Limit | Value |
|---|---|
| Default TTL (explicit) | 1 hour if you do not set one |
| Minimum or maximum TTL | No bounds listed in the docs |
| Minimum cache size | Varies by model (2,048 or 4,096 tokens, see table above) |
| Maximum cache size | The model’s maximum context |
| Updatable fields | ttl or expire_time only |
| Viewing cached content | Not possible, metadata only |
| Rate limits | No special limits; normal GenerateContent limits apply and token limits include cached tokens |
| API version | v1beta (explicit caching is Beta) |
Gemini vs Claude vs OpenAI Prompt Caching
All three big providers now cache repeated prefixes, but the rules differ. Here is how they line up for the current models, from each provider’s docs:
| Feature | Gemini API | Claude API | OpenAI API |
|---|---|---|---|
| Automatic caching | Yes, implicit on Gemini 2.5+ | Opt-in: top-level cache_control or block markers |
Yes, on by default |
| Manual control | Cache objects via client.caches (Gemini 3 and 2.5) |
Up to 4 cache_control breakpoints |
Explicit breakpoints on GPT-5.6 and later |
| Minimum tokens | 2,048 to 4,096 | 512 on Opus 5.5, Sonnet 5.5, Haiku 5.5 | 1,024 on GPT-5.6 and later |
| Cache read price | About 0.1x input (0.05x on Gemini 4 Argon) | 0.1x input; 0.05x on Opus 5.5 and Sonnet 5.5 | 0.1x input; 0.05x on GPT-6.2 Astra and Sol |
| Write cost | No write fee, but hourly storage on explicit caches | 1.25x (5 min) or 2x (1 hour) | 1.25x (30 min) or 2.5x (12 h) on GPT-5.6 and later |
| Lifetime | Any TTL you set (default 1 hour) | 5 minutes default, 1 hour option, refreshed on each hit | 30 minutes default, 12 hours option |
| Usage field | cached_content_token_count |
cache_read_input_tokens |
cached_tokens |
The big difference is the billing model. Claude and OpenAI charge a one-time write premium. Gemini’s explicit caches charge rent by the hour, which suits a big document you hit hard for a set window.
For a deeper side-by-side with code for all three, read my prompt caching guide for Claude, OpenAI and Gemini.
Troubleshooting: Common Problems and Fixes
| Error or symptom | Cause | Fix |
|---|---|---|
400 Cached content is too small. total_token_count=..., min_total_token_count=... |
Content is below the model’s minimum | Add more content, or skip explicit caching for small prompts |
Explicit cache request rejected on gemini-4-argon |
Gemini 4 Argon and onward support implicit caching only | Drop client.caches for that model, or use Gemini 3.8 Flash or 3.6 Flash |
Error with max_total_token_count=0 on create |
Developers on the Google forum report this when the project cannot use caching on that model or tier | Check billing is active on the project and the model supports explicit caching |
TypeError on caches.delete(cache.name) |
SDK methods take keyword arguments | Use client.caches.delete(name=cache.name) |
Error when setting expire_time |
Naive datetime without a time zone | Use datetime.now(datetime.timezone.utc) |
| Request fails with “not found” after a while | The cache expired at its TTL | Extend the TTL with caches.update() before it ends, or recreate the cache |
| Model mismatch error | Request model differs from the cache’s model | Use the exact model the cache was created with |
cached_content_token_count is empty |
No implicit hit: prefix changed, prompt too short, or requests too far apart | Put shared content first and send requests close together |
For other errors such as 429 and 503, see my Gemini API errors fix guide.
Frequently Asked Questions
Is Gemini implicit caching free?
There is no setup and no storage fee. When a request hits the implicit cache, the cached tokens are billed at the lower cached rate, but Google does not guarantee a hit.
Does Gemini 4 Argon support explicit context caching?
No. Google’s docs say explicit caching is not supported for Gemini 4 Argon and onward. It does support implicit caching, with cached input at $0.10 per 1M tokens until 30 Nov 2026 and $0.20 after.
What is the minimum token count for Gemini context caching?
It is 4,096 tokens for Gemini 4 Argon, 3.8 Flash, 3.6 Flash and 3.1 Pro Preview. It is 2,048 tokens for Gemini 2.5 Flash and 2.5 Pro.
How long does an explicit Gemini cache last?
One hour by default. You can set any ttl or expire_time when you create it and extend it later with client.caches.update().
How do I know if my request used the cache?
Read response.usage_metadata.cached_content_token_count in the Python SDK. In the Interactions API, Google points to the usage.total_cached_tokens field.
Can I see or edit what is inside a cache?
No. You can only read metadata such as name, model, token count and expiry time, and you can only update the TTL or expiry time.
Is Gemini caching cheaper than Claude or OpenAI caching?
It depends on your traffic. Gemini’s explicit caching charges hourly storage instead of a write premium, so it wins when you send many requests against one large cache in a short window.
Sources
- Google AI for Developers: Context caching (generateContent)
- Google AI for Developers: Context caching (Interactions API)
- Google AI for Developers: Gemini API pricing
- Google AI for Developers: Gemini models
- PyPI: google-genai
- Claude Docs: Prompt caching
- OpenAI: Prompt caching guide
- Google AI Developers Forum: Cached content is too small



