Why Semantic Caching Matters for Production AI
Large language model (LLM) and retrieval-augmented generation (RAG) applications often receive repeated or semantically similar questions. Without a caching mechanism, these requests can trigger unnecessary document retrieval, language model inference, token consumption, and processing delays.
Consider a customer support assistant answering:
- "What is your refund policy?"
- "How can I request a refund?"
- "What is the process for returning a product?"
Although these questions are phrased differently, some may be eligible to reuse the same answer when their meanings, permissions, and supporting document versions are compatible.
Traditional exact-match caching cannot reliably identify these relationships.
LongCache is EnDevSols' open-source Python semantic caching framework for LLM and RAG applications. It uses local embeddings, FAISS similarity search, scoped request identities, and configurable storage to reuse eligible responses while limiting unnecessary model execution.
This guide explores LongCache's architecture, features, Python API, storage backends, framework integrations, production safeguards, and practical applications.
What Is LongCache?
LongCache is a semantic similarity cache designed to reduce repeated LLM and RAG execution.
Instead of comparing incoming queries only by exact text, LongCache generates vector embeddings and searches for previously cached requests with similar meanings.
However, semantic similarity alone does not authorize reusing an answer.
LongCache also checks request identity, execution context, candidate verification, and response eligibility before returning a cached result.
Its architecture supports:
- Local embedding generation using BGE-small.
- FAISS-based semantic similarity search.
- SQLite, Redis, and in-memory storage.
- Request and tenant isolation.
- Configurable similarity thresholds and expiration.
- Synchronous and asynchronous Python operations.
- Concurrent request coordination through singleflight.
- Selected OpenAI and FastAPI integration paths.
LongCache is released as an open-source project under the MIT License.
Official repository: https://github.com/ENDEVSOLS/LongCache
Why Traditional Caching Is Not Enough for RAG
Traditional caching typically uses an exact request key.
For example:
cache = {
"What is your refund policy?":
"Customers can request a refund within 30 days."
}If the next user asks "How do I get a refund?", an exact-match cache treats it as a different request.
The application may execute the complete retrieval and language-model pipeline again.
Semantic caching addresses this limitation by comparing vector representations of queries.
Exact-Match Caching vs. Semantic Caching
| Capability | Exact-match cache | Semantic cache |
|---|---|---|
| Identical queries | Supported | Supported |
| Paraphrased queries | Usually missed | Candidate matching |
| Vector embeddings | Not required | Required |
| Similarity threshold | Not applicable | Configurable |
| Context isolation | Depends on implementation | Explicitly modeled in LongCache |
| Answer verification | Not inherent | Eligibility checks required |
Semantic caching can improve response efficiency, but it introduces a correctness challenge: two similar questions do not necessarily have interchangeable answers.
For production applications, cache reuse must depend on more than similarity.
LongCache Architecture: From User Query to Cached Response
LongCache separates request validation, embedding generation, vector search, response verification, and storage.
Its conceptual workflow is:
User Query → Request Context Validation → Local Embedding → FAISS Similarity Search → Candidate Verification → Cache Hit or Miss → Response

