Here is a harsh reality of scaling AI applications:
Humans are incredibly predictable.
If you launch an AI feature to thousands of users, I guarantee that dozens of them are going to ask the exact same questions, prompt the exact same workflows, and request the exact same summaries.
And if you don’t have a caching strategy in place?
You are paying your LLM provider to generate the exact same answer, over and over again.
Imagine running a restaurant and cooking a brand new meal every time a customer asks to see the menu. That is exactly what you are doing when you route every single user query directly to the flagship models.
Today, I am going to show you how to intercept those duplicate requests before they ever hit the API.
We are going to build a multi-layered caching infrastructure that serves instant answers and drops your token consumption to zero.
Let’s get into it.

Why Middleware is Mandatory
The biggest mistake I see developers make is calling the LLM directly from their frontend client or writing a basic, un-optimized serverless function that acts as a simple pass-through.
This is a massive architectural flaw.
You need a middleware layer.
A middleware layer sits between your user and the LLM API. It acts as a gatekeeper. When a request comes in, the middleware pauses and asks: “Have we seen this exact request before?”
If the answer is no, it passes the request to the LLM, pays the token fee, and saves the final response.
If the answer is yes, it instantly returns the saved response. No API call. No latency. No cost.
Building this layer is the absolute most critical step in reducing LLM token usage at the infrastructure level.
But to do it right, you need two distinct layers of caching.
Layer 1: Exact Match Caching
The first layer is the low-hanging fruit. It catches exact duplicate strings.
If User A types: “Summarize the Q3 financial report.”
And User B types: “Summarize the Q3 financial report.”
Your system should intercept User B’s request instantly.
For this, we use Redis. It is an in-memory data store that is blazingly fast.
Here is exactly how you set this up in a modern Node.js or Next.js backend:
First, when a query comes in, you don’t use the raw text as the cache key. You hash the incoming prompt using SHA-256. This creates a short, unique identifier for that specific string of text.
JavaScript
import crypto from 'crypto';
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
async function generateResponse(userPrompt) {
// 1. Hash the incoming prompt
const promptHash = crypto.createHash('sha256').update(userPrompt).digest('hex');
const cacheKey = `llm_cache:${promptHash}`;
// 2. Check Redis for an exact match
const cachedAnswer = await redis.get(cacheKey);
if (cachedAnswer) {
console.log("Cache hit! Serving for free.");
return cachedAnswer;
}
// 3. If no cache, call the expensive LLM
console.log("Cache miss. Calling flagship model...");
const llmResponse = await callExpensiveLLM(userPrompt);
// 4. Save the response in Redis for the next user
await redis.set(cacheKey, llmResponse);
return llmResponse;
}
This exact-match infrastructure takes about ten minutes to set up.
It intercepts repetitive tasks perfectly.
But there is a glaring problem. What happens if User C types: “Please summarize the Q3 financial report for me.”
The string is different. The hash will be different. Redis will report a cache miss, and you will pay for the API call, even though the intent is exactly the same.
That is where we bring out the heavy artillery.
Layer 2: Semantic Caching
Exact match caching cares about characters. Semantic caching cares about meaning.
To catch variations in phrasing, we have to move past simple text strings and step into the world of vector embeddings and relational databases.
Here is the strategy:
Instead of just saving the text of the user’s prompt, we use a cheap, fast embedding model to convert the user’s prompt into a mathematical vector.
Then, we store that vector alongside the AI’s response in a PostgreSQL database using an extension like pgvector.
When a new query comes in, the workflow looks like this:
-
Embed the new user query.
-
Run a similarity search (cosine distance) against your PostgreSQL database.
-
Check the similarity score.
-
If the new query is a 95% mathematical match to an old query, serve the old response.
If you are using Prisma as your ORM alongside a powerful database platform like Supabase, executing this semantic search is incredibly clean.
JavaScript
// Example: Semantic Caching with Prisma and pgvector
async function semanticCacheCheck(userPrompt) {
// 1. Convert the prompt to a vector (extremely cheap)
const queryEmbedding = await generateEmbedding(userPrompt);
// 2. Query Postgres for semantically similar prompts
const similarCache = await prisma.$queryRaw`
SELECT response, 1 - (embedding <=> ${queryEmbedding}::vector) as similarity
FROM "SemanticCache"
WHERE 1 - (embedding <=> ${queryEmbedding}::vector) > 0.95
ORDER BY similarity DESC
LIMIT 1;
`;
if (similarCache.length > 0) {
return similarCache[0].response; // Serve cached answer
}
return null; // Cache miss, proceed to LLM
}
By setting the similarity threshold to 0.95, you ensure that the model only serves cached answers when the user’s intent is virtually identical to a previous query.
This completely eliminates the token waste caused by slight typos, extra pleasantries, or varied sentence structures.
Cache Invalidation Strategies
Now, you have a lightning-fast Redis layer and a deeply intelligent PostgreSQL semantic layer.
But we have to talk about stale data.
Language model outputs are often highly contextual based on time, live data, or current app state. If you cache an answer today, will it still be accurate next week?
If a user asks “What is my current account balance?” and you serve a cached answer from three days ago, you have a massive bug on your hands.
You must implement strict Cache Invalidation (TTL – Time to Live).
For dynamic data, your Redis keys should have a TTL of 5 to 15 minutes.
JavaScript
// Set cache to expire in 300 seconds (5 minutes)
await redis.set(cacheKey, llmResponse, 'EX', 300);
For static queries (like coding tutorials, documentation Q&A, or general knowledge), you can push the semantic cache TTL to 30 days or even longer.
The trick is segmenting your caches. Tag queries that rely on live user context and expire them aggressively. Tag general knowledge queries and let them live forever.
Final Thoughts
Implementing a two-tier caching architecture separates amateur AI projects from production-grade, highly profitable applications.
By stopping duplicate exact-match queries at the Redis layer, and catching semantically identical variations at the database layer, you insulate your API budget from unpredictable user behavior.
Stop paying the API toll twice. Build the middleware.

