Containerized Deployment and Productization of RAG Systems: Architecture, Operations, and Quality Practices

    Retrieval-augmented generation (RAG) combines external knowledge retrieval with language model generation. This article explains how to move a RAG system from a chat demo to a maintainable business deployment. It covers logical service boundaries, offline and online data flows, resource planning for generation, embedding, and reranking, containerization boundaries, persistent data, readiness checks, document parsing and chunking, hybrid retrieval and reranking, application orchestration, citation validation, troubleshooting by layer, security controls, and evaluation and acceptance. The focus is on traceable evidence chains and maintainable operations rather than simply stacking components.

    1. From “the Model Can Answer” to “the System Has Evidence”

    Retrieval-augmented generation (RAG) is a technical approach that combines external knowledge retrieval with language model generation. The system first retrieves relevant content from an authorized knowledge scope based on the user’s question, then passes the retrieved results to the model as context, and finally generates an answer.

    The goal is not to make the model memorize all enterprise materials. Instead, it is to let the model use currently accessible knowledge when answering. For scenarios such as internal policy queries, technical documentation Q&A, and business process explanations, this approach is usually easier to update and easier to trace back to evidence than relying solely on the model’s existing knowledge.

    However, connecting a knowledge base does not guarantee accurate answers. Document parsing errors, unreasonable chunking, irrelevant retrieval results, insufficient context, and incorrect interpretation of evidence by the model can all cause answer deviations. Therefore, deployment must cover the full chain rather than stopping at opening a chat page.

    In practice, the system can be divided into five types of capabilities:

    1. Generation model service: organizes answers based on questions and evidence.
    2. Embedding service: converts questions and document chunks into comparable vectors.
    3. Reranking service: further judges the relevance between candidate chunks and the question.
    4. Knowledge processing and retrieval service: handles document parsing, index construction, and candidate recall.
    5. Application orchestration service: connects retrieval, generation, citation display, and business entry points.

    These are logical responsibilities, not a requirement to run exactly five independent containers. When resources are limited, services can be combined. When facing multi-user access, continuous updates, or high availability requirements, they should be split according to load and failure boundaries.

    2. Clarify the Architecture Before Deployment

    It is recommended to divide the system into an offline knowledge processing chain and an online question-answering chain.

    Offline chain:

    Raw documents → text and structure parsing → content cleaning → document chunking → vector generation → index writing

    Online chain:

    User question → identity and permission verification → candidate retrieval → reranking → context assembly → model generation → citation validation and return

    Supporting capabilities such as configuration management, logging, monitoring and alerting, and backup and recovery are also required.

    2.1 Define Data Contracts Between Services

    Even if each component can start independently, they may fail to work together because request formats or field meanings are inconsistent. Before deployment, clarify the following:

    • What message structure the generation service accepts and how it returns full answers or streamed results.
    • Whether the embedding service supports batch input and what the output vector dimension and data type are.
    • Whether the reranking service returns scores or sorted results after receiving a question and candidate chunks.
    • How the retrieval service returns document identifiers, chunk positions, versions, and permission information.
    • How the application service associates citations with source materials.

    Do not assume that interfaces from different implementations are naturally compatible. Even when request fields look similar, verify error responses, timeout behavior, input length limits, and batch processing semantics.

    2.2 Separate Business Entry Points from Internal Services

    User-facing entry points can be exposed through a unified gateway, but models, indexes, task scheduling, and internal management services should not be exposed to the public internet by default.

    The fact that a developer can access a port on a local machine only proves that a local connection works. It does not mean containers can communicate using the same address. For different containers, the loopback address usually points to each container’s own runtime environment, not to another service. Internal calls should use service addresses in the container network or explicitly configured host addresses.

    3. Resource Planning Determines Whether Deployment Runs Stably

    3.1 GPU Memory Demand for Generation Models Comes from More Than Weights

    In addition to model weights, inference requires runtime buffers, context caches, and resources occupied by the computing framework. Context length, concurrent request count, and output length all affect actual GPU memory usage.

    Therefore, you cannot judge whether a GPU is sufficient based only on model file size. A more reliable approach is to start with conservative context and concurrency settings, complete single-request tests, then gradually increase load while observing peak memory, queueing time, and failures.

    Reducing weight precision may lower memory requirements, but its effect, compatibility, and answer quality must be confirmed through actual testing. It should not be treated as a cost-free optimization.

    3.2 Control Competition When Multiple Models Share Accelerators

    Generation, embedding, and reranking tasks may compete for the same accelerator. During bulk knowledge import, embedding tasks continuously occupy resources and can easily affect the response speed of online question answering.

    Small-scale deployments can mitigate contention by limiting import concurrency, scheduling processing during off-peak hours, and queuing tasks. As business volume grows, offline processing and online inference should be separated to avoid a large document update slowing down all user requests.

    3.3 Document Processing Can Also Become a Bottleneck

    Scanned file recognition, complex table extraction, and batch text cleaning can consume significant CPU, memory, and disk resources. Deployment planning should not focus only on GPUs. It should also evaluate:

    • Storage space for raw files and intermediate parsing results.
    • Growth rate of vector indexes and metadata.
    • Memory peaks during bulk import.
    • Network bandwidth for file uploads and service calls.
    • Time windows required for backup and rebuild.

    4. Containerized Deployment: Boundaries Matter Beyond Convenience

    Containerization can unify runtime environments, but it does not automatically eliminate driver, permission, network, and version compatibility issues.

    4.1 Pin Versions and Preserve Traceable Configuration

    Production environments should record image versions, model file versions, application configuration, and index construction parameters. Do not rely long-term on version tags that point to constantly changing content; otherwise, the same deployment description may produce different results at different times.

    Model updates require particular care. Replacing a generation model mainly affects answer behavior. Replacing an embedding model may change the entire retrieval space and often requires regenerating document vectors and rebuilding the index. Even if the old and new vectors have the same dimension, they should not be assumed to be interchangeable.

    4.2 Identify Which Data Must Be Persistent

    Containers can be rebuilt at any time, but business data must not be lost as a result. At a minimum, distinguish among:

    • Model weights and download caches.
    • Raw documents.
    • Parsing results and chunk data.
    • Indexes and business metadata.
    • Application configuration and necessary runtime records.

    Persistence is not the same as backup. A consistent backup plan should be defined based on the underlying storage method, and the recovery process should be actually verified. Some indexes can be rebuilt from source documents, but rebuild time may not meet business recovery requirements.

    4.3 Use Conceptual Configuration to Check Deployment Completeness

    The following is only an illustration of deployment planning and does not correspond to the configuration syntax of any specific tool:

    1. Generation service:
    2. Listen on the internal network
    3. Persist the model directory
    4. Limit request concurrency
    5. Set call timeouts
    6. Knowledge processing service:
    7. Persist the source document directory
    8. Queue import jobs
    9. Record document versions
    10. Allow failed jobs to retry
    11. Application service:
    12. Enforce unified identity verification
    13. Configure internal service addresses
    14. Retain request trace identifiers
    15. Expose only necessary endpoints

    In actual implementation, confirm configuration items against the official documentation of the chosen implementation. Do not directly apply unverified interface names or parameters.

    4.4 Check “Readiness,” Not Just “Process Alive”

    A model service may still be loading weights after startup. A knowledge service may still be waiting for an index storage connection after startup. The existence of a process does not mean it can handle business requests.

    It is recommended to check service liveness, business readiness, and critical dependencies separately. Requests should be routed to a service only after model loading, dependency connections, and necessary initialization are complete.

    5. Knowledge Processing Quality Determines the Retrieval Ceiling

    5.1 First Confirm Whether Parsing Results Are Trustworthy

    After knowledge is ingested, sample the actual extracted text instead of checking only the upload status.

    Common issues include disordered reading order on multi-column pages, table titles separated from values, repeated headers and footers, and OCR errors in scanned text. For business processes that depend on tables, column names, units, and row-column relationships must be preserved; otherwise, the model may receive chunks that look complete but are semantically incomplete.

    Content that cannot be parsed reliably should be clearly marked and sent to manual processing or a specialized parsing workflow. “Processing succeeded” should not be equated with “knowledge is usable.”

    5.2 Chunking Must Balance Completeness and Retrieval Precision

    If chunks are too long, multiple topics are easily mixed together. If chunks are too short, conditions, definitions, and context may be lost. Reasonable chunking should respect semantic boundaries such as headings, paragraphs, lists, tables, and process steps.

    A moderate overlap can be retained between chunks to reduce the risk of losing boundary information, but excessive overlap increases index size and fills retrieval results with duplicate content.

    Each chunk should retain document source, section path, version, update time, permission tags, and location information. These are used not only for displaying citations but also for filtering outdated content, enforcing permission control, and troubleshooting errors.

    5.3 Keep Document Updates Consistent

    The update process should distinguish among additions, modifications, and deletions. Repeated uploads should not generate unlimited duplicate chunks, and after a source document is deleted, content should no longer be returned from the old index.

    Stable identifiers can be established for documents and chunks, and the source document, chunks, and index for the same version should remain linked. For important knowledge updates, build and validate the new version first, then switch to the available version to reduce the risk of users retrieving a half-updated state.

    6. Retrieval and Reranking: Get the Right Evidence into Context

    Vector retrieval is suitable for finding semantically similar content, but it is not always the most reliable for identifiers, abbreviations, and exact terminology. Keyword retrieval can supplement these capabilities. When needed, hybrid retrieval can merge candidate sets from different sources before deduplication and reranking.

    Scores from different retrieval methods are usually not on the same scale and cannot simply be added together as a unified relevance score. Fusion strategies should be validated with a test set.

    Reranking provides a more detailed relevance judgment for candidate chunks, but it cannot recover evidence that was not recalled by the initial retrieval, and it adds computational overhead. Therefore, ensure recall coverage first, then optimize ranking.

    In particular, a relevance score is not the probability that an answer is correct. If score thresholds are used, they should be calibrated based on the system’s real data rather than chosen arbitrarily.

    Before entering the generation stage, you should also:

    • Remove duplicate or near-duplicate chunks.
    • Filter out unauthorized and expired content.
    • Preserve important definitions, applicability conditions, and source information.
    • Control the total amount of evidence according to the context budget.
    • Retain version and time clues when evidence conflicts.

    More retrieval results are not necessarily better. A large amount of irrelevant content can dilute key evidence and increase the risk of the model misusing information.

    7. Application Orchestration: Make Answers Explainable and Controllable

    The application layer should not merely forward questions to the model. It needs to handle identity and permissions, retrieval scope, conversation context, failure degradation, and result display.

    Generation instructions should require the model to base answers on the provided evidence. When evidence is insufficient, the model should clearly state that it cannot confirm rather than inventing clauses, numbers, or processes. When analysis or inference is required, inference should be distinguished from source facts.

    Citations must also be validated. At a minimum, the system should confirm that the citation identifier belongs to the authorized retrieval results for the current request and can be located in a real document. The existence of a citation only proves that a source exists; it does not prove that the source supports the current conclusion. High-risk business scenarios still require further review of the relationship between evidence and answer.

    Conversation history should not accumulate indefinitely. The scope of the previous question, document permissions, or version may differ from the current request. Each turn should reassess retrieval needs and control how much history is passed to the model.

    8. Troubleshooting Should Verify the Chain Layer by Layer

    8.1 Service Cannot Be Reached

    Check the process, listening address, container network, port mapping, and access control in sequence, then check whether the calling address is incorrect. Do not begin by disabling all security restrictions.

    8.2 Model Loading or Inference Fails

    Check model file integrity, runtime environment compatibility, GPU and memory peaks, and whether input exceeds limits. Validate with short input and a single request first, then gradually expand context and concurrency. This helps locate resource boundaries.

    8.3 Document Import Fails

    Check file size, parsing task status, directory permissions, index writing, and embedding output dimensions. When the index definition and embedding results are inconsistent, correct the configuration and rebuild affected data. Do not bypass the issue by truncating or zero-padding.

    8.4 Answer Exists but Lacks Correct Evidence

    Inspect the parsed text, recalled chunks, reranking results, final context, and model output separately. If correct evidence never enters the context, prioritize fixing knowledge processing and retrieval. If sufficient evidence has been provided but the answer is still wrong, then check generation instructions and model behavior.

    9. Security Controls Should Cover the Entire Data Chain

    Permission filtering should cover recall, reranking, context assembly, and citation display, not just hide document titles on the final page. Unauthorized content should not enter the model context.

    Knowledge documents may also contain text designed to induce the model to perform other actions. The system must treat retrieved content as data to be analyzed, not as trusted instructions. Capabilities involving external operations should have independent authorization, input validation, and necessary human confirmation.

    Logs should also follow the principle of minimization. Questions, retrieved chunks, and answers may contain sensitive information and should be redacted as needed, with access restricted and retention periods set. Credentials should not be written into public configuration, images, or ordinary business logs.

    10. Complete the Productization Loop with Evaluation and Acceptance

    Before launch, prepare a test set covering typical questions, exact terminology, cross-document queries, insufficient evidence, document conflicts, and unauthorized access, and record the expected evidence.

    Evaluation should cover at least four aspects:

    • Retrieval quality: whether correct evidence is recalled and ranked in a reasonable position.
    • Answer quality: whether conclusions are supported by evidence and whether key conditions are missing.
    • Operational quality: response latency, concurrency stability, error rate, and resource usage.
    • Governance quality: whether permissions take effect, updates are timely, and backups can be restored.

    Testing should separately cover idle states, multi-user question answering, and bulk import periods. Do not judge system capability based only on a single demonstration.

    A gradual acceptance approach is recommended: first validate the generation service, then validate embedding and reranking, then connect a small set of representative documents and complete the full question-answering chain, and finally add permissions, monitoring, backup, and stress testing.

    The value of a RAG system lies not in how many components are stacked together, but in whether it can form a traceable evidence chain and a maintainable operation chain. Only when documents can be parsed correctly, knowledge can be recalled accurately, answers can be verified, permissions can be enforced, and failures can be located does a deployment truly move from a technical demo to a sustainable business system.