Back to Writing

RAG

Building a Production LangChain RAG Pipeline

Design a production LangChain RAG pipeline with separate ingestion and query paths, latency budgets, retrieval evals, tracing, and cost controls.

9 min read

Key takeaways

  • A production LangChain RAG pipeline has six components: ingestion, chunking, embedding, retrieval, generation, and serving.
  • Split the pipeline into an asynchronous write path for ingestion and a synchronous read path for queries, with state kept in three separate stores.
  • Set per-hop latency budgets, such as retrieval under 300ms and reranking under 200ms for a 2-second p95, and measure each hop with tracing.
  • Build a 50-200 question golden dataset and run retrieval evals like recall@k before any LLM-as-judge generation evals.
  • The most common failure modes are stale indexes, chunk-boundary answer loss, retrieval drift after re-embedding, and runaway context inflating token costs.

A production-grade LangChain RAG pipeline is six components (ingestion, chunking, embedding, retrieval, generation, serving) wired together with explicit latency budgets, eval checkpoints, and tracing at each hop. This walkthrough maps every component to concrete system design decisions, then covers the failure modes that surface only under real traffic, when your token bill and p95 latency stop being demo problems.

What are the core components of a LangChain RAG pipeline?

A production LangChain RAG pipeline has six components: ingestion, chunking, embedding, retrieval, generation, and serving. Each owns one decision, and each is where a demo that works becomes a system that bleeds money under real traffic.

Ingestion and chunking

Ingestion pulls documents from their source systems into a processable form. Chunking splits them into retrievable units using LangChain's document loaders and text splitters, which the LangChain documentation covers under its retrieval guides. Chunk size and overlap directly bound what retrieval can later find.

Embedding and vector storage

Embedding converts chunks into vectors via an embeddings model, then persists them in a vector store. This is where your per-query token bill starts: re-embedding the whole corpus on every schema change is a cost decision, not a detail.

Retrieval and generation

Retrieval fetches the top-k relevant chunks, often as a retriever composed into a chain. Generation passes retrieved context plus the user query to the LLM and returns an answer. Serving wraps the whole thing behind an API that must survive real users.

This component map is the same one I use when taking a client's demo to production (federicomolina.com).

How should a full RAG pipeline be structured for production?

A production LangChain RAG pipeline splits into two paths: an asynchronous write path that ingests and indexes documents, and a synchronous read path that answers queries. Keeping them separate means a bad upload never blocks a user, and a traffic spike never corrupts your index.

The write path: ingestion as a batch job

Run ingestion as a queued, idempotent batch job, not inline with a request. Parse and chunk documents, generate embeddings, then write vectors plus chunk metadata to your vector store in one transaction. Version every batch so you can reindex without downtime, and deduplicate on a content hash so re-running a job is safe.

The read path: query to answer

The read path is where latency budget gets spent. A typical flow: embed the query, retrieve top-k candidates, rerank, assemble the prompt, generate, then stream the answer. Cache the query embedding and, where queries repeat, the retrieved chunk sets. Set explicit timeouts on retrieval and generation so a slow vector store degrades to a smaller context window instead of a 500.

Where state and caches live

Treat state as three separate stores: vectors in the vector database, conversation and orchestration state in Postgres or Redis, and raw documents in object storage as the source of truth. Never let the vector store be the only copy of your data; reindexing is a when, not an if. The reason this split matters: teams that inline ingestion with serving hit a wall the first time real traffic arrives, because a single large document upload can stall every user request behind it. Separating the paths means ingestion failures are invisible to users, reindexing is a background operation you schedule, and the read path's latency budget stays predictable under load. That predictability is what lets you set honest timeouts, size your caches against measured query patterns, and ship changes to chunking or retrieval without touching the serving code.

If your pipeline works in demos but the architecture above is missing, that is usually the demo-to-production gap. I help teams close it; reach me at Contact.

What system design decisions matter when serving LLMs in a RAG pipeline?

Latency budgets per component

A production pipeline needs a per-hop budget, not a single "response time" target. A workable split for a 2-second p95: retrieval under 300ms, reranking under 200ms, and generation gets the rest. Measure each hop separately with tracing, because the slow hop is rarely the one you guess. LangSmith's tracing lets you attribute latency per run and per span, which is how you find a 900ms embedding call hiding behind a fast-looking average (LangSmith docs).

Model routing and token cost

Route queries instead of defaulting everything to your largest model. A classifier or small model handles greetings and simple lookups; the expensive model only sees queries that need multi-hop reasoning. Cap the token bill structurally: limit retrieved context, cap output tokens per request, and cache embeddings for repeated queries. Review routing thresholds weekly against real traffic, since query distributions drift.

Streaming and timeouts

Stream tokens to the user as they generate; perceived latency drops even when total time is unchanged. Set explicit timeouts per hop and a total request deadline, then decide the degradation path: partial answer, cached response, or retry. I cover more serving tradeoffs like these on Writing.

How do you evaluate and debug a RAG pipeline before shipping it?

Build a golden dataset first: 50-200 real questions with known source documents, pulled from actual user queries, not invented ones. Every pipeline change runs against this set before it ships.

Retrieval evals before generation evals

Measure recall@k: for each question, did the correct chunk appear in the top-k retrieved results? If recall@k is 70%, no amount of prompt engineering fixes the 30% of answers with no grounding. Retrieval metrics are cheap, deterministic, and pinpoint whether the problem lives in chunking, embedding choice, or the retriever itself. Only once retrieval is solid do LLM-as-judge evals make sense, scoring faithfulness and answer relevance on the golden set. Judge models drift, so spot-check judgments by hand.

