AWS Builder Center
RAG from Basics to Advanced (Part 2): Architecture and the Query-to-Response Flow

RAG from Basics to Advanced (Part 2): Architecture and the Query-to-Response Flow

Breaking down the retriever-generator split, the core RAG pipeline, and tracing a real query end-to-end from user input to final answer.

Series: RAG from Basics to Advanced (8 articles)

  1. 2
    RAG from Basics to Advanced (Part 2): Architecture and the Query-to-Response Flow This article
AWS DevOps Engineer | 7+ Yrs Cloud Automation | EKS, ECS, IaC | GenAI & AIOps Expert
This is Part 2 of a series that builds up Retrieval Augmented Generation (RAG) from the ground up.

Two Components, Not One

RAG is built around two distinct components:
  • Retriever:- finds relevant information
  • Generator:- an LLM that uses that information to produce a final answer
The obvious follow-up question: why two separate components? Why can't one model do both?

Why Separation of Concerns

  • The retriever's job is search and matching it understands semantic similarity, but it doesn't reason or generate language.
  • The generator's (LLM's) job is synthesis reading retrieved chunks and turning them into a coherent, contextual answer.
If a single model tried to do both:
  • It would need to internally encode the entire knowledge base which is just fine-tuning again, the very approach we ruled out in Part 1.
  • Specialized, lightweight embedding models are dramatically faster and cheaper at the search task than asking an LLM to "search" through generation.
In simple term
Retrieval is a search problem. Generation is a language problem. Merging them into a single model makes both worse and more expensive.

The High-Level Pipeline


Let's go through each step — why it exists, and what the alternatives were.

Step 1: Query Embedding

The user's query is converted into a vector representation using an embedding model (e.g., OpenAI's text-embedding-3, or open-source options like sentence-transformers).

Keyword Search
Semantic (Vector) Search
Matches on
Exact/fuzzy word overlap
Meaning/intent
"car" vs. "automobile"
Misses (no exact word match)
Matches (semantically similar)
Speed at scale
Fast, mature technology
Fast, with the right indexing (ANN)
Weakness
Struggles with synonyms, paraphrasing
Can miss exact numbers, codes, IDs
Why embeddings, and not keyword search like traditional search engines?
production systems often use hybrid search combining keyword (BM25) and semantic search because each covers the other's weaknesses. Pure semantic search can miss precise identifiers like product codes or exact names.

Steps 2 & 3: Retrieval + Vector Database

The query embedding is searched against a vector database (Pinecone, Weaviate, FAISS, AWS OpenSearch, etc.), using a similarity metric cosine similarity, dot product, or Euclidean distance to find nearest neighbors.
Why a vector database, and not just a SQL database with a similarity function bolted on?
  • A traditional database would need to linearly scan every row and compare it against the query vector O(n) over millions of documents, which is far too slow.
  • Vector databases use Approximate Nearest Neighbor (ANN) algorithms (HNSW, IVF, and others) that find approximate matches in sub-linear time, trading a small amount of accuracy for a massive speed gain.
Now question comes "Why approximate, not exact?" Exact nearest-neighbor search in high-dimensional space is computationally expensive the classic curse of dimensionality. Approximate methods deliver 95–99% accuracy at a fraction of the cost, and that trade-off is almost always worth it in production.

Step 4: Prompt Construction (Augmentation)

The retrieved top-K chunks are combined with the original query into an augmented prompt, roughly like this:
Context: [retrieved chunk 1] [retrieved chunk 2] ...
Question: [user query]
Answer based only on the above context.
Why does the "answer only from context" instruction matter? It gives the LLM grounding instead of relying on its own parametric memory (which may be outdated or simply wrong), it's directed to use only the provided context. This is one of the key techniques for reducing hallucination.
How do you decide top-K?
  • Too small (K=1) real context can get missed, leading to incomplete answers.
  • Too large (K=20) irrelevant, noisy chunks confuse the LLM, token costs rise, and the "lost in the middle" problem (covered in Part 1) resurfaces.
  • In practice, teams typically experiment in the K=3 to K=10 range, tuned to the specific use case.

Step 5: Generation

The LLM processes the augmented prompt and generates the final answer and can include source citations if the prompt instructs it to.

The Complete Journey: Query to Response

