Building a Retrieval-Augmented Generation System from Scratch: A Deployment and Practice Guide

    This article explains how to build and deploy a retrieval-augmented generation (RAG) system from scratch. It distinguishes model serving from a complete knowledge Q&A system, outlines criteria for evaluating open-source components, and describes an architecture that separates knowledge ingestion from online querying. It also covers containerized deployment, model service validation, document processing, chunking, metadata design, retrieval and reranking, grounded answer generation, pre-launch evaluation, and a phased path from validation to production.

    1. Define the Goal First: Model Serving or a Complete Knowledge Q&A System?

    When an organization wants to connect internal policies, product documentation, technical documents, or business materials to a large language model, two problems usually appear: the model does not know the organization’s private knowledge, and the generated answers lack verifiable evidence.

    Retrieval-augmented generation, or RAG, is mainly designed to address these two problems. The basic flow is to first find material relevant to the user’s question in a knowledge base, then pass that material to the language model as context, and let the model organize an answer and provide source clues.

    However, “deploying a model” and “building a RAG system” are not the same thing. A model inference service receives input and returns inference results. A complete knowledge Q&A system also needs to handle document management, content parsing, chunking, indexing, retrieval, access control, and quality evaluation.

    Therefore, before choosing an open-source technical solution, you should distinguish among three types of requirements:

    • You only need local inference capability: Focus on model loading, hardware compatibility, concurrency handling, and service interfaces.
    • You need knowledge base Q&A: Focus on document parsing, retrieval quality, citation accuracy, and knowledge updates.
    • You need complex business workflows: In addition to Q&A, you need conditional logic, human confirmation, business data queries, and audit records.

    These requirements can be combined, but they should not be confused. A convenient visual configuration interface does not necessarily mean better inference performance, and fewer components do not necessarily mean higher system quality. The real selection criterion is whether the solution meets business goals and whether the team can maintain it over time.

    2. Choosing Open-Source Options: Evaluate Capabilities, Not Popularity

    The value of an open-source solution is not only that it can be downloaded and deployed, but also that you can understand how it works, control the data flow, and adjust key stages according to business needs.

    It is useful to build a selection checklist around the following dimensions.

    2.1 Document Processing Capability

    If the knowledge base consists mainly of clean plain text, parsing is relatively straightforward. If it contains scanned files, multi-column layouts, complex tables, and mixed text and images, document parsing becomes a major challenge.

    Key points to verify include:

    • Whether a reasonable reading order can be restored;
    • Whether heading hierarchy, page numbers, and section positions can be preserved;
    • Whether tables retain the relationship between headers and data;
    • Whether scanned content requires an additional text recognition process;
    • Whether parsing results support manual review and correction.

    Test with your own real documents rather than judging only from sample results. Parsing errors are amplified along the downstream pipeline: incorrect text is chunked and indexed, and even accurate retrieval can only recall incorrect or incomplete information.

    2.2 Model Integration and Replacement Capability

    Generation models, embedding models, and reranking models serve different purposes and should ideally be configured and replaced independently.

    The generation model organizes the answer. The embedding model converts text into vectors used for similarity retrieval. The reranking model rescores the relevance between candidate documents and the question.

    During selection, check whether interfaces are clear, whether timeout mechanisms are controllable, whether failures can be traced, and whether model upgrades affect existing indexes. In particular, changing an embedding model usually means that document vectors must be regenerated. Even if two models produce vectors with the same dimension, you should not assume that their vectors can be mixed.

    2.3 Operations and Governance Capability

    When evaluating a solution, do not look only at whether the management page is easy to use. Also check whether it supports data backup, task retries, runtime logs, access control, configuration migration, and version rollback.

    At the same time, review the open-source license, model usage terms, and restrictions of dependency components. Open source does not mean that all scenarios can be used unconditionally, nor does it mean that model weights and software code are governed by the same licensing rules.

    3. System Architecture: Separate Responsibilities

    A typical RAG system can be organized along the following query path:

    User question → identity and access check → question processing → candidate retrieval → reranking → context assembly → answer generation → citation validation and result return

    Knowledge ingestion is a separate path:

    Document upload → content parsing → cleaning and chunking → metadata enrichment → vector generation → index writing → status confirmation

    The two paths should work together, but they do not have to run in the same process.

    For early validation, you can use fewer service components to reduce deployment complexity. For a system that needs to run continuously, prioritize isolating long-running tasks from online requests. For example, large-scale document parsing and vector generation should not permanently consume all the compute resources needed for online Q&A.

    In addition, original files, parsing results, retrieval indexes, and business metadata serve different purposes and should be managed separately. Original files are used for traceability and reprocessing; parsing results help locate content issues; indexes speed up queries; metadata carries document versions, permissions, sources, and processing status.

    4. Containerized Deployment: Easy Startup Does Not Mean Automatic Reliability

    Containerization reduces environment differences and simplifies component installation and migration, but it does not automatically solve driver compatibility, model caching, network connectivity, or data persistence issues.

    4.1 Check Resources and Compatibility Before Deployment

    Confirm the host’s compute resources, memory, storage space, and network conditions in advance. If GPUs are used, verify the compatibility among host drivers, the container runtime environment, and inference components.

    Whether a model can run should not be judged only by parameter size. GPU memory usage is also affected by numerical precision, quantization method, context length, concurrency level, and runtime caching. Resource planning should therefore be based on actual load testing.

    Disk space also needs headroom: model files, download caches, document copies, parsing intermediates, indexes, and logs can all keep growing.

    4.2 Define Persistent Directories

    Model caches, uploaded documents, and index data should not exist only in a container’s temporary file system, or they may be lost when the container is recreated.

    A general directory layout can look like this. This is only a generic organization example, not a fixed requirement for any specific product:

    1. /data/
    2. model-cache/
    3. source-documents/
    4. parsed-documents/
    5. search-index/
    6. application-data/
    7. logs/

    In addition to mounting directories, verify read and write permissions, disk capacity, and backup methods. For databases or indexes that are continuously written, do not assume that copying a directory will always produce a consistent backup. Use the backup or snapshot mechanisms supported by the relevant component.

    4.3 Separate Listen Addresses from Access Entry Points

    A service listening on all network interfaces can help containers communicate with one another, but it does not mean the service should be directly exposed to the external network.

    It is advisable to set separate access scopes for the management entry point, inference service, and data storage, and expose only the entry points required by the business. Model management functions especially need authentication to prevent unauthorized users from loading models, consuming resources, or reading configuration.

    4.4 Pin Versions and Keep Rollback Paths

    During validation, you can try new versions quickly, but a long-running system should pin application versions, dependency versions, and model versions to avoid interface incompatibilities or behavior changes after component upgrades.

    Before upgrading, record the configuration, back up data, and check database migrations, model calls, and index queries in a test environment. Rollback also needs to consider data formats: the ability to roll back the program does not guarantee that upgraded data can be read by the old version.

    5. Model Service Deployment: Validate Individual Capabilities Before Integration

    Model services can be divided into three types:

    Service type Core responsibility Main validation points
    Generation service Generate answers based on questions and context Input length, concurrency, timeout, streaming output
    Embedding service Convert text into vectors Output dimension, input limits, batching, version consistency
    Reranking service Rescore candidate passages Input format, candidate size, latency, relevance quality

    Validate each service one by one rather than starting all components at once and then troubleshooting.

    First confirm that the generation service can handle short inputs, then test longer contexts and concurrent requests. Next, validate the embedding service and ensure that documents and questions use a consistent vectorization strategy. Finally, connect the reranking service and check whether it actually improves candidate ordering.

    Model acquisition also needs engineering management. Download channels should be based on legitimate authorization, file integrity, and network reachability. Preparing caches, checksum files, and model version records in advance can reduce the risk of repeated downloads on every restart.

    6. Knowledge Ingestion: The Key Step That Sets the Quality Ceiling

    6.1 Clean Content Without Breaking Factual Boundaries

    After document parsing, you can remove repeated headers and footers, meaningless whitespace, and obvious recognition noise. However, do not remove qualifiers, scope of application, or exception clauses just to make the text “flow better.”

    For example, in a policy document, a phrase such as “only applicable to a certain group of people” may be more important than the operational instructions that follow. Missing such conditions can make an answer look correct while being misleading in business terms.

    6.2 Chunking Must Balance Semantics and Retrieval Granularity

    If chunks are too short, context may be lost. If chunks are too long, the topic may be diluted and model input costs may increase.

    In practice, prioritize chunking along headings, paragraphs, lists, and table boundaries, then control length according to model input limits. Appropriate overlap between adjacent chunks helps preserve cross-paragraph semantics, but too much overlap increases index size and duplicate retrieval.

    There is no fixed chunk length that works for all documents. Technical manuals, contract clauses, FAQs, and meeting notes usually have different optimal chunking approaches.

    6.3 Metadata Must Be Part of the Design

    Each chunk should ideally retain the document identifier, source position, version, update time, and permission labels. This supports citation construction and also allows old versions to be deleted or outdated content to be located when knowledge is updated.

    For permission-sensitive materials, access filtering should be performed at the retrieval stage. Do not pass content the user is not allowed to access to the model and then rely on prompts to ask the model to keep it confidential.

    7. Retrieval and Reranking: Get Relevant Material into Context

    Vector retrieval is good at finding semantically related content, but keyword retrieval is often valuable for identifiers, exact terminology, and special abbreviations. Therefore, you can combine semantic retrieval and keyword retrieval according to the characteristics of the data, then deduplicate and rank the candidate results.

    Reranking is usually used when the candidate set is large and initial recall contains a lot of noise. It can improve the ordering quality of relevant passages, but it adds inference overhead. Whether to enable it should be decided through testing of quality and latency.

    It is especially important to be clear that reranking can only reorder content that has already been recalled. If the correct material never enters the candidate set, reranking cannot bring it back.

    When assembling context, also avoid repeatedly inserting similar chunks from the same document into the model. A better approach is to select complementary evidence based on relevance, information coverage, source reliability, and input length budget.

    8. Answer Generation: Provide Answers and Verifiable Evidence

    At the answer stage, the model should be explicitly required to answer based on the provided material and to state when it cannot confirm something due to insufficient evidence. If the material contains contradictions, the system should show the conflict and its sources rather than arbitrarily merging them into a definitive conclusion.

    Citations need to establish a traceable relationship from the answer to the chunk and then to the original document. A citation marker on the page does not prove that the marker actually supports the neighboring conclusion. Tests or manual spot checks should confirm that the cited content is consistent with the answer statement.

    Knowledge base documents may also contain instructions designed to induce the model to change its behavior. The system should therefore treat retrieved content as data to be analyzed, not as higher-priority operating instructions. Capabilities involving external actions should also have separate authorization and confirmation mechanisms.

    9. Pre-Launch Evaluation: Locate Problems at Specific Stages

    Prepare a test set that covers real business scenarios, including:

    • Questions that can be answered directly from the material;
    • Questions that require combining multiple chunks;
    • Questions containing exact identifiers or specialized terminology;
    • Questions whose answers do not exist in the material;
    • Questions involving permission restrictions or version conflicts.

    Evaluation should separately observe parsing correctness, recall, ranking quality, answer accuracy, citation support, response latency, and failure rate rather than giving the system only a vague overall score.

    When an answer is incorrect, troubleshoot along the pipeline:

    1. Does the original material contain the answer?
    2. Is the parsing result complete?
    3. Did chunking break key semantics?
    4. Was the correct chunk recalled?
    5. Did reranking place it in an appropriate position?
    6. Was the context truncated due to length limits?
    7. Did the model faithfully use the evidence?

    This troubleshooting approach is more effective than repeatedly changing the generation model, and it is easier to turn into reusable optimization experience.

    10. From Validation to Production: Use a Phased Strategy

    In the first phase, use a small set of real documents to run through the complete pipeline and confirm that the system can generate answers with source evidence.

    In the second phase, focus on improving document processing and retrieval quality, build a stable test set, and record the performance of different chunking strategies, model configurations, and retrieval strategies.

    In the third phase, add authentication, permission filtering, log masking, backup and recovery, resource monitoring, and rate limiting.

    Finally, add task queues, service replicas, or dedicated compute resources according to business load. Before scaling, identify the bottleneck first: latency may come from document retrieval, reranking, model queuing, or answer generation, and it is not always necessary to scale every component.

    A reliable RAG system is essentially the result of data processing, retrieval engineering, model inference, and security governance working together. Containerization lowers the barrier to environment delivery, and open-source components provide flexible composition options, but the final quality still depends on material quality, pipeline design, and continuous evaluation. Starting with a verifiable minimum closed loop and then gradually improving production capabilities is usually more reliable than stacking many components at once.