Why the community can’t agree on a single RAG architecture
There is a lively debate on forums and internal chats about whether a single‑purpose retrieval component is enough for large organisations. Some argue that wiring a language model directly to one vector database keeps things simple. Others point out that the moment a new data source appears or a compliance rule changes, the whole system starts to wobble. The disagreement often boils down to two philosophies: monolithic pipelines that are quick to prototype versus modular stacks that can be swapped out piece by piece. This post leans toward the latter, because in an enterprise setting the cost of a hard‑to‑change pipeline quickly outweighs the convenience of a single‑file script.
In the following sections I break down the problem, walk through a concrete design, flag the usual traps and finish with a step‑by‑step checklist you can apply to the next project. The tone is conversational – think of us sharing a coffee break while the CI/CD pipeline hums in the background.
Context: why a robust pipeline matters now
Enterprises are suddenly dealing with petabytes of internal documentation, support tickets, regulatory filings and code bases. Retrieval‑augmented generation (RAG) promises to turn that raw material into concise answers, but the promise only holds if the underlying pipeline can ingest new content daily, keep latency under a second for most queries, and stay compliant with data‑residency rules. A monolithic design that locks the model to a single storage backend makes every future change feel like a refactor of the entire code base. By contrast, a modular architecture lets you replace the vector store, add a cache layer or switch to a different embedding model without touching the rest of the system.
Beyond flexibility, modularity improves observability. Each component can emit its own metrics – ingestion lag, vector indexing cost, cache hit ratio – and those signals feed directly into capacity planning. When the business decides to expand the knowledge base from a few hundred megabytes to tens of gigabytes, you already have the knobs in place to scale each part independently.
Technical deep dive: the building blocks and their trade‑offs
Below is the minimal set of abstractions that keep the pipeline decoupled yet coherent.
- Ingestion adapters – small classes that know how to pull data from a source (SharePoint, S3, relational DB) and emit a stream of plain text chunks.
- Embedding service wrapper – an interface that can call OpenAI, a local transformer or a hosted inference endpoint. The wrapper returns fixed‑size vectors and can be swapped by changing a config file.
- Vector store abstraction – a thin layer that hides the API of Pinecone, Qdrant, Weaviate or a self‑hosted FAISS index. The abstraction defines methods like
upsert,searchanddelete. - Cache layer – usually a Redis instance that stores recent query results keyed by a hash of the query text. It reduces repeated vector searches and smooths latency spikes.
- Fallback retriever – a traditional BM25 or Elasticsearch index that can answer the query when the vector store returns no hits or when the embedding service is unavailable.
All of these pieces can be wired together with a tiny orchestration function. The code snippet shows the essential flow without any framework‑specific glue.
class Ingestor:
def __init__(self, source):
self.source = source
def load(self):
# Load raw documents from the source and yield chunks
for doc in self.source.fetch():
for chunk in split_into_chunks(doc.text):
yield {"id": doc.id, "text": chunk}
class VectorStore:
def __init__(self, client):
self.client = client
def upsert(self, vectors, ids, metadata):
self.client.upsert(vectors=vectors, ids=ids, metadata=metadata)
def search(self, query_vector, top_k=5):
return self.client.query(vector=query_vector, top_k=top_k)
class CacheLayer:
def __init__(self, redis_client):
self.redis = redis_client
def get(self, key):
return self.redis.get(key)
def set(self, key, value, ttl=300):
self.redis.setex(key, ttl, value)
def retrieve(query, ingestor, store, cache, fallback, embedder):
cached = cache.get(query)
if cached:
return cached
q_vec = embedder.embed(query)
results = store.search(q_vec)
if not results:
results = fallback.search(query)
cache.set(query, results)
return results
Trade‑offs become clear when you examine each block:
- Ingestion adapters – writing a custom adapter costs time, but it isolates source‑specific authentication and pagination logic. When a new source appears you only add a new class.
- Embedding service – hosted APIs give you the latest model with zero maintenance, yet they add latency and cost per token. A local model reduces variable cost but requires GPU resources and version management.
- Vector store choice – managed services (Pinecone, Qdrant Cloud) handle scaling automatically but may lock you into a region. Self‑hosted FAISS gives full control over hardware and distance metric, yet you must implement sharding and persistence yourself.
- Cache strategy – a simple key‑value store cuts repeat work, but cache invalidation is tricky when the underlying corpus changes. A TTL‑based approach works for most enterprise use cases because updates are batched nightly.
- Fallback retriever – BM25 is fast and works even if embeddings are stale, but it cannot capture semantic similarity. Using it as a safety net protects against service outages without degrading user experience.
Common pitfalls and what tends to go wrong
Even with a modular blueprint, teams often stumble over a few recurring issues.
- Coupling through shared data models – passing raw dictionaries between modules sounds easy, but a subtle schema change in the ingestion output can break the vector store’s metadata expectations. Defining a Pydantic model for the chunk payload prevents silent failures.
- Cache poisoning – if a query is cached before the vector store finishes indexing new documents, the stale result will be served forever until the TTL expires. The safe pattern is to invalidate the cache for any query that matches newly added IDs, or to use a short TTL during heavy ingestion windows.
- Version drift in embeddings – upgrading from a 768‑dimensional model to a 1024‑dimensional one without re‑indexing leaves a mixed‑dimensional store that crashes at query time. A migration plan that re‑embeds in batches and keeps both versions live during the transition avoids downtime.
- Fallback never triggers – some teams disable the BM25 fallback because the vector store always returns a result, even if it is an empty list. The code above checks
if not results, but a vector store may return a list with low‑score entries that are effectively noise. Adding a score threshold before deciding to fall back yields better coverage. - Scaling assumptions baked into the monolith – hard‑coding batch sizes for upserts based on a small test dataset leads to timeouts when the corpus grows. Parameterising batch size and making it configurable per deployment solves the problem.
Practical implementation guide: a decision framework
Below is a checklist you can run through when you start a new RAG project. Treat each bullet as a decision point that maps to one of the modular components.
- Identify data sources – list every repository (SharePoint, Confluence, internal APIs). For each source, decide whether you need a custom adapter or an existing connector. Prioritise adapters that expose a
fetchgenerator to keep memory usage low. - Select embedding provider – compare hosted APIs (cost per 1k tokens, latency, region) against on‑prem models (GPU budget, version control). Record the vector dimension and distance metric (cosine vs dot product) for later compatibility checks.
- Pick a vector store – evaluate based on scalability, query latency SLA, supported distance metric and data‑residency requirements. If you need multi‑region redundancy, choose a managed service with cross‑region replication; otherwise, a self‑hosted FAISS cluster on Kubernetes may be cheaper.
- Design cache policy – decide key format (hash of query text), TTL length (shorter during ingestion, longer for stable queries) and invalidation triggers (new document IDs, manual purge endpoint).
- Define fallback strategy – provision a BM25 index on the same raw text store. Set a score threshold (e.g., 0.3) that, when not met, forces a fallback search. Ensure the fallback client uses the same tokenizer to keep term matching consistent.
- Wire the orchestration – implement a thin function like
retrievethat respects the order: cache → vector store → fallback → cache update. Keep logging at each step for observability. - Test end‑to‑end latency – simulate a realistic query mix, measure cache hit ratio, vector search latency, and fallback latency. Adjust batch sizes, TTLs or replica counts until you meet the SLA.
- Plan for version upgrades – store embedding model version alongside each vector. Write a migration script that re‑embeds only the changed documents and writes to a new namespace in the vector store, then switches the read alias.
Following this framework gives you a pipeline that can grow from a handful of documents to millions without a complete rewrite.
Closing thoughts: keep the architecture flexible and observable
The main lesson is that a RAG pipeline is not a single algorithm but a collection of interchangeable services. When each piece speaks a well‑defined interface, you can react to business needs – new data regulations, cost optimisation, performance tuning – without pulling the whole stack apart. Observability is the glue that tells you when a component is misbehaving; without metrics you won’t know whether a cache miss or an embedding outage is the culprit.
In practice, start small, expose the interfaces early and let the code evolve as new requirements surface. The extra upfront effort of modularising pays off when the next compliance audit or regional rollout arrives.
Next steps
If you want to see a reference implementation or discuss how to adapt this design to your own stack, drop by akkistech.com. I’m happy to chat over a virtual coffee.