---
title: "Google ADK: ContextCacheConfig in ADK — Reusing Prompts Across Repeated Runs"
date: "2026-12-04T08:51:58+07:00"
description: "Turn on ADK's ContextCacheConfig so repeated agent runs reuse cached prompt prefixes. Step-by-step setup, parameter tuning, and how to verify cache hits."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-context-cache-config.jpg"
alt: "Screenshot-style diagram of an ADK App with ContextCacheConfig reusing a cached prompt prefix across multiple agent runs"
tags: ['google-adk', 'caching', 'gemini', 'cost-optimization', 'app-config']
---

Every turn of your agent resends the same material: the system instruction, the tool schemas, the reference documents. On a research assistant with 4,000+ tokens of instructions and a dozen tools, that static prefix is billed in full on every single run — and re-transmitted over the network every time. Multiply by every user, every session, every retry, and the "small" prompt becomes the dominant line item.

ADK ships a direct answer: `ContextCacheConfig`, an App-level feature that caches request data with generative models (Gemini 2.0 and higher) and reuses it across runs. This tutorial configures it from scratch, explains every parameter, and — the part most teams skip — verifies the cache is actually hitting.

## Prerequisites

- ADK Python v1.15.0 or higher (when the feature landed)
- A Gemini 2.0+ model configured on your root agent
- A prompt large enough to matter: the reference sample uses 4,096+ tokens to clear typical thresholds

## 1. Understand what gets cached

When an agent runs repeatedly — multi-turn sessions, batch jobs, retries — the request prefix (tools, instructions, shared documents) is identical while only the newest user input changes. The Gemini API's caching bills matching prefix tokens at a steep discount: implicit caching is enabled by default on Gemini 2.5 and newer, with cached input tokens costing 90–95% less depending on model, plus a 4,096-token minimum input floor on Gemini 4 and Gemini 3 (2,048 on Gemini 2.5).

ADK's `ContextCacheConfig` layers *explicit* caching on top of that at the `App` level. The class is marked **experimental** — constructing one emits a warning in Python — and its settings apply to all agents within the App.

## 2. Configure the App

Caching is not an agent parameter; you wrap the agent in an `App` and attach the config:

```python
from google.adk import Agent
from google.adk.apps.app import App
from google.adk.agents.context_cache_config import ContextCacheConfig

root_agent = Agent(
    name="my_caching_agent",
    model="gemini-flash-latest",   # any Gemini 2.0+ model
    instruction="Answer using the attached policy handbook...",
)

# Create the app with context caching configuration
app = App(
    name="my-caching-agent-app",
    root_agent=root_agent,
    context_cache_config=ContextCacheConfig(
        min_tokens=2048,    # Minimum tokens to trigger caching
        ttl_seconds=600,    # Store for up to 10 minutes
        cache_intervals=5,  # Refresh after 5 uses
    ),
)
```

Then run the App through your normal runner setup. Everything downstream — sessions, events, callbacks — works unchanged; only the model-call layer consults the cache.

## 3. Know every knob

| Parameter | Type | Default | Rules | Purpose |
| --- | --- | --- | --- | --- |
| `min_tokens` | int | `0` | Compared against the **previous** request's prompt token count | Skip caching for prompts too small to pay off; the first request in a session is never cached |
| `ttl_seconds` | int | `1800` (30 min) | Must be `> 0` | How long cached content lives before refresh |
| `cache_intervals` | int | `10` | Must be `1`–`100` | Max uses of the same cached content before it expires, independent of TTL |
| `create_http_options` | `HttpOptions` | none | Python and Kotlin only | Timeout for the cache-creation call; on timeout, the request proceeds uncached |

Tuning guidance:

- **Interactive chat:** `ttl_seconds=600`, `cache_intervals=5` — conversations pause often but rarely last hours (the sample uses exactly this for "10-minute research sessions").
- **Batch / repeated identical runs:** higher `cache_intervals`, shorter TTL — you want frequent refresh, not longevity.
- **Small prompts:** leave `min_tokens` low but expect few hits; below the model's floor (4,096 on Gemini 4/3, 2,048 on Gemini 2.5) no cache can form regardless of configuration.

## 4. Verify the cache is being used

A configuration you cannot measure is a configuration you will silently regress. Two checks, from the official `cache_analysis` sample:

**Run the experiment harness.** The sample ships a script that compares cached versus uncached runs and averages repeats:

