Build a RAG Service with Separate Ingestion and Answer Paths
In this article
This guide walks you through building a Retrieval-Augmented Generation (RAG) service where document ingestion and query answering run as separate, independent paths. This architecture lets you scale ingestion and query processing independently, improve fault isolation, and simplify updates—for example, re-indexing documents without taking the answer service offline. You'll end up with a production-ready pattern using a vector database, an embedding model, an LLM, and a simple API layer.
What You'll Need
- Python 3.9+ installed on your machine
- A vector database—options include Pinecone, Weaviate, Qdrant, or pgvector (we'll use Qdrant in this guide for its simplicity and self-hosted option)
- An embedding model—we'll use OpenAI's
text-embedding-3-smallor a local model likeall-MiniLM-L6-v2from sentence-transformers - An LLM for answer generation—OpenAI GPT, Anthropic Claude, or a local model via Ollama
- Basic familiarity with Python, FastAPI, and REST APIs
- Pip installed packages:
fastapi,uvicorn,qdrant-client,openai(orsentence-transformers),pypdforpython-docxfor document parsing
Step-by-Step
- Design the two paths. The ingestion path takes raw documents, splits them into chunks, embeds each chunk, and stores the vectors in a collection. The answer path takes a user query, embeds it, searches for similar chunks, and passes those chunks as context to an LLM to generate an answer. Keep these as separate services or at least separate modules with distinct endpoints.
- Set up the vector database. Install and run Qdrant locally:
docker run -p 6333:6333 qdrant/qdrant. Or create a free cloud instance. Create a collection nameddocumentswith a vector size that matches your embedding model (e.g., 1536 for OpenAI'stext-embedding-3-small, 384 forall-MiniLM-L6-v2). Use cosine distance for similarity. - Implement the ingestion service. Create a FastAPI app with an endpoint
POST /ingestthat accepts a file or text. Parse the document, split it into chunks of around 500-1000 characters with some overlap (e.g., 100 characters) to preserve context. Use a library likelangchainor write your own splitter. For each chunk, generate an embedding using the chosen model. Store the chunk text and its embedding in Qdrant, along with metadata like source filename and chunk index. - Implement the answer service. Create another FastAPI app (or a separate module) with an endpoint
POST /answerthat accepts a user query. Embed the query using the same embedding model. Search the Qdrant collection for the topkmost similar chunks (e.g.,k=4). Retrieve the chunk texts and build a prompt that includes the user's question and the retrieved context, with instructions for the LLM to answer based only on that context. - Call the LLM. Using the OpenAI API (or your chosen provider), send the prompt to the chat completions endpoint. Set a reasonable temperature (e.g., 0.2) to keep answers factual. Return the LLM's response from the
/answerendpoint, optionally including the source chunks for citation. - Add asynchronous processing (optional but recommended). For ingestion, use a task queue like Celery or FastAPI's
BackgroundTasksto process large documents without blocking the API. For the answer path, keep it synchronous for simplicity, but consider streaming responses for long answers. - Test both paths. Run both services (or one service with two routers). Upload a sample PDF or text file via
/ingest, then ask a question via/answerthat should be answerable from the document. Verify the answer is accurate and grounded in the provided context. - Deploy and scale. Containerize both services with Docker. Use a reverse proxy like Nginx to route
/ingestand/answerto the appropriate service. Scale the answer service horizontally because it handles user-facing latency, while the ingestion service can be scaled based on document volume. Use environment variables for API keys and database URLs.
Common Mistakes
- Using different embedding models for ingestion and query. This results in vectors that are not comparable, so retrieval fails. Always use the exact same model.
- Not handling document chunking properly. Chunks that are too large may exceed the embedding model's token limit; too small lose context. Also, splitting in the middle of a sentence or code block can break meaning. Use overlap and consider sentence-aware splitting.
- Ignoring metadata. Without storing source information, you can't cite answers or filter results. Always store at least the document ID and chunk index.
- Mixing sync and async code in the same path. If you use async for one part, make sure the whole path is async or use thread pools; otherwise, you'll block the event loop.
- Not cleaning up old vectors. When re-ingesting a document, you need to delete the old vectors first, or you'll have duplicates. Use a unique document ID and delete by filter before re-inserting.
Tips
- Use a consistent chunk size. For most documents, 500-800 characters with 50-100 overlap works well. Test with your own data to find the sweet spot.
- Add a relevance threshold. In the answer path, filter out chunks with similarity score below a threshold (e.g., 0.7) to avoid passing irrelevant context to the LLM.
- Cache embeddings. If you have many duplicate chunks, caching can save API costs. Use a simple dictionary or a cache like Redis.
- Log everything. Log the query, retrieved chunk IDs, scores, and the final answer. This helps debug retrieval issues and improve the system.
- Consider hybrid search. For better accuracy, combine vector search with keyword search (BM25) using a tool like Qdrant's hybrid queries or a separate Elasticsearch index.
Troubleshooting
- Retrieval returns empty or irrelevant results. Check that the embedding model is the same for both paths. Verify that documents were actually ingested by querying the collection count. Test the embedding similarity manually on a sample chunk and query.
- API calls to the LLM fail. Check your API key and network. Ensure the prompt is not too long—if the context exceeds the model's token limit, truncate or reduce the number of chunks.
- Ingestion is slow. If you're processing many documents, batch the embeddings (e.g., 100 chunks per request) instead of one by one. Use async or a queue.
- Qdrant connection refused. Make sure the Docker container is running and the port is correct. If using a cloud instance, check your API key and URL.
- Answers are hallucinated. The LLM may ignore the context. Improve your prompt: explicitly instruct it to answer only from the given context and to say "I don't know" if the answer isn't there. Also, increase
kor lower the temperature.
Frequently Asked Questions
Can I use a single service for both ingestion and answering?
Yes, you can have one FastAPI app with two routers. The separation is logical, not necessarily physical. However, running them as separate services allows independent scaling and deployment.
What if my documents are very large?
Split them into smaller chunks and process asynchronously. Use a queue to handle multiple documents in parallel, and consider using a distributed vector database like Pinecone for extreme scale.
Do I need to use OpenAI for embeddings and LLM?
No, you can use any embedding model and LLM. For local, open-source options, try all-MiniLM-L6-v2 for embeddings and Llama 3 via Ollama for the LLM.
How do I update or delete documents?
Assign a unique document ID to each ingested document. To update, delete all vectors with that document ID (using a filter) and re-ingest. To delete, just remove the vectors.
How do I ensure the answer service is fast?
Use a fast vector search index (HNSW in Qdrant), limit the number of chunks retrieved (e.g., 3-5), and consider caching common queries. Also, use a fast LLM or stream the response.
Is this architecture suitable for production?
Yes, with proper error handling, logging, monitoring, and scaling. Use container orchestration like Kubernetes if you need auto-scaling. Ensure you have a backup strategy for your vector database.