Semantic Caching with Qdrant and BGE-Small: Slashing OpenAI API Bills by 78% for Nigerian AI Support Agents
High token costs and transatlantic network latency make calling GPT-4o for every recurring customer query unsustainable. We show you how to build an in-memory, CPU-based semantic cache with Qdrant and BGE-Small that intercepts duplicate questions, reduces latency to 15ms, and drastically lowers API bills.
In late 2024, a fintech client came to us at Neobot Tech with an ugly billing emergency. Their WhatsApp support agent—powered by GPT-4o—was costing them $2,400 a month. As the FX exchange rate fluctuated unpredictably, that USD-denominated API bill was devouring over 40% of their gross SaaS margin.
When we dumped 30 days of conversation logs into Postgres for analysis, the problem became clear: 68% of incoming customer messages were identical or semantically equivalent questions. "My transfer never enter", "I paid but my wallet is not funded", "Where is my money?", and "How long does NIBSS settlement take?" were hitting GPT-4o over and over again. Each request triggered a fresh round of expensive input tokens, full context system prompts, and tool calling overhead.
Traditional key-value caching in Redis does not help here. A string hash lookup on "My transfer never enter" fails completely when the next user writes "my money never reflect for wallet". But routing every single inquiry to a top-tier LLM vendor is financial suicide when operating in an economy with index-linked revenue pressure.
The solution is a self-hosted, latency-optimized semantic cache built on Qdrant and a lightweight CPU-friendly embedding model. By intercepting incoming queries at the API gateway layer, vectorizing them locally, and running cosine similarity lookups against previous verified answers, we cut the client's monthly OpenAI bill from $2,400 down to $520 while reducing average response latency from 2.8 seconds to 45 milliseconds.
Here is how to design, build, and deploy this architecture on budget infrastructure without sacrificing answer precision.
Why Exact-Match Caching Fails for Localized AI Agents
Exact-match keys (like MD5 hashes of prompt strings in Redis) work for static REST endpoints, but fail entirely in conversational AI. Human language, especially in West African commerce contexts, has high variance. Consider these four customer inputs received by a logistics startup in Yaba:
- "Where is my item?"
- "Abeg where my package dey?"
- "My order hasn't arrived yet, tracker says Lekki"
- "Wetin dey delay my delivery?"
To an LLM, all four queries require the exact same context retrieval and response template. To Redis, these are four distinct cache misses requiring four separate token payouts to OpenAI or Anthropic.
Furthermore, full-text search (like Postgres tsvector or Elasticsearch BM25) struggles with slang, typos, and shorthand common in mobile messaging ("plz", "ndpr", "ussd", "gtb"). BM25 relies on exact token matching and term frequency-inverse document frequency (TF-IDF). If the indexed query contains "transfer" and the incoming prompt says "alert", BM25 assigns a similarity score near zero.
Dense vector embeddings solve this by mapping phrases into a continuous vector space where distance represents semantic intent rather than character overlap. However, calling OpenAI's text-embedding-3-small for every incoming cache check defeats the purpose—you add external network latency (150ms-300ms from Lagos data centers to AWS us-east-1) and incur embedding API costs on every miss.
To make semantic caching viable, embedding generation must happen locally on CPU in under 10 milliseconds, and vector retrieval must execute within 5 milliseconds.
Designing the System Architecture: Qdrant + BGE-Small on CPU
To keep hosting costs down to a $20/month VPS level, we avoid heavy GPU dependencies. We run the embedding engine directly inside the application process using PyTorch CPU or ONNX Runtime.
We chose BAAI/bge-small-en-v1.5 (Hugging Face model page). It produces 384-dimensional vectors, takes less than 130MB of RAM, and runs inference in 6 to 9 milliseconds on a standard 2-core AMD EPYC CPU.
For the vector store, we use Qdrant (Qdrant documentation). Qdrant is written in Rust, consumes minimal memory when configured with scalar quantization, and supports rich payload filtering out of the box. Filters are mandatory because semantic caches must enforce multi-tenant isolation and user session boundaries—you cannot return User A's cached account balance inquiry to User B.
| Metric / Feature | Redis Exact String Cache | Postgres BM25 Keyword Search | Local Vector Semantic Cache (Qdrant + BGE-Small) | | :--- | :--- | :--- | :--- | | Matching Type | Exact string byte match | Lexical / Token overlap | Deep Semantic Intent | | Handles Pidgin / Slang | No | Poorly (requires manual synonym dictionaries) | High (captures contextual similarity) | | Inference Latency | < 2 ms | 10 - 30 ms | 12 - 20 ms (Local CPU) | | External API Overhead | $0 | $0 | $0 | | Cache Hit Rate (Support) | 12% - 18% | 35% - 42% | 72% - 84% | | Infrastructure RAM | < 50MB | Postgres shared buffers | ~350MB total (Model + Vector DB) |
If your system receives voice notes via WhatsApp, audio transcripts generated by models like Whisper can be passed directly into this semantic cache pipeline. We detailed voice transcription pipelines in our guide on Fine-Tuning Faster-Whisper for Nigerian Pidgin: Low-Latency Voice AI on $20 CPU VPS.
Implementing the Semantic Cache Middleware in Python
Below is a complete implementation of an asynchronous semantic caching proxy using FastAPI, qdrant-client, and sentence-transformers.
This middleware inspects the incoming user query, generates a 384-d vector, performs a cosine similarity lookup against Qdrant, and either returns the cached payload immediately or forwards the request to OpenAI before background-writing the response back to Qdrant.
import os
import time
from typing import Optional, Dict, Any
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct, Filter, FieldCondition, MatchValue
from openai import AsyncOpenAI
app = FastAPI(title="Semantic Cache Gateway")
# Initialize Local Embedding Model on CPU (384 dimensions)
embedder = SentenceTransformer("BAAI/bge-small-en-v1.5", device="cpu")
# Initialize Qdrant Client
QDRANT_HOST = os.getenv("QDRANT_HOST", "localhost")
qdrant = QdrantClient(host=QDRANT_HOST, port=6333)
COLLECTION_NAME = "support_semantic_cache"
SIMILARITY_THRESHOLD = 0.88 # Cosine similarity score cutoff
# Ensure collection exists
if not qdrant.collection_exists(COLLECTION_NAME):
qdrant.create_collection(
collection_name=COLLECTION_NAME,
vectors_config=VectorParams(size=384, distance=Distance.COSINE),
)
# Index tenant_id for payload filtering
qdrant.create_payload_index(
collection_name=COLLECTION_NAME,
field_name="tenant_id",
field_schema="keyword",
)
openai_client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
class ChatQuery(BaseModel):
tenant_id: str
user_id: str
prompt: str
def get_vector(text: str) -> list[float]:
# Normalizing embeddings ensures cosine similarity equals inner product
embeddings = embedder.encode(text, normalize_embeddings=True)
return embeddings.tolist()
async def query_semantic_cache(tenant_id: str, prompt_vector: list[float]) -> Optional[Dict[str, Any]]:
# Search Qdrant with tenant payload filter to prevent cross-tenant data leakage
search_result = qdrant.search(
collection_name=COLLECTION_NAME,
query_vector=prompt_vector,
query_filter=Filter(
must=[
FieldCondition(
key="tenant_id",
match=MatchValue(value=tenant_id)
)
]
),
limit=1,
score_threshold=SIMILARITY_THRESHOLD
)
if search_result:
best_match = search_result[0]
return {
"cached_response": best_match.payload["response"],
"score": best_match.score,
"id": best_match.id
}
return None
@app.post("/api/v1/chat")
async def handle_chat(query: ChatQuery):
start_time = time.perf_counter()
# Step 1: Compute local embedding vector
prompt_vector = get_vector(query.prompt)
# Step 2: Query Qdrant for semantically identical answer
cache_hit = await query_semantic_cache(query.tenant_id, prompt_vector)
if cache_hit:
elapsed = (time.perf_counter() - start_time) * 1000
return {
"source": "semantic_cache",
"response": cache_hit["cached_response"],
"similarity_score": cache_hit["score"],
"latency_ms": round(elapsed, 2)
}
# Step 3: Cache Miss - Forward to LLM Vendor (OpenAI)
try:
completion = await openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful customer support agent for a Nigerian e-commerce platform."},
{"role": "user", "content": query.prompt}
],
temperature=0.2
)
llm_response = completion.choices[0].message.content
except Exception as e:
raise HTTPException(status_code=502, detail=f"LLM Provider Error: {str(e)}")
# Step 4: Write-through cache insertion
import uuid
point_id = str(uuid.uuid4())
qdrant.upsert(
collection_name=COLLECTION_NAME,
points=[
PointStruct(
id=point_id,
vector=prompt_vector,
payload={
"tenant_id": query.tenant_id,
"original_prompt": query.prompt,
"response": llm_response,
"created_at": time.time()
}
)
]
)
elapsed = (time.perf_counter() - start_time) * 1000
return {
"source": "llm_completion",
"response": llm_response,
"similarity_score": 0.0,
"latency_ms": round(elapsed, 2)
}
Notice how cache population can be offloaded asynchronously to background task workers if API gateway latency is sensitive. If your backend infrastructure uses background queues, check our evaluation on Postgres SKIP LOCKED vs BullMQ vs Temporal: Choosing a Job Queue for Flaky Nigerian APIs for low-overhead queue selection on constrained servers.
Managing Cache Invalidation, Drift, and Threshold Tuning
Deploying a vector cache without invalidation policies creates dangerous stale-state bugs. If your shipping fees change or an ongoing bank downtime is resolved, returning cached responses generated two weeks ago will misinform users and trigger customer support escalations.
1. Dynamic Similarity Cutoffs by Intent Class
A single global similarity threshold of 0.88 is a dangerous default. High-risk transactional queries require tight matching thresholds, whereas general FAQ queries can afford broader thresholds.
- Transactional Intent ("How much is shipping to Port Harcourt?"): Use
0.94threshold. A slight variance in destination or parcel weight changes the price. - Informational Intent ("What are your opening hours?"): Use
0.82threshold. "Wetin be una opening time" and "Are you open on Sundays?" map safely to the same response.
To enforce this, run a low-overhead classifier before cache retrieval to adjust SIMILARITY_THRESHOLD dynamically.
2. Time-To-Live (TTL) and Payload Metadata Invalidation
Qdrant does not natively expire vectors by default like Redis TTL keys. To implement TTL, store a created_at timestamp in the point payload and inject a range filter into vector queries:
from qdrant_client.models import Range
# Filter out cache hits older than 7 days (604,800 seconds)
seven_days_ago = time.time() - 604800
search_result = qdrant.search(
collection_name=COLLECTION_NAME,
query_vector=prompt_vector,
query_filter=Filter(
must=[
FieldCondition(key="tenant_id", match=MatchValue(value=tenant_id)),
FieldCondition(key="created_at", range=Range(gte=seven_days_ago))
]
),
limit=1,
score_threshold=0.88
)
For immediate cache invalidation when business data changes (e.g., an updated refund policy), send an explicit delete command filtered by tags:
qdrant.delete(
collection_name=COLLECTION_NAME,
points_selector=Filter(
must=[FieldCondition(key="category", match=MatchValue(value="refund_policy"))]
)
)
Common Pitfalls When Running Vector Caching on Budget Infrastructure
1. Unnormalized Vector Similarity Skew
If you fail to pass normalize_embeddings=True to sentence-transformers, magnitude differences in vectors will distort cosine distance calculations. Unnormalized vectors lead to false positive hits where completely unrelated prompts trigger high similarity scores.
2. Out-Of-Memory (OOM) Kills on 1GB VPS Instances
Running PyTorch, ONNX runtime, and Qdrant on a single micro-instance with 1GB of RAM will trigger the Linux OOM killer. Always set PyTorch thread limits:
import torch
torch.set_num_threads(2)
And pass quantized vectors to Qdrant so vector indices reside in memory as int8 rather than float32, cutting RAM consumption by 75%.
3. Cross-Tenant Data Leakage
Never perform vector searches without explicit payload_filter scopes. If your SaaS serves multiple merchant accounts, omitting tenant_id from the Qdrant filter will return Account A's localized delivery pricing to Account B's customers—a severe privacy breach under NDPR guidelines.
Frequently Asked Questions
How does semantic caching differ from RAG (Retrieval-Augmented Generation)?
RAG retrieves reference documents and passes them as context into an LLM to generate a new answer. Semantic caching bypasses the LLM entirely—it retrieves the final generated response from a previous identical context. RAG still incurs LLM generation costs; semantic caching costs $0 in model inference fees on cache hits.
What embedding model should I use for West African English and Pidgin?
For pure CPU execution with under 15ms latency, BAAI/bge-small-en-v1.5 or all-MiniLM-L6-v2 perform exceptionally well on English and light Pidgin variants. If your user base uses heavy code-switching or Hausa/Yoruba/Igbo phrasing, switch to intfloat/multilingual-e5-small. It increases RAM footprint slightly (approx 470MB) but retains robust semantic alignment across local languages.
How do I handle localized dynamic data like user balance checks?
Never cache responses that contain personalized dynamic state (e.g., "Your current account balance is ₦45,000"). Filter out prompts containing personal entities before writing to the semantic cache, or extract state parameters into placeholders like {{account_balance}} so the template is cached while dynamic values are injected at runtime.
What is the expected response latency reduction?
Calling OpenAI GPT-4o typically takes between 1.5 to 3.5 seconds over West African ISP routes due to transatlantic packet hops. A local semantic cache lookup running Qdrant + BGE-Small on the same VPS returns responses in 15 to 45 milliseconds—delivering a 50x speed improvement for cached queries.
Neobot Engineering Standard
Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.
Discussion
Comments Coming Soon
We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.