1. Request Context Validation
Before accessing cached responses, LongCache validates the request's trusted execution context.
The context can include tenant identity, user identity, provider, model, prompt version, and document corpus version.
Missing or unsupported identity information causes caching to be bypassed.
2. Local Embedding Generation
LongCache uses the
BAAI/bge-small-en-v1.5 embedding model by default.The model converts queries into numerical vectors representing their semantic relationships.
Embedding generation runs locally after the required model files have been downloaded.
3. FAISS Similarity Search
LongCache uses FAISS to search cached query embeddings.
The system compares the incoming query vector against candidates in the appropriate semantic partition.
The configured similarity threshold determines which candidates are sufficiently close to consider.
4. Candidate Verification
A high similarity score does not automatically mean a cache hit.
LongCache verifies whether the candidate satisfies the applicable request identity, response decoding, and reuse policies.
5. Cache Hit or Miss
When a verified, eligible response exists, LongCache returns it without executing the original LLM or RAG function.
Otherwise, the application executes the original operation. An eligible result may then be admitted into the cache.
Unsupported request shapes bypass caching rather than being served an inappropriate response.
Core Features of LongCache
Semantic Similarity Caching
LongCache identifies semantically related queries through local embeddings and FAISS.
It can reuse compatible answers even when the query wording changes, subject to its verification requirements.
Scoped Multi-Tenant Isolation
LongCache supports trusted request identities that include tenant and user boundaries.
Its default private scope policy requires appropriate identity information.
This helps prevent cached answers from being reused across incompatible users, models, prompts, or document versions.
Configurable Cache Expiration
Entries can use time-to-live (TTL) values.
A TTL defines how long a response remains eligible for reuse before expiration.
Multiple Storage Backends
LongCache provides SQLite, Redis, and in-memory storage options for different application requirements.
Cache Invalidation
Developers can invalidate entries using scoped operations or tags.
This is important when source documents, business policies, or application configurations change.
Concurrent Request Coordination
LongCache includes singleflight execution for supported identical scoped requests.
Rather than running the same expensive operation repeatedly during concurrent requests, eligible callers can share ongoing execution.
Operational Monitoring
LongCache exposes statistics, inspection, and management commands to help developers understand cache behavior.
Getting Started with LongCache: Installation and Python API
LongCache provides a Python package and an API for integrating semantic caching into existing applications.
Installation
Install the standard package:
pip install longcacheFor Redis support:
pip install "longcache[redis]"For supported LangChain compatibility integrations:
pip install "longcache[langchain]"Install the available optional components:
pip install "longcache[all]"The standard installation uses SQLite storage and local embedding-based similarity search without requiring a separately deployed cache service.
Create a Request Context
LongCache requires an explicit trusted execution context for supported caching operations.
from longcache import (
LongCache,
RequestContext,
RequestScope,
)
context = RequestContext(
scope=RequestScope(
tenant_id="company-a",
user_id="user-123",
),
operation="support.answer",
provider="openai",
provider_scope="production",
model="gpt-4o",
prompt_version="support-v1",
corpus_version="knowledge-v1",
)The tenant and user IDs should originate from trusted authentication information rather than arbitrary request input.
Model and provider values should match the actual generation operation.
Cache an Existing RAG Function
LongCache provides a decorator for supported query-only functions.
cache = LongCache(context=context)
@cache.cached
def answer_question(query: str) -> str:
return expensive_rag_pipeline(query)Here,
expensive_rag_pipeline() represents the application's existing retrieval and LLM operation.The function is application-defined, not a built-in LongCache API.
Execute the first request:
answer_question(
"What is your refund policy?"
)If no verified cached response exists, the underlying function executes.
Repeat the query:
answer_question(
"What is your refund policy?"
)An eligible cached result can now be returned.
Try a paraphrased query:
answer_question(
"How can I request a refund?"
)This request is served from cache only when similarity and verification requirements are satisfied.
Important: LongCache does not guarantee that every semantically similar query will produce a cache hit.
Resource Cleanup
Long-lived application instances should be closed during shutdown.
cache.close()For a bounded synchronous operation, developers can also use a context manager.
Configuring LongCache for Production
LongCache provides a
CacheConfig dataclass for controlling cache behavior.from longcache import CacheConfig, LongCache
config = CacheConfig(
similarity_threshold=0.92,
ttl_seconds=3600,
max_entries=10000,
namespace="support",
backend="sqlite",
db_path=".longcache/v2/cache.db",
track_stats=True,
singleflight_enabled=True,
)
cache = LongCache(
config,
context=context,
)Important Configuration Parameters
| Parameter | Purpose |
|---|---|
similarity_threshold | Minimum candidate similarity |
ttl_seconds | Cache entry expiration |
max_entries | Maximum entries per semantic partition |
namespace | Logical cache grouping |
backend | Storage backend selection |
track_stats | Enable operational statistics |
singleflight_enabled | Coordinate eligible identical requests |
The documented default similarity threshold is
0.92.A higher threshold is stricter and may reduce inappropriate matches, but it can also lower the cache hit rate.
A lower threshold may increase candidate matches while raising the risk of incorrect answer reuse.
Threshold selection should be based on representative application queries and observed results.
LongCache Storage Backends: SQLite, Redis, and Memory
Different environments require different storage characteristics.
SQLite: Default Persistent Storage
SQLite is the default backend.
It provides persistent local storage without requiring an external database server.
Advantages include straightforward setup, local development compatibility, and support for single-machine applications.
Redis: Persistent Response Storage
Redis can store cached responses and TTL information.
In default single-process mode, each LongCache process maintains its own FAISS index.
For multi-process deployments, LongCache also provides an explicit shared Redis mode.
That mode uses Redis coordination and journal synchronization while retaining local indexes within application processes.
It requires additional deployment planning and consistent cache-generation settings.
In-Memory Storage
The memory backend keeps responses within the running process.
It is useful for unit tests, local experiments, and workloads that do not require persistence.
| Backend | Persistence | Suitable use |
|---|---|---|
| SQLite | Yes | Local and single-machine applications |
| Redis | Yes | Durable storage and configured shared deployments |
| Memory | No | Testing and temporary caching |
Multi-Tenant Caching and Data Isolation
Caching becomes more sensitive when one application serves multiple customers, departments, or user accounts.
Suppose two organizations use a shared support platform.
Both ask:
"What is the refund policy?"
Even when the questions are identical, their policies may be different.
Reusing one organization's response for another would be incorrect and could expose private information.
LongCache addresses this by including execution and scope information in cache identity.
Relevant factors include:
- Tenant and user identity.
- Model and provider configuration.
- Prompt and instruction versions.
- Knowledge-base and document versions.
- Cache policies and execution settings.
Its default private policy is designed for scoped reuse. Broader sharing must be explicitly configured and reviewed.
Production principle: Semantic similarity determines potential relevance; trusted execution identity determines whether reuse is permitted.

