Skip to content
Blog

Cache Invalidation Patterns: When and How to Invalidate Cached Prompts in Google ADK

Master cache invalidation strategies for Gemini 3.8 and Google ADK prompt caches, avoiding stale state and optimizing cache hit rates.

Published on • December 5, 2026

AI Assistant

Context caching in Gemini 3.8 and Google ADK provides massive latency and cost benefits—slashing input token billing by up to 75% for prompts exceeding 32,768 tokens.

However, as Phil Karlton famously observed, there are only two hard things in Computer Science: cache invalidation and naming things.

In agentic systems, caching stale data is catastrophic: an agent might quote obsolete financial figures, retain deleted user permissions, or execute deprecated tool contracts. This guide explores explicit and implicit cache invalidation patterns in Google ADK.


How Gemini Context Caching Works Under the Hood

Gemini models utilize Deterministic Prefix Hashing:

[System Instructions] + [Tool Definitions] + [Cached Static Corpus] ──► Cached Prefix Block (Shared)
                                                                               │
                                                                               ▼
Turn 1: [Cached Prefix Block] + [User Turn 1] ────────────────────────► Hit! Fast & Cheap
Turn 2: [Cached Prefix Block] + [User Turn 1 + Assistant 1 + Turn 2] ─► Hit! Fast & Cheap

Modified Instruction (Invalidation):
[Modified System Inst.] + ... ────────────────────────────────────────► Cache Miss! (Re-computed)

If a single character changes within the cached prefix, the hash changes, triggering a complete cache miss and forcing full token reprocessing.


Invalidation Triggers in Production

When should an ADK cache be invalidated?

  1. Schema or Tool Signature Updates: A tool’s parameters or docstring change.
  2. System Instruction Deployment: Prompt version updates during a canary or blue/green rollout.
  3. Data Mutation in Underlying Storage: The underlying PDF, product catalog, or customer record is modified.
  4. Security & Permission Revocation: A user’s clearance level changes, requiring immediate expulsion of restricted knowledge.

Cache Invalidation Patterns

1. Time-to-Live (TTL) Rolling Expiry

The simplest strategy assigns a predictable TTL to cached resources. ADK allows configuring TTLs at creation time:

from google_adk.context import ContextCacheConfig
from datetime import timedelta

# Auto-expires after 30 minutes of inactivity
cache_config = ContextCacheConfig(
    ttl=timedelta(minutes=30),
    cache_contents=["gs://bucket/knowledge_corpus_v1.txt"]
)

2. Content-Hash Versioned Cache Keys

Instead of relying on mutable identifiers, compute a cryptographic digest (SHA-256) over the cached content. The agent references the hash directly. When data changes, the hash changes automatically, creating a clean new cache without race conditions:

import hashlib
from typing import List

def compute_cache_fingerprint(system_prompt: str, tool_schemas: List[dict], corpus_text: str) -> str:
    hasher = hashlib.sha256()
    hasher.update(system_prompt.encode("utf-8"))
    for tool in sorted(tool_schemas, key=lambda x: x["name"]):
        hasher.update(str(tool).encode("utf-8"))
    hasher.update(corpus_text.encode("utf-8"))
    return f"cache_v2_{hasher.hexdigest()[:16]}"

3. Explicit Eviction via Webhooks / Event Bus

When an enterprise database records an update, a cloud event (e.g., Google Cloud Pub/Sub) triggers an eviction function that explicitly deletes the cached resource from Vertex AI:

from google.genai import Client

async def invalidate_cached_resource(cache_resource_name: str):
    """Explicitly deletes the cache handle from Gemini context servers."""
    client = Client()
    try:
        await client.caches.delete(name=cache_resource_name)
        print(f"Successfully evicted cache: {cache_resource_name}")
    except Exception as e:
        print(f"Error during explicit cache invalidation: {e}")

Prefix Layout Rules to Prevent Accidental Invalidation

A common bug in agent design is placing dynamic data ahead of static data in the prompt:

BAD (Breaks Cache on every turn):
[Dynamic Date: 2026-12-05 10:45:12] ──► [System Instructions] ──► [Static Knowledge Base]
(Result: Cache missed 100% of the time)

GOOD (Preserves Cache Prefix):
[Static System Instructions] ──► [Tool Definitions] ──► [Static Knowledge Base] ──► [Dynamic Turn Data]
(Result: Cache hits 95%+ of the time)

Rule: Keep all invariant tokens strictly at the beginning of the context stream. Dynamic variables (timestamps, user IDs, current turn parameters) must always appear at the end.


Monitoring Cache Hit Ratios

Implement observability logging in your ADK Runner hooks to track cache hits:

def log_cache_metrics(event):
    metadata = getattr(event, "usage_metadata", None)
    if metadata:
        total = metadata.total_token_count
        cached = getattr(metadata, "cached_content_token_count", 0)
        hit_ratio = (cached / total) * 100 if total > 0 else 0
        print(f"Turn Metrics: Total={total}, Cached={cached} ({hit_ratio:.1f}% hit rate)")

Conclusion

Context caching transforms the unit economics of autonomous agents, but requires deliberate invalidation engineering. By structuring prompt prefixes immutably, adopting content-hash keys, and implementing explicit webhook-driven eviction, your ADK agents remain both fast and strictly up to date.