AI

Building a RAG Chatbot: A Production Architecture Guide

A practical guide to building scalable RAG chatbots with Gemini, document chunking, and background processing for real-world production environments.

By · · 6 min read

Short answer

A RAG chatbot architecture connects an LLM to your private data by embedding documents into a searchable vector store. To build a production-grade version, implement asynchronous document ingestion via background tasks, use semantic retrieval for context, and store user-specific data in isolated namespaces to ensure multi-tenant security.

Key takeaways

  • Decouple heavy document processing and vectorization from the main request loop using background workers.
  • Use semantic retrieval to fetch relevant text segments rather than simple keyword matching for better accuracy.
  • Enforce strict multi-tenancy by namespacing your vector store identifiers to prevent cross-tenant data leaks.
  • Include citations in model responses by mapping retrieved chunks back to their source document metadata.

What is the core architecture of a RAG chatbot?

A RAG chatbot improves LLM performance by grounding answers in your specific data. Instead of relying on a model's training set, the system searches your document store for relevant context before passing that context to the model.

The architecture consists of an ingestion pipeline and a retrieval pipeline. During ingestion, documents are parsed, chunked, and transformed into vector embeddings. These embeddings are high-dimensional numerical arrays that represent semantic meaning. The system stores these in a database optimized for similarity searches, typically using cosine similarity or Euclidean distance to determine proximity.

During retrieval, the user's query undergoes a similar transformation. The system converts the natural language input into a vector in the same embedding space. By querying the database, the system identifies the nearest neighbors—the specific text chunks most semantically similar to the user's question. These chunks act as a focused knowledge base, providing the model with the exact information needed to construct a factually grounded response.

Why use background tasks for RAG ingestion?

Processing large documents often exceeds the timeout limits of HTTP requests. By using a task queue, you ensure that your API remains responsive while files are being uploaded, parsed, and embedded in the background. A synchronous approach risks connection drops and browser timeouts, which provide a poor experience for users attempting to index complex files or large datasets.

In my experience with bubbl.ooo, I utilized Celery with a Redis broker to handle these background jobs. This setup allows the application to handle multiple document uploads from different tenants concurrently without blocking the main event loop. The system acknowledges the receipt of the file immediately, while the heavy computation—vectorization, chunking, and database insertion—occurs in isolated worker processes.

When designing these workers, consider atomicity. Each document ingestion should be an independent task. If a specific document fails to process due to a corrupted file or an API error, you can retry that individual job without affecting the state of the remaining document corpus. This creates a predictable pipeline where progress can be tracked and reported back to the user interface via polling or WebSockets.

@celery.task def index_document_task(file_path, tenant_id): vector_store = client.file_search_stores.create(display_name=tenant_id) operation = client.file_search_stores.upload_to_file_search_store(file=file_path, file_search_store_name=vector_store.name) wait_for_operation(operation)

Gemini File Search vs. Custom Vector Databases?

The choice depends on your infrastructure constraints and required control. Managed services like Gemini File Search handle chunking, indexing, and embedding storage for you, significantly reducing maintenance overhead. They abstract away the complexities of maintaining a running vector index, allowing you to focus on the application logic rather than the underlying infrastructure.

Alternatively, using a custom database like pgvector or Qdrant gives you complete control over indexing logic, metadata filtering, and hardware allocation. For most early-stage SaaS projects, starting with a managed retrieval tool is safer and faster to deploy. However, as your data volume grows, you might find that fine-grained control over search parameters—such as hybrid search, which combines keyword-based BM25 with semantic vector search—becomes necessary for high-accuracy retrieval.

Consider the latency impact as well. Managed services rely on external API calls, which introduce network latency. A locally hosted custom vector database might perform better for high-throughput applications where milliseconds matter. Balance this against the engineering cost of maintaining your own search engine, including backups, sharding, and index updates.

FeatureManaged File SearchCustom Vector DB
Setup EffortLowHigh
ScalabilityAutomaticManual
ControlLimitedComplete

