Caching Tool Responses to Eliminate Duplicate Expensive API Calls
How to eliminate redundant API calls and cut agent latency by implementing deterministic tool caching with in-memory LRUs, Redis backends, and cache-busting keys.
Published on • November 28, 2026
AI Assistant

Agents frequently make redundant inquiries during multi-turn planning. When exploring a research question or validating user inputs across multiple steps, an agent might request exchange rates, user profile data, or product catalog schemas repeatedly. If each check executes a live network call, latency accumulates and API bills rise. Caching tool responses at the tool layer ensures idempotent queries settle in sub-millisecond time.
This tutorial covers cache key generation, distinguishing immutable reference queries from volatile state mutations, implementing local in-memory LRU stores, and scaling to distributed Redis caches across multi-worker ADK deployments.
When to cache: safe vs volatile tools
Not all tools can or should be cached:
| Tool category | Idempotency | Cache safety | Recommended TTL | Example |
|---|---|---|---|---|
| Static Reference | Completely safe | High | 12 to 24 hours | Product catalog taxonomy, postal codes |
| Read-Only Volatile | Semi-idempotent | Conditional | 30 to 300 seconds | Weather conditions, currency exchange |
| Session Context | Read-only per user | High within session | Session lifespan | Account balance, user permissions |
| State Mutations | Non-idempotent | NEVER CACHE | 0s (Cache buster) | Payment charges, database writes, emails |
Mutations must never return cached results—they must execute every time and invalidate related read caches.
Generating stable cache keys
A tool cache key must deterministically represent the function identity and its arguments, independent of parameter ordering in the dictionary:
import hashlib
import json
def make_tool_cache_key(tool_name: str, args: dict, tenant_id: str | None = None) -> str:
"""Build a deterministic SHA256 cache key from tool name and arguments."""
# Sort keys to ensure {"a": 1, "b": 2} matches {"b": 2, "a": 1}
normalized_json = json.dumps(args, sort_keys=True, separators=(",", ":"))
raw_key = f"{tenant_id or 'global'}:{tool_name}:{normalized_json}"
return f"toolcache:{hashlib.sha256(raw_key.encode('utf-8')).hexdigest()}"
Sorting keys avoids cache misses caused by arbitrary JSON serialization orders produced across different LLM turns.
In-memory caching with TTLCache
For lightweight single-instance ADK agents, an in-memory TTL cache from cachetools avoids external infrastructure dependencies:
from cachetools import TTLCache
from google.adk.tools import ToolContext
# Cache up to 1000 items with a 5-minute time-to-live
GEO_CACHE = TTLCache(maxsize=1000, ttl=300)
async def lookup_postal_code(postal_code: str, ctx: ToolContext) -> dict:
"""Look up district and city details for a given postal code.
Args:
postal_code (str): 5-digit ZIP or postal code.
"""
key = make_tool_cache_key("lookup_postal_code", {"postal_code": postal_code})
if key in GEO_CACHE:
cached_result = GEO_CACHE[key]
cached_result["_cached"] = True
return cached_result
# Execute actual expensive network request
data = await external_geo_service.fetch(postal_code)
GEO_CACHE[key] = {
"status": "success",
"city": data.city,
"region": data.region,
"country": data.country
}
return GEO_CACHE[key]
Distributed caching with Redis
In production agent deployments running behind load balancers on Cloud Run or Kubernetes, multiple agent replicas must share the same cache to avoid duplicate work:
import redis.asyncio as redis
import json
redis_client = redis.from_url("redis://localhost:6379/0", decode_responses=True)
async def query_company_financials(ticker: str, fiscal_year: int) -> dict:
"""Retrieve verified annual financial filings.
Args:
ticker (str): Stock ticker symbol, e.g., 'GOOGL'.
fiscal_year (int): Year of the filing, e.g., 2025.
"""
cache_key = make_tool_cache_key("query_financials", {"ticker": ticker.upper(), "year": fiscal_year})
# Check Redis cache
cached = await redis_client.get(cache_key)
if cached:
payload = json.loads(cached)
payload["_source"] = "redis_cache"
return payload
# Real upstream fetch
filing = await sec_edgar_client.get_filing(ticker, fiscal_year)
result = {
"status": "success",
"ticker": ticker.upper(),
"revenue_usd": filing.revenue,
"net_income_usd": filing.net_income
}
# Store with 24-hour expiration (86400 seconds)
await redis_client.setex(cache_key, 86400, json.dumps(result))
return result
Cache invalidation on mutation
When an agent executes an update action—such as updating customer contact details—it must proactively purge any read caches that depend on the modified record:
async def update_customer_email(customer_id: str, new_email: str) -> dict:
"""Update a customer's registered email address."""
await crm_client.save_email(customer_id, new_email)
# Evict corresponding profile cache
profile_key = make_tool_cache_key("get_customer_profile", {"customer_id": customer_id})
await redis_client.delete(profile_key)
return {"status": "success", "customer_id": customer_id, "updated": True}
Takeaways
- Distinguish static reference tools (safe to cache for hours) from mutation tools (must never be cached).
- Normalize argument dictionaries before hashing to prevent spurious cache misses due to key order.
- In-memory TTL caches work well for local tools; distributed Redis backends prevent duplicate work across load-balanced workers.
- Add an explicit metadata key (
_cached: true) in development to verify cache hits during testing. - Pair mutation tools with explicit cache invalidation logic to prevent agents from acting on stale data.