Tracing every production query

Wire LangSmith or OpenTelemetry tracing into the pipeline from day one. Each production query should log the retrieved chunks, prompt, completion, token counts, and latency per step. When a user reports a wrong answer, you replay the trace and see whether retrieval missed the document or generation ignored it. Without traces, you are guessing; with them, most failures take minutes to diagnose.

Evals catch what you thought of; tracing catches what users actually hit. If your team lacks the senior architecture time to build both, that is exactly the gap I close through fractional CTO and AI engineering work.

What are the most common failure modes in a production RAG pipeline?

Retrieval failures

Stale indexes are the most common: your source data changed, your vector store did not, and users get confident answers from documents that no longer exist. Mitigate with incremental ingestion on a schedule plus a last_updated field you filter on at query time.

Chunk-boundary answer loss happens when the answer straddles two chunks, so neither retrieves alone. Use overlapping chunks and, for structured docs, chunk by heading rather than fixed token count.

Retrieval drift after re-embedding is the silent one. You swap embedding models, re-embed the corpus, and similarity scores shift enough that your top-k now returns different documents. Re-run your eval suite before and after any model change; if you have no evals yet, that is the first fix. Managed platforms like Dify bundle ingestion, retrieval, and observability so drift is easier to spot, though you trade away pipeline control.

Generation and cost failures

Runaway context inflates your token bill: retrieved chunks accumulate, conversation history never gets trimmed, and every turn re-pays for all of it. Set a hard context budget and truncate history deliberately.

Silent provider outages look like user churn, not alerts, because the request returns something. Add tracing on every span (this is where working with someone who has shipped this before pays off) and alert on retrieval-empty and low-confidence response rates, not just 5xx.

How does a LangChain RAG pipeline compare to alternatives like Dify or a custom AWS RAG pipeline?

The honest answer: LangChain buys you control at the cost of glue code, Dify buys you speed to demo at the cost of orchestration flexibility, and a custom AWS pipeline buys you managed infrastructure at the cost of writing and maintaining that glue yourself. Which trade matters most depends on your team size and how far your demo is from production.

LangChainDifyCustom AWS RAG pipeline
ControlCode-first, full access to retrieval and orchestration logicVisual workflows, limited to what the canvas supportsFull control, but you own every integration
Speed to productionModerate: you write the pipeline, evals, and serving layerFast to demo, slower to bend once requirements hardenSlow start: more glue code before first real traffic
Lock-inLow: Python you ownHigher: logic lives in the platformLow code-wise, but tied to AWS managed services like Bedrock Knowledge Bases, which handle ingestion, chunking, and retrieval for you (AWS docs)

For a 2-20 person team with no senior AI-architecture hire, LangChain is the middle path: no platform ceiling, but every production concern (tracing, evals, cost) is code you write.

When does a LangChain RAG pipeline stop being the best rag pipeline for your team?

Signals you've outgrown the framework

Three signals show up first. Your orchestration graph grows more branching and stateful than your actual retrieval logic, so most engineering time goes to gluing chains instead of improving answers. Your product shifts from single-shot RAG to agent-heavy workloads with loops, tool calls, and human approval steps, where the framework's abstractions hide latency and token spend you need to see. Or your team needs enforced guardrails, versioned prompts, and reproducible evals more than it needs flexibility, and the framework keeps letting developers ship untested changes to real traffic.

Build versus buy for a small team

Run the same criteria against your staffing options: who owns the architecture, how fast you can debug a production incident, and what the fully loaded cost is. Hiring a senior AI-architecture engineer takes months of recruiting plus a salary that strains a pre-seed or Series A budget. Platforms trade flexibility for speed but lock you into their retrieval and serving choices. Fractional-CTO support, like what I offer, puts a senior architect on your pipeline part-time: you keep your LangChain code where it fits, replace it where it does not, and get evals, tracing, and cost discipline set up without a full-time hire. The honest trade-off is that fractional support is not in your Slack every day, so you still need engineers who can execute the architecture between sessions.

FAQ

Is LangChain good for RAG in production, or only for prototypes?

LangChain is fine in production if you own the production concerns yourself: tracing, evals, latency budgets, and cost caps are all code you write on top of it. It becomes a bad fit when orchestration grows more stateful than your retrieval logic, or you shift to agent-heavy workloads where its abstractions hide latency and token spend.

How much does it cost to run a RAG pipeline at scale?

Costs split into per-query token spend and one-time indexing spend. You control the first by routing simple queries to small models, capping retrieved context and output tokens, and caching query embeddings. You control the second by making re-embedding a versioned batch job, not something triggered by every schema change. Measure per-hop token counts with tracing.

Do I need a vector database for a RAG pipeline?

You need somewhere to persist embeddings and chunk metadata, and a vector store is the standard choice. What you must not do is let it be your only copy of the data: keep raw documents in object storage as the source of truth, keep conversation state in Postgres or Redis, and treat reindexing as a scheduled background operation you will eventually need.

How long does it take to move a RAG demo to production?

There is no fixed timeline, but the work is concrete: split ingestion into an async write path, set per-hop latency budgets with tracing, build a 50-200 question golden dataset, and run retrieval evals before generation evals. Teams without a senior AI-architecture hire typically spend the most time on exactly these pieces, not on the pipeline code itself.

Got an AI system that works in the demo but not in production?

Book a call