You ask your company chatbot about the refund policy and it answers confidently, fluently and wrongly. The model never saw your policy document, so it filled the gap with something that sounds plausible. This is the problem that RAG architecture exists to solve.
Retrieval-augmented generation (RAG) gives a language model the right information at the moment it answers, instead of hoping the model memorised it. This guide is for developers who want to understand how a RAG system is put together, build a small working version in Node.js, and know where the real problems hide in production.
Direct answer: what is RAG?
- RAG is a pattern where an application retrieves relevant documents from your own data and passes them to an LLM as context, so the model generates an answer grounded in that data.
- The core components are an ingestion pipeline (chunk, embed, store), a retriever (usually vector search, often combined with keyword search) and a generator (the LLM prompt).
- Use RAG when answers depend on private, frequently changing or large knowledge. It changes what the model sees, not what the model is.
- RAG reduces unsupported answers but does not eliminate them. Retrieval quality is the most common point of failure.
Table of contents
- What RAG is and why it exists
- How RAG architecture works
- The components of a RAG system
- Build a minimal RAG pipeline in Node.js
- Beyond naive RAG: what improves retrieval
- RAG in real products: an engineering view
- Common RAG mistakes
- Best practices
- Frequently asked questions
- Conclusion
- References
What RAG is and why it exists
A large language model knows what was in its training data up to a cutoff date. It does not know your internal wiki, last week's pricing change or a customer's ticket history. It also cannot tell you where an answer came from.
The idea behind RAG comes from the 2020 paper Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks by Lewis et al., which combined a retriever with a generator. Modern applications use a simpler version of the same idea: search your data first, then put the best results into the prompt.
That design gives you three practical benefits:
- Fresh knowledge. Update a document and the next answer reflects it. No retraining.
- Source attribution. You know which chunks the answer used, so you can show citations.
- Access control. You decide which documents a given user may retrieve, which is much harder to enforce inside model weights.
How RAG architecture works
A RAG system has two flows. The ingestion flow runs ahead of time (or on every content change). The query flow runs on every user question.
flowchart TD
subgraph Ingestion
A[Source documents] --> B[Clean and chunk]
B --> C[Embedding model]
C --> D[(Vector store plus metadata)]
end
subgraph Query
Q[User question] --> E[Embed the question]
E --> F[Similarity search]
D --> F
F --> G[Top-k chunks]
G --> H[Prompt with context]
Q --> H
H --> I[LLM]
I --> J[Answer with citations]
endIn words: documents are split into chunks, each chunk is converted into an embedding (a vector of numbers that represents meaning), and the vectors are stored. At question time, the question is embedded the same way, the closest chunks are found, and those chunks are placed in the prompt. The model answers from that context.
The components of a RAG system
Chunking
Chunking decides what a "unit of knowledge" is. Chunks that are too small lose context; chunks that are too large dilute the match and waste tokens. A reasonable starting point is a few hundred tokens with a small overlap, split on natural boundaries such as headings and paragraphs. Treat the numbers as a starting point to tune against your own questions, not a rule.
Embeddings
An embedding model maps text to a vector so that similar meanings land close together. OpenAI's embeddings guide lists text-embedding-3-small (1536 dimensions by default) and text-embedding-3-large (3072 by default), both with an 8192-token input limit. Use the same model for documents and queries. Vectors from different models are not comparable.
Vector store
The store holds vectors plus metadata (source, section, access level, updated date) and answers nearest-neighbour queries. Options range from a Postgres table with the pgvector extension to dedicated vector databases. Our deeper comparison is in Vector Databases Explained.
Retriever
The retriever turns the question into a ranked list of chunks. Pure vector search is the simplest version. Production systems often add keyword search, metadata filters and a reranker (covered below).
Generator
The generator is the LLM call. The prompt tells the model to answer only from the supplied context, to say so when the context is insufficient, and to cite sources. That instruction matters as much as the retrieval.
Build a minimal RAG pipeline in Node.js
The example below is intentionally small: an in-memory store, cosine similarity and two API calls. It is a learning scaffold, not production code. It uses the official openai package and Node.js 20 or later.
npm install openai
// rag.mjs: minimal RAG, in-memory store (learning example, not production-ready)
import OpenAI from "openai";
const openai = new OpenAI(); // reads OPENAI_API_KEY from the environment
const EMBED_MODEL = "text-embedding-3-small";
const CHAT_MODEL = process.env.OPENAI_MODEL; // set to a current model name from the OpenAI models page
const docs = [
{ id: "refunds", text: "Refunds are available within 14 days of purchase. Annual plans are refunded pro rata after 14 days." },
{ id: "export", text: "You can export all project data as CSV or JSON from Settings, then Data export. Exports are emailed within 10 minutes." },
{ id: "sso", text: "Single sign-on with SAML is available on the Business plan and above." },
];
async function embed(texts) {
const res = await openai.embeddings.create({ model: EMBED_MODEL, input: texts });
return res.data.map((d) => d.embedding);
}
function cosine(a, b) {
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }
return dot / (Math.sqrt(na) * Math.sqrt(nb));
}
// Ingestion: embed once, keep vectors next to the text
const vectors = await embed(docs.map((d) => d.text));
const store = docs.map((d, i) => ({ ...d, vector: vectors[i] }));
export async function ask(question, k = 2) {
const [qv] = await embed([question]);
const top = store
.map((c) => ({ ...c, score: cosine(qv, c.vector) }))
.sort((a, b) => b.score - a.score)
.slice(0, k);
const context = top.map((c) => `[${c.id}] ${c.text}`).join("\n");
const response = await openai.responses.create({
model: CHAT_MODEL,
instructions:
"Answer using only the context. If the context does not contain the answer, say you do not know. Cite source ids in square brackets.",
input: `Context:\n${context}\n\nQuestion: ${question}`,
});
return { answer: response.output_text, sources: top.map((c) => c.id) };
}
console.log(await ask("Can I get my money back after three weeks?"));
Expected output (wording varies by model):
{
answer: 'Refunds are available within 14 days. For annual plans, a pro rata refund applies after that [refunds].',
sources: [ 'refunds', 'export' ]
}
A few details worth noticing. The question never mentions the word "refund", yet the right chunk is retrieved, which is the point of semantic search. The second source (export) is irrelevant: with k = 2 and only three documents, the retriever returns whatever is next best. A relevance threshold would filter it out. And the instruction to say "I do not know" is what prevents the model from improvising.
The OPENAI_MODEL variable is deliberate. Model names change often; take a current one from the OpenAI models page rather than hard-coding one from a tutorial.
Beyond naive RAG: what improves retrieval
The version above is often called naive RAG. These techniques address its usual failures:
- Hybrid search. Combine vector search with keyword search (BM25 or Postgres full-text) so exact terms like error codes and product names still match.
- Metadata filtering. Filter by tenant, language, product version or permission before similarity ranking.
- Reranking. Retrieve 30 candidates cheaply, then rescore them with a cross-encoder or reranker model and keep the best 5.
- Query rewriting. Rewrite a vague follow-up ("what about annual?") into a standalone query using the chat history.
- Parent-child chunks. Search small chunks for precision but pass the larger surrounding section to the model.
- Context ordering. Research on long contexts, such as Lost in the Middle, found that models can use information in the middle of a long prompt less reliably. Keep the context short and put the best chunks first.
RAG in real products: an engineering view
The following is a hypothetical example, not a description of a specific shipped system. Imagine a SaaS support assistant that answers from help-centre articles and past tickets.
Architecture decisions. Store chunks in Postgres with pgvector if you already run Postgres and have under a few million vectors, so permissions, joins and backups stay in one system. Move to a dedicated vector database when scale, filtering or latency needs justify another service.
Trade-offs. Larger k improves recall but increases cost, latency and the chance of distracting context. Re-embedding the whole corpus when you change the embedding model is expensive, so store the model name and version with every vector.
Production challenges. Index freshness (deleting or updating a source must remove its old chunks), per-tenant isolation (filter on tenant id in the query, not afterwards), and prompt injection through retrieved text. Treat retrieved content as untrusted input: a document that says "ignore previous instructions" is still just data, and your prompt should say so. For a security checklist see web API security.
Debugging. Log the question, the retrieved chunk ids with scores, the final prompt and the answer. When an answer is wrong, the first question is always "was the right chunk retrieved?" If not, fix retrieval. If yes, fix the prompt or the model choice.
Evaluation. Build a small set of real questions with the expected source document. Measure whether the right chunk appears in the top results (retrieval) separately from whether the answer is faithful to the context (generation). Without this you are tuning blind.
Common RAG mistakes
- Blaming the model for a retrieval problem. If the right chunk is not in the prompt, no model can answer correctly. Inspect retrieval first.
- Fixed-size chunking that cuts mid-sentence. Split on headings and paragraphs and keep titles with their content.
- Mixing embedding models. Embedding documents with one model and queries with another produces meaningless similarity scores.
- No relevance threshold. Always returning top-k feeds the model irrelevant text. Return nothing, and say "I do not know", when scores are low.
- Skipping metadata. Without tenant, version and permission fields you cannot filter, which becomes a security problem, not just a quality problem.
- Never re-indexing. Stale chunks answer with outdated policy. Tie indexing to content changes.
- No evaluation set. "It seems better" is not a measurement. Keep a test set and rerun it after every change.
- Trusting retrieved text. Untrusted documents can carry instructions. Separate context from instructions in the prompt and limit what the model can do with tools.
Best practices
- Start with the simplest pipeline, measure, then add hybrid search or reranking where the data shows a gap.
- Store source, section, updated date and access level as metadata on every chunk.
- Instruct the model to answer only from context, to admit uncertainty and to cite sources.
- Keep ingestion idempotent so a re-run replaces chunks rather than duplicating them.
- Log retrieval results so every answer can be traced and debugged.
- Compare RAG with fine-tuning before committing to either; the two solve different problems, as covered in RAG vs Fine-Tuning.
Conclusion
RAG architecture is a retrieval system with an LLM on the end. Ingestion turns your documents into searchable vectors; the query flow finds the best chunks and asks the model to answer from them. The model is the easy part. The quality of your chunking, metadata, retrieval and evaluation decides whether users trust the result.
A practical next step: take twenty real questions from your users, run the minimal pipeline above against your own documents, and check whether the right chunk is retrieved for each one. If you want to go further, read Vector Databases Explained and How to Build an AI-Powered Search System, or see how I approach AI integration work.
References
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (Lewis et al., 2020)
- Lost in the Middle: How Language Models Use Long Contexts (Liu et al., 2023)
- OpenAI: Embeddings guide
- OpenAI: Models
- OpenAI: Responses API text guide
- pgvector on GitHub
Written by Shivam Thakur, a Software Engineer focused on web applications, SaaS platforms and modern software products. More at shivamthakur.me.

