top of page

RAG in Production Building Better Pipelines Chunking and Framework Choices

10 minutes ago
8 min read

A prototype that answers five demo questions is easy. A production system that answers thousands of real questions, with incomplete wording, stale documents, access rules, and measurable quality, is a different project.


That gap is where many retrieval systems fail. The model gets blamed for hallucinations, but the root cause often sits earlier in the pipeline: weak document parsing, careless chunking, poor metadata, missing evaluation, or a framework choice that hides too much of the retrieval path.


The idea behind RAG is straightforward. Retrieve relevant information first, then pass it to a language model so the answer is grounded in source material. The term comes from the 2020 paper Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks by Patrick Lewis and coauthors. The production version is less simple. It is an engineering system with moving parts that need tests, logs, and version control.


Wide-angle view of a glowing server rack surrounded by labeled paper folders

RAG: A production pipeline needs clear stages

A good retrieval augmented generation system has more than a vector database and a prompt template. It usually has two pipelines: one for ingestion and one for answering.


The ingestion pipeline turns raw material into searchable units. The answer pipeline finds those units, ranks them, and gives the model enough context to answer.


A practical production flow looks like this:


  1. Collect the source data


    Sources may include PDFs, HTML pages, Markdown files, support tickets, product docs, API references, database rows, or transcripts. Each source type has different failure modes. PDFs may lose table structure. HTML pages may include nav text. Transcripts may need speaker labels.


  2. Parse and clean the content


    This step removes boilerplate, normalizes headings, keeps tables readable, and preserves links or page numbers. Bad parsing creates bad retrieval. If a PDF parser turns a two-column document into scrambled lines, no embedding model can fully fix it.


  3. Split content into chunks


    The system creates units small enough to retrieve and fit into a model context window, but large enough to keep meaning. Chunking deserves its own section because it drives answer quality.


  4. Attach metadata


    Metadata can include document title, product version, date, author, access group, source URL, section heading, language, and document type. This lets the system filter before retrieval, not after.


  5. Create embeddings and indexes


    Embeddings map text into vectors for semantic search. Many systems also keep a keyword index, often based on BM25, a long-used ranking function in search systems such as Apache Lucene and Elasticsearch.


  6. Retrieve, rerank, and assemble context


    Vector search finds likely matches. Keyword search catches exact terms, part numbers, error codes, and names. A reranker can reorder the top candidates before the model sees them.


  7. Generate an answer with citations


    The prompt should tell the model how to use sources, how to handle missing evidence, and how to cite retrieved passages. The answer should expose source references when trust matters.


  8. Log and evaluate


    Production systems need traces of retrieved chunks, model inputs, outputs, latency, failures, and user feedback. Without these records, quality issues become guesses.


A simple rule helps: treat retrieval results as data, not magic. Store them, inspect them, compare versions, and test changes with the same care used for application code.


Chunking is where many systems win or lose

Chunking looks like a preprocessing detail. In practice, it controls what the model can know.


A chunk should answer one clear question or provide one coherent piece of evidence. If it is too small, it loses context. If it is too large, it brings irrelevant text and wastes the context window.


Fixed-size chunks are a starting point, not a finish

Fixed-size chunking splits text by token or character count, often with overlap. It is simple and repeatable. It works reasonably well for plain prose, such as a long help article.


For example, a 700-token chunk with 100 tokens of overlap might keep neighboring sentences together. This can prevent a definition from being separated from the paragraph that explains it.


The weakness is clear: fixed-size chunking ignores structure. It can split a table, separate a heading from its section, or cut a code example in half.


Structure-aware chunking usually performs better

Many production systems improve retrieval by respecting document structure:


  • Keep headings with the text below them.

  • Keep list items together when they form one procedure.

  • Keep table rows and headers together.

  • Keep code blocks intact.

  • Use section hierarchy as metadata.


A product manual gives a useful example. A question like “How do I reset the device after error E14?” might need the heading, the warning note, and the step list. If the error code lands in one chunk and the reset steps land in another, retrieval may return only half the answer.


Semantic chunking can help with mixed content

Semantic chunking splits text based on topic shifts instead of a fixed size. This can help with long pages that cover several unrelated topics. It can also reduce noisy retrieval because each chunk carries a tighter meaning.


The tradeoff is complexity. Semantic methods can cost more to run, and they may behave differently as models change. Teams should test them against real questions rather than assume they work better.


Overlap is useful but easy to overdo

Chunk overlap reduces boundary problems, but too much overlap fills the index with near-duplicates. That can crowd search results with repeated text. A reranker may help, but the cleaner fix is often better chunk boundaries.


A good benchmark is simple: take a set of real or realistic questions, inspect the top retrieved chunks, and ask whether a human could answer from them. If not, the chunking strategy needs work.


Close-up view of colorful index cards sorted into small labeled boxes

Data preparation matters as much as model choice

A stronger language model can hide retrieval weaknesses during a demo. It cannot reliably fix broken data.


Production data preparation should answer four questions.


What content should enter the index

Not every document belongs in the searchable set. Old policies, duplicate pages, draft articles, and archived product versions can create conflicting answers. If the system retrieves a 2021 support article for a 2025 product question, the answer may sound confident and still be wrong.


Good ingestion pipelines use rules such as:


  • Index only published documents.

  • Keep archived content separate.

  • Tag each product version.

  • Remove exact duplicates.

  • Record the source system and ingestion date.


These rules also make rollbacks easier. If a bad import pollutes the index, the team can remove one batch instead of rebuilding everything by hand.