The five-step pipeline above is the concept. Here's what actually happens, step by step, when a real query moves through a real system.
Say a user asks: "What is our company's refund policy for damaged products?"

Pre-Step: Indexing (Happens Before Any Query Arrives)

This is offline preparation, not part of the runtime flow but the runtime flow depends entirely on it having already happened:
  1. Document ingestion all source documents (PDFs, policies, wikis) are collected.
  1. Chunking each document is split into smaller pieces (commonly 300–500 tokens, sometimes with overlap this deserves its own deep dive later in the series).
  1. Embedding generation each chunk is passed through the embedding model to produce a vector, stored alongside metadata (source document, page number).
  1. Indexing all vectors are indexed into the vector database's ANN structure.



Step 1: The Query Arrives

User types: "What is our company's refund policy for damaged products?"
At this point it's just raw text — the system has no notion of "meaning" yet.

Step 2: Query Preprocessing

  • Cleaning handling extra whitespace, special characters.
  • Expansion (optional) sometimes the query is enriched before embedding, for example by expanding abbreviations, or having an LLM reformulate it into a hypothetical answer first (a technique called HyDE(Hypothetical Document Embeddings). The reasoning: a short query and a long document don't naturally look alike in embedding space, but a hypothetical answer generated by an LLM tends to structurally resemble the real documents being searched improving match quality.

Step 3: Query Embedding

The query (or the HyDE-generated hypothetical answer) is passed through the same embedding model used during indexing.
Query → Embedding Model → [0.023, -0.451, 0.812, ..., 0.109] (e.g., 1024-dim vector)
A non-negotiable rule: the query and the documents must be encoded with the same embedding model otherwise the vector spaces won't align, and similarity scores become meaningless.

Step 4: Retrieval — ANN Search in the Vector Database

The query vector is searched against the index to find the closest matches.
Retrieved candidates:
Retrieved candidates:
1. "Damaged item refund process..." (score: 0.89)
2. "Return policy for electronics..." (score: 0.85)
3. "Shipping damage claims..." (score: 0.83)
... and more
At this stage, retrieval typically pulls a broader set of candidates rather than jumping straight to the final 3–5 chunks because a fast, approximate search casts a wide net first. What happens after that reranking this candidate set for precision, fusing it with keyword search results, and reordering chunks to avoid positional bias is where retrieval gets genuinely interesting technically. That's the focus of Part 3.

Step 5: Prompt Construction

The (now-refined) top chunks are combined with the query and system instructions into a final prompt:
System: You are a customer support assistant. Answer only using the provided context.
If the answer isn't in the context, say you don't know.

Context:
[Chunk 1]: "Damaged item refund process: Customers can request a full refund within
30 days of delivery if the product arrives damaged..."

[Chunk 2]: "Refunds for products damaged in transit are processed within 5-7
business days after..."

Question: What is our company's refund policy for damaged products?

Answer:
Chunks are typically included alongside metadata (source, page, document title) so the LLM can cite where its answer came from.

Step 6: Generation

The augmented prompt is sent to the LLM, which tokenizes it and generates a response token-by-token (autoregressive decoding). Through self-attention, the model attends to both the retrieved context and the query simultaneously — this is where grounding actually happens.
Generated Answer:
"According to our policy, customers can request a full refund within 30 days
of delivery if a product arrives damaged. Refunds are processed within 5-7
business days after the claim is verified. [Source: Refund Policy Doc, Section 3]"

Step 7: Post-Processing & Delivery

  • Citation formatting presenting sources in a clean, readable way.
  • Guardrails (optional) checking the response against toxicity/PII filters, or a confidence threshold.
  • The final answer is delivered to the user.


Summary

RAG is a pipeline, not a single model. Each component does one specific, optimized job:
  • Embedding model encodes meaning into a vector
  • Vector database fast approximate search
  • LLM synthesis and natural language generation
The closing line worth remembering:
RAG's real strength isn't any single component — it's that retrieval and generation are decoupled, so each part can be independently optimized, scaled, and swapped out.


Next in this series (Part 3): The practical layer of retrieval why production systems rerank with cross-encoders, how hybrid search combines keyword and semantic results, why chunk order matters before a prompt reaches the LLM, and how these pieces fit into the flow above.

Series: RAG from Basics to Advanced (8 articles)

  1. 2
    RAG from Basics to Advanced (Part 2): Architecture and the Query-to-Response Flow This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article