Semantic Cache Architecture for Next.js App Router
Production TypeScript architecture blueprint for embedding-based semantic caching in Next.js App Router with Upstash Redis Vector.
Why Exact-String Caching Fails in AI Applications
Exact-string caching misses identical user queries phrased with slight differences in punctuation, casing, or word order. Vector semantic caching compares query intent using high-dimensional cosine similarity, returning cached answers in under 30 milliseconds.
Implementation Code & Script
Vector query route handler checking semantic similarity before calling the upstream model.
import { NextRequest, NextResponse } from 'next/server';
import { Index } from '@upstash/vector';
const vectorIndex = new Index({
url: process.env.UPSTASH_VECTOR_REST_URL!,
token: process.env.UPSTASH_VECTOR_REST_TOKEN!,
});
export async function POST(req: NextRequest) {
const { prompt } = await req.json();
// 1. Query vector index for semantically similar cached responses
const results = await vectorIndex.query({
data: prompt,
topK: 1,
includeMetadata: true,
});
const bestMatch = results[0];
// Cosine distance threshold: score > 0.92 indicates near-identical intent
if (bestMatch && bestMatch.score > 0.92 && bestMatch.metadata?.response) {
return NextResponse.json({
cached: true,
score: bestMatch.score,
response: bestMatch.metadata.response,
});
}
// 2. Generate new response from upstream LLM if cache missed
const upstreamResponse = "Generated response from LLM...";
// 3. Upsert response to vector cache
await vectorIndex.upsert({
id: 'cache_' + Date.now(),
data: prompt,
metadata: { response: upstreamResponse, timestamp: Date.now() },
});
return NextResponse.json({ cached: false, response: upstreamResponse });
}How to cite and attribute this tool
MIT LicenceThis resource is free, open and un-gated under the MIT Open Source Licence. You are encouraged to use, integrate and cite it with attribution:
Geraghty, G. (2026). Semantic Cache Architecture for Next.js App Router. Gordon Geraghty Resources Hub. https://gordongeraghty.com/resources/ai-engineering/nextjs-semantic-cache-architecture
BibTeX Format
@misc{geraghty_nextjs_semantic_cache_architecture,
author = {Geraghty, Gordon},
title = {Semantic Cache Architecture for Next.js App Router},
year = {2026},
url = {https://gordongeraghty.com/resources/ai-engineering/nextjs-semantic-cache-architecture},
note = {Head of Performance, Empire Amplify}
}Changelog & Version History
v1.0.0Initial release of semantic caching route handler with vector cosine distance thresholds.