How to implement secure multi-tenant retrieval?

Multi-tenancy is critical when building a chatbot for multiple clients. You must ensure that Tenant A cannot retrieve data belonging to Tenant B by scoping retrieval queries to specific store identifiers. If your vector database contains data from multiple users, every single retrieval query must be constrained by a mandatory tenant filter or a unique store ID.

Always authenticate the user and map their session to a specific tenant ID. Use this ID as a filter or a specific reference when initializing the tool call in your Gemini API request. Without strict namespacing, a user could inadvertently gain access to private information from other accounts if the similarity search returns cross-tenant chunks that happen to be relevant to the query.

Implementation-wise, treat the tenant ID as a primary metadata field in your document storage. When issuing a search request, force the database to perform a filtering operation on the tenant identifier before calculating similarity. This creates a secure boundary that prevents the retrieval engine from even considering documents outside the authorized user's domain.

How do you handle context injection and hallucinations?

Hallucinations often occur when the retrieved context is irrelevant or noisy. You can reduce this by setting a stricter threshold for similarity scores or by using a re-ranker to confirm the top results. A re-ranker acts as a second pass, evaluating the relevance of the retrieved chunks to the specific query before passing them to the generative model.

System prompts are your first line of defense. Force the model to cite retrieved documents and explicitly instruct it to answer using only provided context or state if it does not know the answer. By standardizing the format of the context passed into the prompt, you make it easier for the model to distinguish between source data and general knowledge.

Include document metadata such as source URLs or file titles in the context passed to the LLM. When the model has access to the origin of the facts, it is far more likely to produce verifiable citations. If the model is not forced to adhere strictly to the retrieved context, it will default to its probabilistic training data, which often leads to inaccurate information when you want it to remain grounded in private files.

What are common gotchas when deploying RAG?

One major pitfall is the degradation of retrieval quality due to poor chunking strategies. If chunks are too small, they lose necessary context; if too large, the model gets overwhelmed with irrelevant data and loses focus. Experiment with chunk overlap to ensure that semantic information spanning across boundaries is preserved in both adjacent segments.

Another risk is failing to manage API rate limits during bulk ingestion. Ensure you implement exponential backoff strategies to handle API errors and maintain stability in your production environment. If you send too many documents for indexing at once, your request queue will overflow or get blocked by the provider.

Finally, watch for stale data. If a document is updated in your primary storage but not in the vector database, the chatbot will provide outdated information. Implement a reconciliation loop that tracks modification timestamps or content hashes. Whenever a source document changes, trigger a fresh background task to re-index that specific record, replacing the existing vector representation to maintain consistency.

Frequently asked questions

Why does my RAG chatbot still provide irrelevant answers?

This usually stems from poor retrieval precision. Evaluate your chunking strategy and ensure your embedding model is appropriate for your content domain. You might also need to refine your system prompt to prioritize retrieved data.

How do I handle documents that change frequently?

Implement a versioning or sync system where document IDs are tracked. When a document is updated, delete the old vector representation before triggering a new background indexing job to avoid stale data.

Can I use RAG with structured databases instead of files?

Yes, this is often called GraphRAG or SQL-to-Text. You can use LLMs to translate natural language into SQL queries, execute them, and then use the results as context for the final response.

Sources & further reading

Work with me

Building something like this?

I build AI-powered products with Next.js, Python and LLM APIs, from first prototype to production. If you need help with a project, a second opinion on your architecture, or a developer on your team, get in touch.

About the author

Tushar Gautam is a full-stack & ai product engineer in India. He builds AI SaaS products such as an AI video ad generator, a RAG chatbot platform and a Razorpay-powered report service, mostly with Next.js, Flask and the Gemini API. See the projects, GitHub or LinkedIn.

This article was drafted with the help of AI (Google Gemini) from official documentation and published by Tushar Gautam. Spotted an error? Let me know.