adk-java icon indicating copy to clipboard operation
adk-java copied to clipboard

RFC: Context Caching Support for Java ADK

Open ruslan-kurchenko opened this issue 1 year ago • 3 comments

Hey team! I've been working on a proposal for context caching in Java ADK, and I wanted to get your thoughts before moving forward. This is a critical feature for production deployments, especially for agents with large static instructions.

The Problem We're Solving

Right now, every single LLM request sends the complete instruction set - system instructions, agent instructions, tools, and conversation history. This becomes really expensive and slow when you have agents with large static instructions that never change.

Let me give you a concrete example from our healthcare support agent at K Health:

Current state (without caching):

Every request includes:
├─ HIPAA Guidelines: 5,000 tokens (STATIC - never changes)
├─ Scheduling Policies: 3,000 tokens (STATIC - rarely changes)
├─ Clinic Info: 2,000 tokens (STATIC - clinic-specific)
├─ Patient Context: 2,000 tokens (DYNAMIC - per patient)
└─ Conversation History: 3,000 tokens (DYNAMIC - grows)
═══════════════════════════════════════════════════════════════
Total: 15,000 tokens → $1.125 per request, 2-3s latency

We're re-processing 10,000 static tokens on EVERY request ❌

What we want (with caching):

Optimized request:
├─ Cache Reference: <cache_id> (10,000 tokens cached)
├─ Patient Context: 2,000 tokens
└─ Conversation History: 3,000 tokens
═══════════════════════════════════════════════════════════════
Total: 5,000 tokens → $0.562 per request, 1-1.5s latency

✅ 50% faster
✅ 50% cheaper

For real-time applications (like our Vapi voice integration), that 2-3 second delay is a dealbreaker. We need this to be competitive.

The Solution: Leverage Gemini's Caching API

Google recently released a Caching API that lets us cache static content on their side. We just need to integrate it properly into ADK.

Here's the high-level architecture I'm proposing:

graph TD
    subgraph "1. App Configuration"
        A[App with ContextCacheConfig] --> B[cacheIntervals: 10<br/>ttlSeconds: 1800<br/>minTokens: 1000]
    end

    subgraph "2. Request Processing"
        C[ContextCacheProcessor] --> D{Cache metadata<br/>in session?}
        D -->|No| E[Generate fingerprint]
        D -->|Yes| F{Valid?}
        F -->|Yes| G[Reuse cache]
        F -->|No| E
        E --> H[GeminiContextCacheManager<br/>createCache]
    end

    subgraph "3. API Layer"
        H --> I[Gemini Caching API]
        G --> J[LlmRequest with<br/>cachedContentId]
        J --> K[Gemini generateContent]
    end

    subgraph "4. Storage"
        L[BaseSessionService<br/>Redis/Firestore/InMemory] -.->|Read metadata| D
        G -.->|Store metadata| L
        H -.->|Store metadata| L
    end

    A --> C
    I --> G

    style A fill:#e1f5fe
    style C fill:#c8e6c9
    style H fill:#fff9c4
    style I fill:#ffccbc
    style L fill:#f3e5f5

Key Design Decisions

I've thought through a few critical design choices:

1. Stateless Cache Manager The cache manager doesn't keep any in-memory state. All metadata flows through session events. This is crucial for horizontal scaling - any pod can pick up where another left off. Works seamlessly with Redis, Firestore, or even InMemorySessionService for local dev.

2. App-Level Configuration (Python Parity) After looking at the Python implementation, they put ContextCacheConfig on the App, not on individual agents. Makes sense - caching is a deployment concern, not an agent concern. Let's match that.

3. Local Validation 99% of cache validations happen locally - we just check the fingerprint, expiration time, and invocation count. No API calls needed. Only create/delete operations hit the Gemini API.

4. RequestProcessor Integration This fits perfectly into our existing RequestProcessor pattern. We already have a pipeline for request processing - just add ContextCacheProcessor to it.

What We Need to Build

1. ContextCacheConfig (App-Level)

@AutoValue
public abstract class ContextCacheConfig {
  // Max invocations before we refresh the cache (prevents stale caches)
  public abstract int cacheIntervals();  // 1-100, default 10

  // How long the cache lives before Gemini deletes it
  public abstract int ttlSeconds();      // Min 300s, default 1800s (30 min)

  // Only cache requests above this token threshold
  public abstract int minTokens();       // 0+, default 0 (cache everything)

  public static Builder builder() {
    return new AutoValue_ContextCacheConfig.Builder()
        .cacheIntervals(10)
        .ttlSeconds(1800)
        .minTokens(0);
  }
}

This goes on the App class, not agents. Python does it this way too.

2. CacheMetadata (Two States)

@AutoValue
public abstract class CacheMetadata {
  // Full resource name (e.g., "cachedContents/abc123")
  public abstract Optional<String> cacheName();

