llmnet.nl • API & Aggregation

Caching LLM Responses: Faster and Cheaper

Architectural strategies to reduce latency and drastically lower token costs through intelligent caching layers.

Why Caching in LLM Infrastructure?

Large Language Models (LLMs) are computationally intensive and inherently come with high Time-to-First-Token (TTFT) and substantial API costs per thousand tokens. In enterprise environments or high-traffic applications, repeatedly processing identical or highly similar user queries results in unnecessary waste of compute and capital.

By adding an intelligent caching layer in front of the LLM aggregation proxy, we intercept redundant requests immediately. This provides two direct benefits:

Key Insight: Caching transforms static or repetitive instruction streams from expensive real-time inference into virtually cost-free memory lookups.

Prompt Caching vs. Response Caching

Within LLM architectures, we distinguish between two fundamental caching mechanisms that complement each other perfectly:

1. Prompt Caching (Context Caching)

Focuses on reusing large, static system prompts, documents, or codebase injections (RAG) in the memory of the provider or gateway.

  • How it works: Stores the Key-Value (KV) states of the prompt.
  • Benefit: Super-fast processing of long contexts without redundant computing power.
  • Ideal for: Large system prompts and document-analyzing agents.

2. Response Caching (Semantic & Exact)

Stores the complete output of the model in an external store (such as Redis) based on the input hash or semantic similarity.

  • How it works: Maps Hash(Prompt + Parameters) to the generated string.
  • Benefit: Complete bypass of the LLM API for identical or similar queries.
  • Ideal for: Frequently asked questions, product descriptions, and standard code generation.

Architecture & Pseudocode

A robust API gateway implements a layered strategy. First, it checks if there is an exact match in the response cache. If not, it checks whether prompt caching can be applied to the context before calling the upstream LLM.

// Pseudocode for API Gateway Cache Flow
function handleLLMRequest(incomingRequest) {
// Step 1: Generate deterministic hash of prompt and model configuration
const cacheKey = generateSHA256(incomingRequest.prompt + incomingRequest.model);

// Step 2: Check Response Cache (e.g., Redis)
const cachedResponse = RedisCache.get(cacheKey);
if (cachedResponse && !isExpired(cachedResponse)) {
return {
source: "response_cache",
latency_ms: 12,
data: cachedResponse.output
};
}

// Step 3: Check if Prompt Caching is possible (KV cache at provider)
let optimizedPayload = incomingRequest.payload;
if (hasStaticSystemPrompt(incomingRequest)) {
optimizedPayload = attachPromptCacheHeaders(incomingRequest);
}

// Step 4: Upstream LLM Call (Aggregator)
const startTime = getCurrentTimestamp();
const llmResponse = UpstreamLLM.complete(optimizedPayload);
const latency = getCurrentTimestamp() - startTime;

// Step 5: Store result in cache for future queries
RedisCache.set(cacheKey, {
output: llmResponse.text,
timestamp: getCurrentTimestamp()
}, TTL_SECONDS);

return {
source: "llm_upstream",
latency_ms: latency,
data: llmResponse.text
};
}

Cache Invalidation and Semantic Caching

The biggest danger of caching with LLMs is outdated or incorrect information. Because users rarely use the exact same phrasing, traditional string matching often falls short.

When to Cache and When Not to?

Not every LLM interaction is suitable for caching. A comparison of use cases:

✅ When to Cache

  • FAQs and customer service bots with a fixed knowledge base.
  • Standard code syntax and boilerplate generation.
  • Repetitive data extraction and classification tasks.
  • Long system prompts that are identical for every session.

❌ When Not to Cache

  • Real-time data queries (stock status, live exchange rates).
  • Highly personalized contexts and unique user data.
  • Creative brainstorming where variation in output is desired (high temperature).
  • Sensitive PII data where privacy risks are associated with persistent storage.