Cache Invalidation and Changing RAG Documents
RAG applications depend on information that changes over time.
A cached response may become outdated when an organization updates a policy, replaces documentation, or changes a retrieval corpus.
Consider an assistant that previously answered:
"Refunds are available within 30 days."
If the policy changes to 14 days, a cached answer based on the previous policy must not be reused as current information.
LongCache supports expiration, tag-based invalidation, and request-context versioning.
Tag-Based Invalidation
Developers can attach tags to eligible stored responses.
When the corresponding content changes, scoped entries associated with those tags can be invalidated.
Document Versioning
LongCache also allows applications to include corpus and document revision information in the execution context.
When relevant documents change, the application should update those values before cache lookup and generation.
Versioning helps prevent reuse across incompatible knowledge-base states.
Expiration alone is not a substitute for correct document-version tracking.
Reducing Duplicate Requests with Singleflight
A common production problem occurs when multiple users submit identical requests simultaneously.
Without request coordination, each request might execute the same expensive LLM operation independently.
LongCache includes singleflight coordination for supported identical scoped requests.
The first request becomes the leader and performs the eligible operation.
Other matching requests can wait for that execution instead of independently running the same operation.
This can reduce redundant execution during traffic spikes.
However, singleflight applies only to supported call paths and matching scoped identities. General manual lookup-and-store sequences do not automatically receive the same coordination.
The feature should be evaluated together with provider timeouts, request concurrency, and application failure handling.