  // When it expires (Unix timestamp)
  public abstract Optional<Long> expireTime();

  // SHA-256 hash for change detection
  public abstract String fingerprint();

  // How many times we've used this cache
  public abstract Optional<Integer> invocationsUsed();

  // How many contents are cached
  public abstract int contentsCount();

  // When we created it
  public abstract Optional<Long> createdAt();

  public boolean expireSoon() {
    // Check if expires within 2 minutes
  }

  public boolean isActiveCache() {
    return cacheName().isPresent();
  }
}

This has two states:

  • Active cache: Has a cacheName, fully populated
  • Fingerprint-only: Just has fingerprint for matching (before cache is created)

This matches Python's design exactly.

3. GeminiContextCacheManager (Stateless)

@Singleton
public class GeminiContextCacheManager {
  private final CachedContentServiceClient cacheClient;

  public Single<CacheMetadata> handleContextCaching(
      LlmRequest llmRequest,
      int cacheContentsCount) {
    // 1. Check if we have existing metadata from session
    // 2. Validate it locally (fingerprint, expiration, invocations)
    // 3. Create new cache if needed (via Gemini API)
    // 4. Return metadata to store in response event
  }

  public Completable deleteCache(String cacheName) {
    // Clean up expired caches
  }

  private String generateCacheFingerprint(
      LlmRequest request,
      int contentsCount) {
    // SHA-256 of systemInstruction + tools + contents
  }
}

Important: This is stateless. No ConcurrentHashMap of cache metadata. Everything flows through session events, which enables horizontal scaling.

4. ContextCacheProcessor

@Singleton
public class ContextCacheProcessor implements RequestProcessor {
  private final GeminiContextCacheManager cacheManager;

  @Override
  public Single<RequestProcessingResult> processRequest(
      InvocationContext context,
      LlmRequest request) {
    // 1. Check if app has ContextCacheConfig
    // 2. Retrieve latest CacheMetadata from session events
    // 3. Call cacheManager.handleContextCaching()
    // 4. Inject cachedContentId into LlmRequest
    // 5. Store updated metadata in response event
  }
}

This plugs into the existing BaseLlmFlow processor pipeline. Zero changes to agent execution logic.

5. Model Updates

We need to add a few fields:

App.java:

public abstract class App {
  public abstract Optional<ContextCacheConfig> contextCacheConfig();
}

LlmRequest.java:

public abstract class LlmRequest {
  @JsonProperty("cachedContentId")
  public abstract Optional<String> cachedContentId();

  public abstract Optional<CacheMetadata> cacheMetadata();
  public abstract Optional<ContextCacheConfig> cacheConfig();
}

Event.java:

public abstract class Event {
  public abstract Optional<CacheMetadata> cacheMetadata();
}

All Optional fields to maintain backward compatibility.

Horizontal Scaling Story

This is where the design really shines. By storing cache metadata in session events, we get multi-pod support for free.

Here's how it works:

sequenceDiagram
    participant LB as Load Balancer
    participant PA as Pod A
    participant PB as Pod B
    participant Redis as Redis/Firestore
    participant Gemini as Gemini API

    Note over LB,Gemini: Request #1 - New Session (Pod A)
    LB->>PA: User request (session-123)
    PA->>Redis: Read session events
    Redis-->>PA: No cache metadata
    PA->>PA: Generate fingerprint
    PA->>Redis: Store fingerprint-only metadata

    Note over LB,Gemini: Request #2 - Same Session (Pod B)
    LB->>PB: User request (session-123)
    PB->>Redis: Read session events
    Redis-->>PB: Found fingerprint-only metadata
    PB->>PB: Fingerprint matches!
    PB->>Gemini: Create cache (one-time cost)
    Gemini-->>PB: cache_name: cachedContents/abc123
    PB->>Redis: Store full CacheMetadata

    Note over LB,Gemini: Request #3+ - Any Pod
    LB->>PA: User request (session-123)
    PA->>Redis: Read session events
    Redis-->>PA: Found active cache metadata
    PA->>PA: Validate locally:<br/>✓ fingerprint matches<br/>✓ not expired<br/>✓ under invocation limit
    PA->>Gemini: generateContent(cachedContent=abc123)
    Gemini-->>PA: Fast response
    PA->>PA: Increment invocationsUsed
    PA->>Redis: Store updated metadata

Works with:

  • ✅ InMemorySessionService (dev)
  • ✅ Redis (production)
  • ✅ Firestore (GCP native)
  • ✅ Any custom implementation

No configuration needed. If you're already using Redis for sessions, caching just works across all pods.

Python Parity Checklist

I've carefully reviewed the Python ADK implementation to ensure we match their design:

Feature Python ADK Java ADK (This PR) Status
Config location App.context_cache_config App.contextCacheConfig() ✅ Match
Metadata fields cache_name, expire_time, fingerprint, invocations_used, contents_count, created_at Exact same (snake_case in JSON) ✅ Match
Two-state model Active cache vs fingerprint-only Same ✅ Match
Fingerprint SHA-256 of systemInstruction + tools + contents Same ✅ Match
Validation Local checks, no API calls Same ✅ Match
Storage Session events Same ✅ Match

Open Questions

I need your input on a few things:

1. Package Structure

Should we use com.google.adk.models.cache or com.google.adk.cache?

I'm leaning toward models.cache to keep cache models close to LlmRequest and Event.

2. Gemini API Client Dependency

We need com.google.ai.generativelanguage.v1beta.CachedContentServiceClient. Should we:

  • Add it as a direct dependency with <optional>true</optional>?
  • Require users to add it themselves?

I prefer the first option - make it easy, but optional so users without caching don't pay the dependency cost.

3. Metrics

Should CacheMetrics be:

  • Always enabled (no-op if Micrometer missing)?
  • Opt-in via config?

I vote for always-on with graceful degradation. Better observability by default.

4. Cache Storage Costs

Gemini charges for cache storage (~$1/million tokens/hour). Should we:

  • Document this clearly in Javadocs? (YES)
  • Add estimatedStorageCost() helper? (YES)
  • Warn if cache size exceeds threshold? (YES)

We need to be transparent about costs.

5. Breaking Changes

We're adding fields to Event and App. Using Optional everywhere should keep us backward compatible, but wanted to confirm this is okay for a 0.4.0 release.

Example Usage

Here's what it looks like for developers:

// Configure caching at app level
App app = App.builder()
    .agent(schedulingAgent)
    .contextCacheConfig(ContextCacheConfig.builder()
        .cacheIntervals(10)     // Refresh after 10 uses
        .ttlSeconds(3600)       // 1 hour cache lifetime
        .minTokens(1000)        // Only cache if >1000 tokens
        .build())
    .build();

// Run agent - caching happens automatically
Runner runner = new Runner(app, sessionService);
runner.runAsync(sessionId, "Schedule appointment for John Doe")
    .subscribe(event -> {
        if (event instanceof LlmResponse response) {
            response.cacheMetadata().ifPresent(metadata -> {
                System.out.println("Cache: " + metadata);
                // Output: Cache abc123: used 3 invocations,
                //         cached 150 contents, expires in 45.2min
            });
        }
    });

Zero manual cache management. It just works.

Why This Matters

For developers:

  • Set config once, forget about it
  • Works automatically with existing session infrastructure
  • Scales horizontally out of the box
  • Full observability with metrics

For production:

  • 50%+ latency improvement for cached agents
  • 70%+ cost reduction on cached content
  • Better UX for real-time apps (voice, chat)
  • Transparent cost tracking

Next Steps

If this looks good, I'll go ahead and submit the MR once ready and tested on our end.

Team, @Poggecci, let me know your thoughts, especially on the open questions!

References

  • Gemini Caching API: https://ai.google.dev/gemini-api/docs/caching
  • Python ADK: https://github.com/google/adk-python

ruslan-kurchenko avatar Oct 23 '25 13:10 ruslan-kurchenko

Hello, @Poggecci , any thoughts on this?

ruslan-kurchenko avatar Oct 24 '25 20:10 ruslan-kurchenko

Hey ruslan. Overall, I am super in favor of this proposal, and really appreciate you breaking down all these facets of this. The gains are tangible, and it would be good to have this. ADK-Python's context caching is still new and apparently has some issues (I haven't dug deeper into these), but at least the interface there and so this RFC comes at a good time.

Addressing your open questions:

  1. Package Structure Should we use com.google.adk.models.cache or com.google.adk.cache?

I agree that models.cache makes more sense.

  1. Gemini API Client Dependency We need com.google.ai.generativelanguage.v1beta.CachedContentServiceClient. Should we:

Let's just add the dependency. Caching is important enough to include in the core lib.

  1. Metrics Should CacheMetrics be:

Always enabled (no-op if Micrometer missing)? Opt-in via config?

Metrics should be always on with configuration options to extend/disable.

  1. Cache Storage Costs Gemini charges for cache storage (~$1/million tokens/hour). Should we:

Document this clearly in Javadocs? (YES) -> Agree Add estimatedStorageCost() helper? (YES) -> Agree Warn if cache size exceeds threshold? (YES) -> Agree We need to be transparent about costs. -> Agree

  1. Breaking Changes We're adding fields to Event and App. Using Optional everywhere should keep us backward compatible, but wanted to confirm this is okay for a 0.4.0 release.

Optional new fields sgtm. would be great addition for 0.4.0

Poggecci avatar Oct 24 '25 22:10 Poggecci

Closing this issue as this feature was successfully implemented in version 0.6.0. You can review the changes in the CHANGELOG and the corresponding commit.

hemasekhar-p avatar Jul 20 '26 14:07 hemasekhar-p