How should metadata support retrieval

Metadata is not decoration. It lets the system narrow the search before ranking.


For instance, a software documentation system might filter by:

Metadata field

Why it matters

`product_version`

Prevents answers from mixing old and current behavior

`document_type`

Separates API reference from tutorials

`access_group`

Keeps private content out of public answers

`last_updated`

Helps prefer current material

`section_path`

Gives the model useful context and improves citations


Access control deserves special care. If users have different permissions, the retrieval layer must enforce those permissions before content reaches the model. Filtering after generation is too late.


How should tables, code, and images be handled

Tables often break during parsing. A table about pricing tiers, error codes, or configuration flags may become a confusing sequence of lines. Better approaches include converting tables to Markdown, storing rows as structured records, or creating summaries while preserving the original table as a citation source.


Code needs similar care. Keep code blocks whole. Include file names or language labels as metadata when possible. For API docs, method names and parameter names should also be searchable with keyword search, not just embeddings.


Images are harder. If images contain important information, such as architecture diagrams or screenshots with settings, the ingestion process may need captions, OCR, or human-written descriptions. Otherwise, the system will miss evidence that readers can see in the source document.


How should the system handle freshness

Production content changes. Policies expire, release notes add features, and support articles get corrected.


A reliable ingestion job should track:


  • Source document ID

  • Content hash

  • Last modified date

  • Index version

  • Embedding model version

  • Chunking method version


These fields make changes traceable. They also help compare retrieval quality after a chunking update or embedding model change.


Retrieval quality needs measurement, not opinion

The most useful production question is not “Does the answer sound good?” It is “Did the system retrieve the right evidence?”


Evaluation should separate retrieval from generation. If the retriever fails, the generator may still produce a fluent answer. That can hide the real defect.


Common retrieval checks include:


  • Recall at k

    Did the correct source appear in the top few retrieved results?


  • Precision

    How many retrieved chunks were actually useful?


  • Citation accuracy

    Did the cited source support the answer?


  • Refusal behavior

    Did the model say it lacked evidence when the index did not contain an answer?


  • Latency

    Did retrieval, reranking, and generation finish within the product’s needs?


For a small system, a spreadsheet of test questions can work. Each row can include the question, expected source document, acceptable answer points, and notes. As the system grows, teams often move these tests into automated evaluation jobs.


The test set should include difficult cases:


  • Questions with exact identifiers, such as error codes

  • Questions that require recent documents

  • Questions with no answer in the corpus

  • Questions where two versions conflict

  • Questions that require a table or code block

  • Questions written in user language rather than document language


Human review still matters. Automated scores can show trends, but a person should inspect retrieval results before major changes go live.


LangChain and LlamaIndex solve different parts of the problem well

LangChain and LlamaIndex are two common choices for building these systems. Both can help connect models, retrievers, prompts, tools, and data sources. The better choice depends on what the system needs to make explicit.


LangChain started as a broad framework for building applications around language models. It includes chains, agents, tool calling patterns, integrations with model providers, vector stores, and tracing through LangSmith. It is often useful when the application needs many steps beyond retrieval, such as tool use, routing, or multi-step workflows.


LlamaIndex has a strong focus on connecting private or domain data to language models. Its concepts around documents, nodes, indexes, retrievers, query engines, and data connectors fit naturally with ingestion and retrieval work. It is often a good fit when the main challenge is preparing, indexing, and querying a knowledge base.


A fair comparison looks like this:

Choice area

LangChain

LlamaIndex

Main strength

Building model-driven application flows with many integrations

Data ingestion, indexing, and retrieval-centered applications

Retrieval work

Supports many retrievers and vector stores

Provides detailed abstractions for documents, nodes, indexes, and query engines

Workflow control

Strong when combining models, tools, and steps

Strong when querying structured and unstructured knowledge sources

Learning curve

Can feel broad because it covers many application patterns

Can feel more focused if the main task is knowledge retrieval

Best fit

Assistants that call tools, route tasks, and use retrieval as one part

Knowledge systems where retrieval quality is the core issue


This is not a permanent either-or choice. Some teams use LlamaIndex for ingestion and retrieval, then use LangChain for orchestration around the model. Others keep the stack smaller and choose one framework to reduce complexity.


The deciding questions are practical:


  • Can the team inspect each retrieved chunk before generation?

  • Can the system enforce metadata filters and permissions?

  • Can ingestion be rerun and versioned?

  • Can evaluation run outside the demo path?

  • Can engineers replace one part, such as the vector store or reranker, without rewriting the whole system?


Frameworks help, but they should not hide the retrieval path. Production teams need enough visibility to debug wrong answers.


Eye-level view of two labeled toolboxes beside a stack of technical manuals

Build for inspection before scale

A production retrieval system becomes easier to improve when every step leaves evidence. Store the parsed text. Store chunk IDs. Store metadata. Log retrieved chunks. Record prompt versions. Track embedding and index versions. Keep evaluation questions in source control.


Start with a small, high-quality corpus and a test set that reflects real use. Improve parsing before changing models. Improve chunking before adding more tools. Add hybrid search when exact terms matter. Use reranking when the top results are noisy. Choose LangChain, LlamaIndex, or both based on the control the system needs, not based on popularity.


The strongest systems do not rely on the model to rescue weak retrieval. They give the model clean evidence, clear instructions, and traceable sources. That is the practical path from a convincing demo to a system people can trust.


bottom of page