Understanding Context Caching in Gemini 1.5
Gemini 1.5 models store the key-value cache of a large prefix on Google’s servers after the first processing. Subsequent requests reference this stored state by cache name, skipping recomputation of attention for the cached tokens. The @google/generative-ai package version 0.21.0 exposes createCachedContent, getGenerativeModelFromCachedContent, updateCachedContent, listCachedContents and deleteCachedContent methods. Both gemini-1.5-flash-001 and gemini-1.5-pro-001 support caching up to their respective context limits of 1 million and 2 million tokens.
Cached content includes a mandatory system instruction plus an array of Content parts that can mix text, inline data, or Google Cloud Storage file references. Once created, the cache receives a unique name starting with cachedContents/. This name is the only identifier needed for later inference calls. Storage duration is controlled by either ttlSeconds or an absolute expireTime RFC3339 timestamp. After expiration the cache is automatically deleted and any reference to it returns a NOT_FOUND error.
Token Billing Mechanics
Regular input tokens and cached input tokens are billed at different rates. The cached prefix is charged once at creation time for processing and then at a lower storage rate per hour. Each inference call charges only for the additional user message tokens, the cached token count at the reduced rate, and the output tokens. This separation makes repeated long-context queries economical when query volume exceeds the break-even point determined by cache creation cost and TTL.
Setting Up the Google Generative AI SDK in TypeScript
Install the precise SDK version to ensure stable cache behavior:
npm install @google/generative-ai@0.21.0
npm install --save-dev @types/node
Create a configuration module that exports a typed client instance. Use environment variables validated at startup to avoid runtime key errors.
import { GoogleGenerativeAI } from "@google/generative-ai";
import { config } from "dotenv";
config();
if (!process.env.GEMINI_API_KEY) {
throw new Error("GEMINI_API_KEY environment variable is required");
}
export const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
export const flashModelName = "models/gemini-1.5-flash-001";
export const proModelName = "models/gemini-1.5-pro-001";
This module is imported by all cache creation and inference files, guaranteeing consistent model versioning. For production deployments on Vercel or Cloud Run, add the environment variable through the respective dashboard rather than a .env file.
TypeScript Interfaces for Cache Operations
Define reusable interfaces to catch configuration mistakes at compile time:
interface CacheConfig {
displayName: string;
systemInstruction: string;
contents: Array<{
role: "user";
parts: Array<{ text: string } | { fileData: { mimeType: string; fileUri: string } }>;
}>;
ttlSeconds?: number;
expireTime?: string;
}
interface CachedModelRequest {
cachedContent: string;
tools?: Array<any>;
}
Creating and Configuring Cached Content
The creation process requires a Google Cloud Storage bucket with appropriate IAM permissions for the service account tied to your API key. Use the following function to create a cache containing both a PDF reference manual and supplementary markdown policies.
import { genAI, flashModelName } from "./config";
export async function createSupportCache(): Promise<string> {
const cache = await genAI.createCachedContent({
model: flashModelName,
displayName: "Customer Support KB v2024.10.15",
systemInstruction: "You are a level-3 technical support agent. Answer using only the cached documentation and retrieved context. Cite document sections. Refuse unrelated questions.",
contents: [
{
role: "user",
parts: [
{
fileData: {
mimeType: "application/pdf",
fileUri: "gs://support-docs-bucket/product-manual-v4.pdf"
}
},
{
text: "# Additional Policies\n\nRefund policy: ... (full markdown here)"
}
]
}
],
ttlSeconds: 86400, // exactly 24 hours
});
console.log(`Cache created: ${cache.name} (expires in 24h)`);
return cache.name;
}
Run this function once during application startup or via a scheduled job. The PDF file must be accessible; otherwise the creation call fails with a PERMISSION_DENIED error. Creation time for a 220 000 token cache averages 45 seconds on Flash. After creation, immediately store the returned name in a persistent key-value store such as Redis or Cloud Firestore under a known key like active_support_cache.
Choosing TTL Values Based on Content Volatility
For documentation that changes weekly, set ttlSeconds: 604800 (7 days) and recreate every Monday at 02:00 UTC. For regulatory texts that change monthly, use 2 592 000 seconds (30 days). Always pair the TTL with a monitoring alert that triggers if cache creation latency exceeds 120 seconds.
Querying Cached Content with Single-turn and Multi-turn Interactions
Retrieve the cache name from storage and instantiate a model that references it. The following function supports both simple questions and chat sessions.
export async function generateWithCache(cacheName: string, prompt: string, history: Array<any> = []) {
const model = genAI.getGenerativeModelFromCachedContent({
cachedContent: cacheName,
});
const chat = model.startChat({
history: history,
});
const result = await chat.sendMessage(prompt);
const usage = result.response.usageMetadata;
console.log(`Cached tokens used: ${usage?.cachedContentTokenCount || 0}`);
return {
text: result.response.text(),
usage,
};
}
The usageMetadata object returns cachedContentTokenCount, promptTokenCount and candidatesTokenCount. Log these values to calculate precise per-query cost using Google’s published rate card for the chosen model and region.
Streaming Responses from Cached Content
Replace generateContent with generateContentStream for user-facing applications. The cache reference works identically:
const streamResult = await model.generateContentStream(prompt);
for await (const chunk of streamResult.stream) {
process.stdout.write(chunk.text());
}
Streaming does not change billing; the full cached token count is still charged once per request.
Building a Hybrid RAG System Combining Vector Search and Caching
Static knowledge lives in the cache while fresh or customer-specific data is retrieved from a vector store. The following complete Next.js 15 route handler demonstrates the pattern using Pinecone 1.1.0 and the Gemini embeddings model.
// app/api/support/route.ts
import { Pinecone } from "@pinecone-database/pinecone";
import { genAI, flashModelName } from "../../../lib/gemini";
import { createSupportCache } from "../../../lib/cache";
const pc = new Pinecone({ apiKey: process.env.PINECONE_API_KEY! });
const index = pc.index("support-embeddings");
let activeCacheName: string | null = null;
async function getCacheName(): Promise<string> {
if (activeCacheName) return activeCacheName;
activeCacheName = await createSupportCache();
return activeCacheName;
}
export async function POST(request: Request) {
const { question, conversationId } = await request.json();
const cacheName = await getCacheName();
// 1. Create embedding for the user question
const embedModel = genAI.getGenerativeModel({ model: "embedding-001" });
const embedResult = await embedModel.embedContent(question);
const vector = embedResult.embedding.values;
// 2. Retrieve top 4 relevant chunks
const queryResult = await index.query({
vector,
topK: 4,
includeMetadata: true,
});
const contextChunks = queryResult.matches
.map((m: any) => m.metadata?.content as string)
.filter(Boolean)
.join("\n---\n");
// 3. Call cached model with augmented context
const model = genAI.getGenerativeModelFromCachedContent({
cachedContent: cacheName,
});
const result = await model.generateContent(
`Retrieved context:\n${contextChunks}\n\nCustomer question: ${question}`
);
return Response.json({
answer: result.response.text(),
cacheName,
retrievalCount: queryResult.matches.length,
});
}
Deploy this route with Edge runtime enabled. The cache creation runs only on cold starts or after TTL expiry. Pinecone index creation command used was pc.createIndex({ name: "support-embeddings", dimension: 768, metric: "cosine" }). The hybrid approach keeps the cache under the 1-million-token limit while still providing up-to-date answers from the vector store.
Cache Lifecycle Management: Listing, Updating and Deleting
Production systems must manage multiple caches for different product lines or language versions. Use these administrative functions:
export async function listAllCaches() {
const caches = await genAI.listCachedContents();
return caches;
}
export async function deleteCache(cacheName: string) {
await genAI.deleteCachedContent(cacheName);
console.log(`Deleted cache ${cacheName}`);
}
// Example scheduled cleanup
export async function cleanupExpiredCaches() {
const caches = await genAI.listCachedContents();
const now = new Date();
for (const cache of caches) {
if (cache.expiration && new Date(cache.expiration) < now) {
await deleteCache(cache.name);
}
}
}
Run cleanupExpiredCaches via a cron job every hour. The listCachedContents method accepts pagination parameters pageSize and pageToken for accounts with hundreds of caches.
Atomic Cache Switching Pattern
Maintain two cache names in your configuration store: blue and green. After validating a newly created cache against a test suite of 50 questions, update a Redis key atomically from one cache name to the other. This achieves zero-downtime updates when documentation changes.
Multimodal Caching for Video and Audio Content
Cache a 45-minute product demonstration video together with its transcript and slide deck. The creation call accepts multiple file references in one cache:
const videoCache = await genAI.createCachedContent({
model: flashModelName,
displayName: "Product Demo Video v2",
systemInstruction: "Answer questions about the demo video, UI flows and spoken explanations.",
contents: [{
role: "user",
parts: [
{ fileData: { mimeType: "video/mp4", fileUri: "gs://demo-bucket/onboarding-v2.mp4" } },
{ fileData: { mimeType: "application/pdf", fileUri: "gs://demo-bucket/slides.pdf" } },
{ text: "Full transcript with timestamps..." }
]
}],
ttlSeconds: 604800,
});
Video files up to approximately one hour are supported. The cache stores extracted frames and audio transcription internally. Subsequent text questions about visual details no longer reprocess the video, saving both time and cost. Combine this cache with the hybrid RAG pattern above to answer questions that reference both the video and the latest customer tickets stored in the vector index.
Comprehensive Error Handling and Recovery Strategies
Wrap every cache operation in a retry loop that distinguishes between transient and permanent failures. Common errors include RESOURCE_EXHAUSTED during high creation load, INVALID_ARGUMENT for oversized content, and NOT_FOUND for expired caches.
async function robustCachedCall<T>(
operation: () => Promise<T>,
recreateCache: () => Promise<string>
): Promise<T> {
try {
return await operation();
} catch (err: any) {
if (err.status === 404 || err.message?.includes("NOT_FOUND")) {
const newCache = await recreateCache();
// update stored cache name
return await operation();
}
if (err.status === 429) {
await new Promise(r => setTimeout(r, 2000));
return await operation();
}
throw err;
}
}
Use this wrapper around both cache creation and inference calls. Log the full error object including err.details to Cloud Logging for later analysis. Set up alerts for any cache recreation that takes longer than 180 seconds.
Observability, Monitoring and Benchmarking
Instrument the cache layer with OpenTelemetry spans. Record custom metrics for cache hit ratio, token usage split, and end-to-end latency. Example metric names: gemini.cache.token.cached, gemini.cache.latency.ms.
Benchmark before and after caching using Artillery:
artillery run support-load-test.yml
The test YAML file should contain 50 concurrent users repeating the same five questions for 5 minutes. Compare the tokens-per-second and dollar cost calculated from usage metadata. Typical production deployments observe 60-75% reduction in input token cost for workloads where the same documentation is queried more than 30 times per cache lifetime.
Store usage metadata in a time-series database such as Prometheus. Create a Grafana dashboard showing cache age versus average latency. Rising latency often indicates that the cache is near expiration and should be refreshed.
Security, Compliance and Data Classification
Never place personally identifiable information, payment details or confidential source code into a cache. Classify all documents before caching using an automated scanner that rejects files containing patterns matching credit card numbers or internal API keys. The cached content is stored encrypted at rest by Google but is accessible to any application that possesses the cache name. Treat cache names as sensitive secrets and rotate them on any suspected leak.
For SOC2 or HIPAA environments, confirm that Google’s cache storage meets the required compliance standards for your industry. Use separate projects and API keys for caches containing different sensitivity levels. Implement access control lists on the Cloud Storage buckets so that only the cache creation service account can read the original files.
Production Deployment Checklist and Migration Guide
- Pin exact SDK and model versions in package.json and cache creation calls.
- Store active cache names in Redis with a 10-second TTL on the lookup key to force refresh on expiry.
- Implement the
robustCachedCallwrapper on every inference path. - Add Prometheus metrics for cache creation duration, hit ratio and token cost.
- Schedule nightly validation of cache answers against a golden dataset of 100 question-answer pairs.
- Document the exact token count of each cache in an internal wiki.
- Provide a rollback procedure that switches back to a previous cache name stored in version control.
- Test the complete cold-start scenario where no cache exists yet.
- Monitor Google Cloud billing daily for the first week after enabling caching to confirm expected savings.
- Train the team on the difference between cachedContentTokenCount and promptTokenCount when calculating costs.
Migration from a pure vector-RAG system involves extracting the static portions of your prompt templates into a new cached content object, updating the inference call sites to use getGenerativeModelFromCachedContent, and adjusting cost dashboards to include the new metadata fields. The migration can be done incrementally by product area, maintaining two parallel code paths behind a feature flag until confidence in the cached system is established.
These patterns, when applied together, allow development teams to run high-volume long-context applications at a fraction of the previous token cost while preserving answer quality and adding deterministic behavior through immutable reference material. The official SDK methods remain stable across minor version updates, enabling reliable production use once the cache lifecycle automation is in place.