Integrating LongCache with OpenAI, FastAPI, and RAG Frameworks
LongCache provides several integration interfaces, but not all of them perform response caching.
Understanding this distinction is important.
OpenAI Integration
LongCache includes
CachedOpenAI for supported single-turn text requests.Eligible requests require complete trusted context and compatible response shapes.
Multi-turn conversations, streaming requests, tool calls, multimodal inputs, and certain other request types bypass caching.
This avoids incorrectly replaying responses for unsupported operations.
FastAPI Middleware
LongCache also provides middleware for supported chat-completion JSON requests.
The middleware can report cache behavior through diagnostic headers.
| Header value | Meaning |
|---|---|
HIT | Cached response served |
MISS | Request continued to the underlying application |
BYPASS | Request not eligible for caching |
Applications must configure trusted scope resolution and manage the cache lifecycle appropriately.
LangChain and LangGraph
LongCache includes compatibility wrappers for LangChain and LangGraph.
The documented generic adapters currently preserve framework interfaces through pass-through behavior rather than automatically caching arbitrary chain or graph state.
Developers who need actual caching should use supported explicit-context paths around well-defined application operations.
LlamaIndex
LongCache also provides a LlamaIndex compatibility interface.
Its generic query-engine adapter preserves the interface without automatically caching opaque engine state.
Streaming Limitations
LongCache's streaming helpers currently pass through to the underlying operation.
They do not provide general cached token-stream replay.
This distinction matters when designing user-facing applications that require incremental response generation.
Measuring Cache Performance and LLM Cost Savings
Semantic caching should be evaluated through real application measurements.
Useful operational metrics include:
- Cache hit rate.
- Cache miss rate.
- Cache bypass rate.
- Response latency.
- LLM calls avoided.
- Embedding and storage overhead.
- False-positive cache matches.
- Estimated token-cost savings.
Understanding Cache Hit Rate
The basic metric is:
Cache Hit Rate = Cache Hits / Eligible Cache Lookups × 100
For example, suppose an application records 1,000 eligible cache lookups and serves 350 verified responses from cache.
Its hit rate would be:
350 / 1,000 × 100 = 35%
This is an illustrative calculation, not a measured LongCache benchmark.
A cache hit rate alone does not demonstrate actual financial savings.
Developers must also consider embedding computation, storage costs, the size of avoided LLM calls, and the correctness of reused responses.
The LongCache repository describes opportunities for substantial cost reduction, but actual results depend on the workload and configuration.
Best Practices for Production Semantic Caching
1. Start with High-Repeat Queries
Customer-support FAQs, documentation assistants, and standardized knowledge-base questions are useful initial candidates.
2. Use Trusted Request Context
Generate tenant, user, and permission-related identity information from authenticated application state.
3. Tune Similarity Thresholds Carefully
Begin with the documented default, then evaluate representative queries for both missed opportunities and incorrect matches.
4. Version Prompts and Knowledge Bases
Update the relevant execution-context versions when source documents, prompts, or model behavior change.
5. Use Explicit Cache Invalidation
Invalidate outdated entries when changes require immediate freshness rather than relying exclusively on TTL expiration.
6. Avoid Unverified Response Reuse
A response should not be served simply because its query embedding is close to another query.
Verification and eligibility checks are essential.
7. Monitor Efficiency and Correctness
Track cache hits, misses, bypasses, latency, and response-quality signals together.
8. Understand Integration Boundaries
Do not assume every framework wrapper, streaming path, or API request is automatically cached.
Choose an integration path documented to support the request shape being used.
LongCache Integration with the Long Suite Ecosystem
LongCache belongs to EnDevSols' Long Suite ecosystem, which includes complementary tools for building and evaluating RAG applications.
| Project | Main responsibility |
|---|---|
| LongParser | Document parsing and intelligent chunking |
| LongTrainer | RAG chatbot and application orchestration |
| LongCache | Semantic response caching and eligible request reuse |
| LongGuard | Agent loop detection and runtime safeguards |
| LongTracer | Generated-answer verification |
| LongProbe | Retrieval regression testing |
These projects address different parts of the AI application lifecycle.
LongParser can help prepare source documents, while LongTrainer provides application-level RAG functionality.
LongCache can reduce duplicate execution in supported workflows.
LongGuard focuses on problematic agent runtime behavior, while LongTracer and LongProbe address different aspects of response reliability and retrieval quality.
The projects may be adopted individually or combined through application-specific integrations. Their availability within the same ecosystem does not imply automatic interoperability.
LongCache Limitations and Production Considerations
LongCache is focused on eligible semantic response reuse rather than caching every possible LLM interaction.
Important limitations include:
- Similar queries may require different answers.
- Some request shapes bypass caching.
- Generic LangChain, LangGraph, and LlamaIndex compatibility adapters currently pass through.
- Streaming response replay is not generally supported.
- Shared Redis deployments require specific coordination and configuration.
- Local embedding generation introduces compute and memory overhead.
- Cached responses still depend on correct versioning and invalidation.
- High cache hit rates do not automatically guarantee answer accuracy.
Production adoption should involve representative testing, trusted identity handling, monitoring, and documented recovery procedures.
Frequently Asked Questions About LongCache
What is LongCache?
LongCache is an open-source Python semantic caching framework for LLM and RAG applications. It uses local embeddings, FAISS, and scoped request verification to reuse eligible cached responses.
How is semantic caching different from traditional caching?
Traditional caching commonly relies on exact request matching. Semantic caching can identify differently worded requests with similar meanings, subject to additional eligibility checks.
Does LongCache use a vector database?
LongCache uses FAISS for vector similarity search. Its response storage backends include SQLite, Redis, and memory.
Does LongCache require an external embedding API?
No. Its default BGE-small embedding model runs locally after the required weights are available.
What is the default similarity threshold?
The documented default threshold is
0.92. Developers should tune it for their own workload.Does LongCache support multi-tenant applications?
Yes. It includes scoped request identities and a default private caching policy designed to prevent incompatible response reuse.
Does LongCache support asynchronous operations?
Yes. Supported async functions and APIs include asynchronous cache operations and concurrent execution coordination.
Can LongCache cache streaming LLM responses?
Its documented streaming helpers currently pass through rather than caching and replaying token streams.
Does LongCache automatically cache every LangChain workflow?
No. Its generic LangChain compatibility wrappers currently operate as pass-through adapters. Supported explicit-context caching APIs can be used around eligible application functions.
Is LongCache free and open source?
Yes. LongCache is available on GitHub under the MIT License. Review the repository's license and dependency requirements before distribution.
Does LongCache guarantee lower LLM costs?
No fixed saving is guaranteed. Results depend on request repetition, cache eligibility, model costs, embedding overhead, and deployment configuration.
Get Started with LongCache
LongCache provides a practical foundation for introducing semantic response reuse into LLM and retrieval-augmented generation applications.
With local embeddings, FAISS similarity search, configurable storage, trusted request identities, and eligible concurrent execution sharing, developers can reduce unnecessary repeated work while maintaining control over how cached responses are reused.
Successful deployment requires more than enabling a cache. Teams must validate request identity, monitor answer correctness, version changing documents, and understand which integration paths support caching.
For installation instructions, API reference, examples, and development updates, explore the official LongCache resources:
- GitHub: https://github.com/ENDEVSOLS/LongCache
- Documentation: https://endevsols.github.io/LongCache/
Reliable semantic caching is not simply about returning faster answers. It is about reusing the right answer under the right execution context.
