Agent Caching Strategies

Production-grade guide to agent caching strategies covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Agent caching strategies are the systematic approaches to reducing latency, minimizing redundant computation, and improving reliability by storing and reusing agent outputs, intermediate states, and context across invocations. They matter when agents operate in distributed environments with high-latency backends, perform expensive computations, or serve high-throughput workloads—especially when the same or similar inputs recur frequently.

Caching at the Input-Output Boundary

When an agent receives a request, it often processes a payload that involves multiple steps: parsing, external API calls, database queries, and logic execution. Caching the result of this entire pipeline is the most direct win.

The agent receives a POST /api/agent/run request with a JSON body:

{
  "input": "Generate a summary of the quarterly report for Q3 2024.",
  "context": {
    "project": "alpha-2024",
    "user_id": "u-12345"
  },
  "options": {
    "format": "markdown",
    "include_tables": true
  }
}

The agent computes a result, returns it, and stores the full response in a cache. The next time the same input arrives, the agent checks the cache before executing the full pipeline.

To implement this, the agent uses a cache key derived from the input, context, and options. The key is a canonical representation of the request, typically a hash of the JSON body, with a predictable structure:

import hashlib
import json

def compute_cache_key(request: dict) -> str:
    # Sort keys to ensure consistent hashing
    sorted_request = json.dumps(request, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(sorted_request.encode()).hexdigest()

The cache is accessed via a standard interface: a key-value store supporting get(key) and set(key, value, ttl=seconds) operations.

On receiving a request, the agent first attempts to retrieve a cached result:

def handle_request(request: dict):
    cache_key = compute_cache_key(request)
    
    cached_result = cache.get(cache_key)
    if cached_result is not None:
        return cached_result  # Serve from cache without computation

    # Compute result from scratch
    result = perform_computation(request)
    
    # Store in cache with a TTL of 3600 seconds (1 hour)
    cache.set(cache_key, result, ttl=3600)
    
    return result

Cache Miss and Cache Hit Semantics

A cache miss occurs when the cache has no entry for a given key. The agent proceeds with full computation, and the result is stored in the cache. A cache hit skips computation entirely.

The key challenge is cache invalidation: when to expire or invalidate a cached entry. The simplest strategy is time-to-live (TTL), where entries are automatically expired after a fixed duration.

A common failure mode is cache stampede: multiple agents simultaneously miss the cache for a popular input, leading to many concurrent recomputations of the same result. The solution is cache warming: pre-populating the cache with likely inputs, often via background jobs or periodic scans.

Caching Intermediate States

When a computation spans multiple steps, caching intermediate results can reduce latency and enable incremental updates.

Consider an agent that processes a document through the following stages:

  1. Text extraction (OCR and parsing)
  2. Named entity recognition (NER)
  3. Summarization
  4. Metadata tagging

Each stage produces a structured output that can be reused.

The agent stores outputs in a hierarchical structure using a key prefixing scheme. For example:

cache:
  - doc:12345:ocr
  - doc:12345:ner
  - doc:12345:summary
  - doc:12345:tags

The agent checks for cached outputs at each stage:

def process_document(doc_id: str):
    # Stage 1: OCR
    ocr_result = cache.get(f"doc:{doc_id}:ocr")
    if ocr_result is None:
        ocr_result = run_ocr(doc_id)
        cache.set(f"doc:{doc_id}:ocr", ocr_result, ttl=86400)

    # Stage 2: NER
    ner_result = cache.get(f"doc:{doc_id}:ner")
    if ner_result is None:
        ner_result = run_ner(ocr_result)
        cache.set(f"doc:{doc_id}:ner", ner_result, ttl=43200)

    # Stage 3: Summarization
    summary_result = cache.get(f"doc:{doc_id}:summary")
    if summary_result is None:
        summary_result = run_summarization(ner_result)
        cache.set(f"doc:{doc_id}:summary", summary_result, ttl=7200)

    # Stage 4: Tagging
    tags_result = cache.get(f"doc:{doc_id}:tags")
    if tags_result is None:
        tags_result = run_tagging(summary_result)
        cache.set(f"doc:{doc_id}:tags", tags_result, ttl=172800)

    return {
        "summary": summary_result,
        "tags": tags_result,
        "processed_at": time.time()
    }

Failure Modes

To mitigate, the agent uses write-through caching: after computing an intermediate result, it writes it to both the cache and a persistent store (e.g., a database). This ensures durability and allows for fallback when the cache is unavailable.

A critical decision is cache write strategy:

For agents that perform long-running computations, write-back is common. For agents that need consistency guarantees, write-through is preferred.

Context Window Caching

In agents using context windows (e.g., LLMs), the context is a sequence of tokens or messages that the model uses to infer outputs. Caching portions of this context can dramatically reduce latency.

The agent maintains a context cache keyed by a combination of:

The context is stored as a JSON array of message objects:

[
  {
    "role": "user",
    "content": "What’s the status of the new feature?",
    "timestamp": 1710000000
  },
  {
    "role": "assistant",
    "content": "The feature is in testing phase with 12 test cases passed.",
    "timestamp": 1710000050
  }
]

The cache key is a hash of the agent identity, task ID, and window size:

def context_cache_key(agent_id: str, task_id: str, window_size: int) -> str:
    return f"ctx:{agent_id}:{task_id}:{window_size}"

When an agent receives a new message, it:

  1. Retrieves the cached context.
  2. Appends the new message.
  3. Computes the new context window (e.g., last window_size messages).
  4. Stores the updated context in the cache.
def add_message_to_context(agent_id: str, task_id: str, message: dict, window_size: int):
    key = context_cache_key(agent_id, task_id, window_size)
    
    context = cache.get(key)
    if context is None:
        context = []
    
    # Append new message
    context.append(message)
    
    # Trim to window size
    if len(context) > window_size:
        context = context[-window_size:]
    
    # Store updated context
    cache.set(key, context, ttl=3600)
    
    return context

Context Cache Invalidation

The cache is invalidated when:

A common failure is context drift: the cache holds a context that no longer reflects the current state of the task. This happens when agents process messages out of order or when multiple agents update the same context.

To detect drift, the agent can store a context version with each context entry, and compare it to a known version. If the version is outdated, the agent recomputes the context from the ground up.

Cache Warmers and Eviction Policies

Caching is only effective when the cache is populated with likely requests. Cache warmers are background jobs that populate the cache in advance.

A typical warmer job runs every 15 minutes and:

The warmer uses curl to hit the agent API:

#!/bin/bash


for input in $(get-top-inputs --last 24h --limit 500); do
    key=$(echo "$input" | jq -c --sort-keys . | sha256sum | cut -d' ' -f1)
    
    # Check if already cached
    if ! curl -s -f -H "Accept: application/json" \
        "http://cache-service:6379/get?key=$key" > /dev/null; then
        
        # Trigger agent to compute and store
        curl -X POST http://agent-api:8080/api/agent/run \
            -H "Content-Type: application/json" \
            -d "$input"
    fi
done

Cache Eviction Policies

When the cache fills up, it must evict old entries. The most common policy is Least Recently Used (LRU), where the least recently accessed entries are removed first.

An agent can configure eviction via a cache.eviction setting:

cache:
  eviction: lru
  max_entries: 100000
  ttl: 3600
  warmup_interval: 900

A subtle failure is cache thrashing: entries are constantly evicted and reloaded due to high access variability. The solution is adaptive LRU, where the cache tracks access frequency and uses a hybrid of LRU and LFU (Least Frequently Used).

Another failure mode is cache pollution: entries are loaded into cache but rarely accessed again. This is common in warmers that pre-load data with low locality.

To reduce pollution, agents use cache metadata to track access patterns:

{
  "key": "doc:12345:summary",
  "value": "Summary of Q3 2024 report...",
  "access_count": 42,
  "last_accessed": 1710000000,
  "created_at": 1709900000
}

The agent can then prioritize entries for eviction based on both access frequency and recency.

Error Handling and Observability

Caching introduces new failure modes:

The agent logs cache operations with structured metadata:

{
  "event": "cache.hit",
  "key": "doc:12345:summary",
  "timestamp": 1710000000,
  "agent_id": "agent-01",
  "duration_ms": 12
}

A common error is cache miss with no fallback. The agent fails to compute the result and returns an error, but the cache is not updated. This leads to cold cache and repeated computation.

A robust agent always updates the cache on both success and failure:

def handle_request(request: dict):
    cache_key = compute_cache_key(request)
    
    cached_result = cache.get(cache_key)
    if cached_result is not None:
        return cached_result  # Serve from cache

    try:
        result = perform_computation(request)
        cache.set(cache_key, result, ttl=3600)
        return result
    except Exception as e:
        # Log error
        logger.error(f"Cache miss, failed to compute: {e}")
        # Store error in cache as fallback
        cache.set(cache_key, {"error": str(e), "computed": False}, ttl=1800)
        raise

Summary

Agent caching strategies are essential for reducing latency, avoiding redundant computation, and increasing reliability. They begin with simple input-output caching and evolve into layered systems that cache intermediate states, manage context windows, and proactively warm the cache. Key decisions include cache key design, TTL and eviction policies, write strategies, and error handling. The most subtle failures arise from cache inconsistency, stale data, and unmanaged warmers—each requiring explicit configuration and monitoring.

This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.