RAG in Production: An Engineering Guide to Retrieval-Augmented Generation

    Learn how to build a production-ready RAG system, from document parsing and hybrid retrieval to reranking, evidence-based generation, and containerized deployment. This guide covers access controls, citations, refusal policies, and evaluation practices that help turn a prototype into a maintainable knowledge-based application.

    Retrieval-augmented generation (RAG) is not about making a model memorize every document. It is about bringing relevant, traceable evidence into the context when a question is asked. For frequently updated, mixed-format data such as policies, contracts, manuals, and reports, relying on model memory alone offers little control and makes source attribution difficult.

    A production-ready system typically includes document understanding, indexing, retrieval, reranking, generation, and operational evaluation. This guide follows that engineering sequence, explaining what each layer should do, where failures commonly occur, and how containerization can separate inference services from the application.

    Define Boundaries Before Choosing an Architecture

    Start by documenting three sets of boundaries:

    • Data boundaries: Which repositories can be ingested? Do they contain personal information or trade secrets? How long should data be retained, and who can retrieve it?
    • Answer boundaries: Should the model refuse to answer when evidence is insufficient, or provide the closest available explanation? Are citations required for each paragraph?
    • Operational boundaries: What are the latency and concurrency requirements? Must inference remain on a private network? Do services need exclusive GPU access?

    Once these boundaries are clear, choose between vector-only retrieval and hybrid keyword-plus-vector retrieval. Short titles, identifiers, and specialized terms often benefit from lexical matching, while semantic similarity works better for longer passages. Production systems rarely rely on a single retrieval method.

    Reranking orders the retrieved candidates by relevance, reducing the number of noisy passages included in the prompt. The generation stage should consume only a small set of reranked passages and require citation markers, rather than producing fluent answers with no traceable sources.

    Document Understanding Sets the Quality Ceiling

    Poor question-answering performance often starts before chunking, not in the model itself. Scanned documents, multicolumn layouts, tables, headers and footers, and paragraphs spanning pages can lose their meaning when split at fixed character counts.

    A more reliable approach is to:

    • Identify document structure first. Handle heading levels, lists, tables, and image captions separately rather than flattening everything into plain text.
    • Preserve table relationships. Keep row and column associations intact. Where necessary, convert entries into short field–value statements so that questions about a metric in a particular period remain searchable.
    • Chunk along semantic boundaries. Avoid purely mechanical length-based splits. Retain a small amount of overlap between chunks to reduce the chance of splitting an answer across boundaries.
    • Attach metadata to every chunk. Include the document name, section, page number, version, effective date, and access-control labels. Citations and permission filters depend on these fields.
    • Filter document versions. When multiple versions coexist, use version numbers or effective dates to prevent outdated clauses from being retrieved.

    Before ingestion, run a sample quality check. Select questions at random and verify that the top retrieved chunks actually contain the statements needed to answer them. This is often more efficient than repeatedly switching embedding models.

    Indexing, Embeddings, and Hybrid Retrieval

    An embedding model maps text into a vector space, where semantically related questions and passages should be close together. Evaluate models on three criteria:

    • Reliability with Chinese-language content and domain terminology.
    • Vector dimensionality and storage cost.
    • Batch encoding throughput.

    Do not substitute a single public benchmark score for evaluation on your own questions. A comparison using 20–50 real questions can provide a useful starting point. Record evidence hit rates and clear examples of irrelevant retrieval.

    At the indexing layer, retain:

    • Vectors for semantic retrieval.
    • A lexical index for identifiers, proper names, and exact phrases.
    • Metadata filter fields for permissions, departments, and document versions.

    Query rewriting is not always beneficial. Simple factual questions often work best unchanged. For questions with multiple conditions or unclear references, clarifying the subject and time range before retrieval can help.

    Retrieve more candidates than you ultimately send to the generation model. For example, retrieve several dozen passages, then use reranking to reduce them to a handful. This helps preserve recall while controlling context length and cost.

    Reranking and Evidence Compression

    Vector similarity does not necessarily mean that a passage can answer the question. A reranking model scores question–passage pairs directly and can substantially reduce irrelevant results.

    Embedding, reranking, and language-model inference can run as separate services. Embedding workloads emphasize throughput and batch processing; reranking emphasizes low-latency scoring of small batches; generation emphasizes answer quality. Separating these services allows one stage to scale without overwhelming the rest of the pipeline.

    Before generation, compress the evidence by removing duplicate chunks, merging adjacent chunks from the same section, and applying permission filters again.

    The prompt should explicitly require the model to:

    • Answer only from the supplied passages.
    • Explain what information is missing when the passages are insufficient.
    • Cite passage identifiers rather than inventing page numbers.

    These constraints cannot eliminate hallucinations, but they make errors easier to verify.

    Service boundaries can be expressed as illustrative configuration rather than tied to a particular set of deployment commands:

    1. services:
    2. embed:
    3. role: batch_encode
    4. device: gpu
    5. rerank:
    6. role: cross_encoder
    7. device: gpu
    8. max_pairs: 32
    9. generate:
    10. role: chat_completion
    11. device: gpu
    12. max_context_chunks: 6
    13. index:
    14. role: vector_and_keyword
    15. persistence: object_storage_or_local_volume

    Persist indexes and model caches in separate volumes or object storage so they survive container recreation. Allocate GPU resources per service to prevent one process from consuming all available GPU memory and blocking other stages from starting.

    Expose only the application entry point and necessary administrative ports. Keep inference endpoints on the private network.

    Generation, Citations, and Refusal Policies

    The generation model should organize the answer, not add unsupported conclusions from its general knowledge.

    For policy questions, first extract the conditions, exceptions, and effective dates from the source, then reformulate them into an answer. For numerical questions, every number in the answer must appear exactly in the cited evidence. If passages conflict, present the differences and identify their versions rather than letting the model resolve the conflict on its own.

    Use a consistent citation format: document title, section, and page number or chunk identifier. The interface should let users open the corresponding source location. Without access to the underlying text, citations are merely decorative.

    Refusal behavior should be part of the product design, not left entirely to the model. For example, return a predefined explanation when:

    • The highest relevance score falls below a threshold.
    • Permission filtering leaves no results.
    • The question falls outside the knowledge base.

    The response should also indicate what types of additional material would be needed. This lets operators distinguish “unable to answer” from “answered incorrectly” instead of combining both into a single satisfaction measure.

    Deployment Options and Operational Considerations

    Local or private-network deployment suits scenarios where data must remain within a controlled environment. A typical setup runs inference services in containers, mounts data directories, maps fixed ports, configures listening addresses for private-network access, and allocates GPUs as needed.

    The application should call embedding, reranking, and chat services through a consistent inference interface rather than hard-coding model file paths into business logic.

    For cloud deployments, separate object storage, the container platform, logging, and monitoring. Store original files in object storage, run parsing tasks as horizontally scalable jobs, and serve online question answering through stateless services with retries.

    When using cloud resources such as Baidu AI Cloud, keep the architecture focused on general capabilities: object storage for source files and index snapshots, a container platform for inference and retrieval engines, and logging and monitoring for latency, error rates, and GPU utilization. Avoid coupling business logic to vendor-specific interface names.

    Before launch, verify at least the following:

    • Model and index versions can be rolled back.
    • Knowledge-base updates are clearly defined as incremental or full rebuilds, and the existing index remains queryable during updates.
    • Permissions are enforced during retrieval, not by masking answers after generation.
    • Timeouts, rate limits, and circuit breakers are configured so that one slow query cannot overwhelm the inference queue.
    • Logs capture questions, matched documents, and citations without unnecessarily recording full sensitive content.

    Evaluate Whether the System Is Actually Improving

    Use a fixed question set for offline evaluation. Measure whether:

    • Retrieved results contain the reference evidence.
    • The top reranked results include the required evidence.
    • Final answers are consistent with the evidence.
    • Refusals are appropriate.

    Online feedback alone is insufficient. Positive ratings can hide answers that sound convincing but cite the wrong sources.

    Review a sample of failures each week and classify them into five categories:

    1. Parsing errors.
    2. Chunking errors.
    3. Retrieval errors.
    4. Ranking errors.
    5. Generation that contradicts or goes beyond the evidence.

    Change one category at a time and rerun the evaluation. Replacing embeddings, chunking rules, and prompts simultaneously makes it difficult to identify what caused an improvement or regression.

    The usual priority is to fix document parsing and metadata first, add hybrid retrieval and reranking next, and consider a larger generation model last. A larger model cannot compensate for evidence that was never retrieved.

    Once evidence hit rates are consistently high on the evaluation set, improvements to context length, citation formatting, and refusal wording are more likely to produce noticeable benefits for users.

    Conclusion

    Reliable RAG combines document understanding, hybrid retrieval, reranking, constrained generation, and observable operations. It is not simply a matter of uploading files into a chat interface.

    Containerize inference services, persist indexes, enforce permissions during retrieval, and use a fixed evaluation set to distinguish the five major failure categories. These practices help a demonstration become a maintainable knowledge-based question-answering system.

    Whenever you add a document format or a departmental knowledge base, repeat the same quality checks rather than simply adding more models.