```bash
# Explicit caching + implicit caching on 2.5 models; explicit vs. uncached on others
python run_cache_experiments.py gemini-2.5-flash --output results.json

# Average across multiple iterations
python run_cache_experiments.py gemini-2.5-flash --repeat 3 --output averaged_results.json
```

Expected results from the sample: simple text agents typically see **30–70% latency reduction** with caching, and up to **~75% lower input token cost** for cached content.

**Read the usage metadata.** Successful cache hits show up as non-zero cached-token counts in the response usage metadata:

```python
# Cache hits are indicated by non-zero cached_content_token_count values.
# If it is always 0, check the troubleshooting list below.
cached = response.usage_metadata.cached_content_token_count or 0
print(f"Cached tokens: {cached}")
```

When `cached_content_token_count` stays at zero, the sample's troubleshooting order is:

1. Model name mismatch (must match exactly, e.g. `gemini-2.5-flash`)
2. Prompt + instructions below the `min_tokens` threshold
3. Config passed as a standalone agent instead of through the `App` wrapper

At runtime, events backed by an LLM response can carry `CacheMetadata` describing what the cache did: an **active cache** sets `cacheName`, `expireTime`, and `invocationsUsed`, while a **fingerprint-only** state (all three null) means ADK measured the cacheable prefix but no cache is in use — the first turn, a changed prefix, or a prefix below `min_tokens`.

## 5. Keep the prefix stable or the cache never hits

Caching only pays off if the prefix survives across runs. The Gemini caching rules map directly onto ADK code:

- **Freeze the `tools` array.** Adding, removing, or reordering non-deferred tools invalidates the system instruction and all history below it.
- **Keep `system_instruction` static.** No timestamps, UUIDs, or per-user values baked in — pass volatile metadata in the user message instead.
- **Hold `thinking_level` constant** within a session; it serializes first, so changing it busts 100% of the prefix.
- **For session-long instructions**, the ADK docs point to the `static_instruction` parameter as the companion feature — instructions used throughout a session belong there rather than in dynamically rebuilt prompts.

## 6. Layer it with the rest of the context stack

`ContextCacheConfig` does not replace compaction or memory — it sits beside them:

| Mechanism | Handles | Config surface |
| --- | --- | --- |
| `ContextCacheConfig` | Repeated identical prefixes across runs | App-level, this tutorial |
| `EventsCompactionConfig` | Unbounded history growth within a session | App-level (`token_threshold`, `event_retention_size`) |
| `MemoryService` + tools | Exact recall beyond the window | Runner-level (`preload_memory`, `load_memory`) |

A production agent typically runs all three: compaction bounds the window, caching discounts the static prefix, and memory carries durable facts that neither should be trusted to preserve.

## Checklist

- [ ] ADK Python ≥ v1.15.0 with a Gemini 2.0+ model on the root agent
- [ ] `ContextCacheConfig` attached to the `App`, not passed as a standalone agent
- [ ] `min_tokens` set relative to the model's real floor (4,096 on Gemini 4/3)
- [ ] `ttl_seconds` > 0 and `cache_intervals` within 1–100, sized to traffic pattern
- [ ] `create_http_options` timeout set so a slow cache-creation call degrades to uncached, not to a hang
- [ ] Tools, `system_instruction`, and `thinking_level` byte-stable across runs
- [ ] `cached_content_token_count` (or `CacheMetadata`) monitored in production
- [ ] Experimented with `run_cache_experiments.py` before and after prompt changes
- [ ] Compaction and memory configured alongside caching for long sessions

## Conclusion

`ContextCacheConfig` turns ADK's most repetitive cost — resending identical instructions, tools, and reference material on every run — into a cached asset. Three parameters (`min_tokens`, `ttl_seconds`, `cache_intervals`) govern when caching kicks in, how long it lives, and how often it refreshes, and attaching it requires nothing more than moving your agent under an `App`.

The feature is only half the work. Cache hits depend on prefix stability, and a non-zero `cached_content_token_count` is the metric that proves the design survived contact with production. Configure it, freeze your prompt, measure the hits — then let the discount compound across every repeated run.

## References

- https://adk.dev/
- https://adk.dev/context/caching/
- https://ai.google.dev/gemini-api/docs/caching
- https://github.com/google/adk-python/tree/main/contributing/samples/context_management/cache_analysis
