Spring AI – Prompt Stuffing vs RAG: When Context in the Prompt Isn’t Enough

  • Last Updated:
  • By: javahandson
  • Series
img

Spring AI – Prompt Stuffing vs RAG: When Context in the Prompt Isn’t Enough

Prompt stuffing vs RAG in Spring AI, explained simply. See when to stuff context in the prompt, when to use RAG, and how to build it with Spring AI 2.0.1.

1. Introduction

If you have built one chat app with Spring AI, you already know the trick. You paste some extra text into the prompt, and suddenly the model answers from your data. That trick has a name. It is called prompt stuffing. It works, and it is easy. But it breaks in quiet ways as your data grows. This is where the whole prompt stuffing vs RAG question comes up, and it is the exact thing we will sort out in this guide.

In the earlier articles, we covered tokens, embeddings and chat memory. Now we join those ideas together. First, we will see what prompt stuffing really is. Then we will see where it hurts. After that, we will build RAG in Spring AI, step by step, using a real vector store.

By the end of this guide, you will know:

  • what prompt stuffing is, and why it feels so natural at first
  • the exact point where stuffing a prompt starts to cost you money and accuracy
  • what RAG is, in plain words, without the heavy jargon
  • when to pick prompt stuffing, and when to move to RAG
  • how to build RAG in Spring AI 2.0.1 with QuestionAnswerAdvisor and RetrievalAugmentationAdvisor

Let us start from the simplest setup of all.

2. Start Simple: Just the LLM and Its Prompt

A plain LLM is like a very well-read person with no internet. You ask a question. It answers from whatever it learned during training. For general questions, this is fine. Ask it about Java basics, and the answer is solid.

However, this person cannot look anything up. They cannot open your company wiki. They cannot read today’s news either. So the model is stuck with old, general knowledge only.

2.1 Where a Plain LLM Falls Short

A plain model has three clear gaps. Knowing them helps you see why stuffing and RAG exist at all.

  • It does not know your private data, like your HR policy or your product catalogue.
  • It cannot fetch real-time data, such as today’s order status or stock price.
  • It offers little personalization, because it knows nothing about your user.

As one common saying goes, it is like asking someone to answer without letting them Google or check their notes. To close these gaps, you must hand the model the right notes yourself. That brings us straight to prompt stuffing.

3. What Is Prompt Stuffing?

Prompt stuffing means giving the LLM an open book before it answers. You add the reference text right next to the user’s question. Then the model reads that text and replies using it.

You may also hear two other names for this idea. Some people call it in-context learning. Others call it retrieval-augmented prompting when it is done in code. The core move stays the same. You put the facts in the prompt, and the model uses them.

3.1 A Small Example You Can Picture

Imagine a simple HR question inside your company app. A user asks how many paid leaves they get each year. The model was never trained on your policy, so on its own it would guess.

With prompt stuffing, you add the policy text to the prompt first. For example:

  • Stuffed context: “Employees are eligible for 18 days of paid leave annually. Unused leave can be carried over to the next year.”
  • User question: “How many paid leaves do employees get each year?”
  • Model answer: “Employees are eligible for 18 days of paid leave annually.”

Notice how clean this is. The model did not know your policy. Yet it answered correctly, because you gave it the right note at the right moment.

3.2 Prompt Stuffing in Spring AI

In Spring AI, stuffing is just a matter of filling a system message. You keep a small template with a placeholder. Then you pass your reference text into that placeholder. Here is a tiny version of the HR example:

@GetMapping("/stuffed/chat")
public String stuffedChat(@RequestParam String message) {
 
    // In a real app this text would come from a file or a database.
    String policy = """
        Employees are eligible for 18 days of paid leave annually.
        Unused leave can be carried over to the next year.
        """;
 
    return chatClient.prompt()
            .system(s -> s.text(hrSystemTemplate)   // template has a {documents} placeholder
                          .param("documents", policy))
            .user(message)
            .call()
            .content();
}

The template itself is plain text with one slot. It usually says something like “Answer only from the documents below”, followed by the {documents} placeholder. So the model stays grounded on your text and does not wander off.

For a single small policy, this code is perfect. Honestly, you do not need anything fancier. The trouble starts only when the amount of text grows.

3.3 Where Prompt Stuffing Starts to Hurt

Prompt stuffing scales badly. It is great for a page or two. But feed it a whole handbook, and four problems show up together.

3.3.1 Token Limits

Every model has a context window, measured in tokens. Stuff too much text, and you simply run out of room. The request then fails, or you must cut your own documents short.

3.3.2 Rising Cost

You pay per token on most cloud models. When you stuff the full handbook into every single call, you pay for all of it every time. Even worse, you pay again for the next question, even if it needs none of that text.

3.3.3 Lost in the Middle

Long prompts also confuse the model. Research shows accuracy often drops when the key fact sits in the middle of a huge context. This is widely called the “lost in the middle” problem. More text can mean worse answers, not better.

3.3.4 Mostly Irrelevant Context

Here is the quiet waste. For any one question, only a tiny slice of your documents matters. The rest is noise. Yet with stuffing, you ship the whole book anyway, question after question.

💡 Interview Insight
Interviewers love to ask why prompt stuffing does not scale. Keep the answer tight. You pay for every token on every call, you can blow past the context window, and long prompts trigger the lost-in-the-middle problem. In short, you send a lot of text, but only a little of it is ever relevant to the question.

4. What Is RAG?

RAG stands for Retrieval-Augmented Generation. It is simply a smarter way to put context into the prompt. Instead of sending the whole book, you send only the few lines that actually answer the question.

Think of the earlier open-book example again. Prompt stuffing hands over the full book every time. RAG, on the other hand, flips to the right page first, then hands over only that page.

4.1 Retrieval, Augmentation, Generation

The name itself is the recipe. RAG has three simple steps, and each one maps to a word:

  • Retrieval: the system searches a knowledge base and finds the most relevant chunks of text.
  • Augmentation: it adds only those chunks to the prompt, right beside the user’s question.
  • Generation: the LLM writes the final answer using that focused context.

So a user asks about a product. The retriever searches your docs, PDFs or a vector database. Then the best chunks go into the prompt, and the model replies from them. The result is accurate, grounded and up to date.

Side-by-side diagram comparing prompt stuffing vs RAG in Spring AI: prompt stuffing sends the user question with all documents in one big prompt, while RAG retrieves only the top relevant chunks from a vector store and sends a small prompt to the LLM

4.2 How RAG Fixes the Prompt Stuffing Problems

RAG was built to solve the exact pains we just listed. Because it sends only the relevant chunks, each problem gets smaller:

  • Fewer tokens: the prompt stays small, so you rarely hit the context window.
  • Lower cost: you pay for a few chunks, not the whole handbook, on every call.
  • Better focus: the model sees relevant text only, so lost-in-the-middle fades away.
  • Fresh data: update the knowledge base, and new answers follow, with no retraining.

In other words, RAG keeps the good part of stuffing. You still ground the model on your own data. Yet you drop the heavy cost of sending everything each time.

5. Prompt Stuffing vs RAG: A Clear Comparison

Now we can answer the main question directly. Neither approach is “better” in every case. Instead, each one fits a different size of problem.

5.1 The Comparison Table

The table below sums up the trade-offs at a glance:

Feature            | Prompt Stuffing              | RAG
-------------------|------------------------------|------------------------------
Context sent       | The whole document set       | Only top relevant chunks
Token usage        | High, grows with data        | Low and fairly steady
Cost per call      | High for large data          | Low, you pay for a few chunks
Setup effort       | Very low                     | More parts (vector store etc.)
Best data size     | Small and stable             | Large or fast changing
Accuracy at scale  | Drops (lost in the middle)   | Stays high with good retrieval
Fresh updates      | Edit the text in code        | Add docs to the vector store

Let me add a quick note from my own work. For years I built banking integrations, where every extra call has a cost and a risk. The same mindset helps here. You do not add a vector store just because it sounds modern. You add it only when the data truly needs it.

5.2 When Prompt Stuffing Is Still the Right Choice

Do not write off prompt stuffing. For small, stable data, it is the simpler and cheaper option. There is no vector store to run, and no indexing to maintain.

Reach for prompt stuffing when:

  • your reference text is small, say a short FAQ or one policy page
  • the content rarely changes, so you can keep it right in the code or a file
  • you want the simplest possible setup, with no extra infrastructure
  • latency matters a lot, since there is no retrieval step to slow you down

5.3 When You Should Reach for RAG

RAG earns its keep once the data grows. The extra setup pays off through lower cost and steadier accuracy.

Choose RAG when:

  • your knowledge base is large, like hundreds of pages or many PDFs
  • the data changes often, so you need easy updates without redeploying
  • you ask many questions per day, where token savings add up fast
  • each question needs only a small, specific slice of the whole data
💡 Interview Insight
A favourite interview question is simply “prompt stuffing vs RAG, when do you use each?”. Give a crisp rule. Use prompt stuffing for small, static data where setup should stay minimal. Move to RAG when the data is large or changes often, because you send only the relevant chunks and keep both cost and accuracy under control.

6. How RAG Works Under the Hood

RAG sounds clever, yet the machinery is simple. It stands on two ideas we covered before, embeddings and a vector store. Let us walk through the three stages once more, this time with the moving parts.

6.1 Step 1: Index Your Knowledge

First, you prepare your data once, up front. You split each document into small chunks. Then you turn every chunk into an embedding, which is a vector of numbers. Finally, you store those vectors in a vector store.

A vector store is a database built for meaning, not keywords. It keeps the vectors and can search them fast. Popular options include Qdrant, PostgreSQL with pgvector, Redis, Elasticsearch and Pinecone.

6.2 Step 2: Retrieve the Right Chunks

Next comes query time, when a user asks something. You turn the question into a vector too, using the same embedding model. Then the vector store compares that query vector with the stored ones.

This comparison is semantic search. It finds text with a similar meaning, even when the words differ. For example, “fix a laptop screen” can match “repair a broken display”. The store returns the top matches, often the top three or five.

6.3 Step 3: Augment the Prompt and Generate

Finally, you glue it together. You take those few retrieved chunks and add them to the prompt. Then the LLM answers using this small, focused context. So the prompt stays short, and the answer stays grounded.

That is the whole loop. Index once, then retrieve and augment on every question. Now let us build this in Spring AI.

7. Building RAG in Spring AI

Spring AI gives you clean, Spring-style tools for RAG. You get a VectorStore abstraction, plus two ready-made advisors. We will use Qdrant as the vector store and OpenAI for embeddings and chat.

This guide uses Spring AI 2.0.1, the current stable release. It runs on Spring Boot 4 and Java 21. A small note for later: some artifact names changed between 1.x and 2.0, and we will flag those as we go.

7.1 Add the Dependencies

First, add the parts you need in pom.xml. You need the Qdrant starter, the RAG module and the vector-store advisor. The Tika reader helps you load PDFs and Word files.

<!-- Vector store: Qdrant -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-qdrant</artifactId>
</dependency>
 
<!-- Modular RAG support (RetrievalAugmentationAdvisor) -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-rag</artifactId>
</dependency>
 
<!-- QuestionAnswerAdvisor + VectorStoreChatMemoryAdvisor -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-vector-store-advisor</artifactId>
</dependency>
 
<!-- Read text from PDFs, DOCs and more -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-tika-document-reader</artifactId>
</dependency>

One version note here, so you do not get stuck. In Spring AI 1.x the advisor artifact was spring-ai-advisors-vector-store. From 2.0 onward it is spring-ai-vector-store-advisor. So if you copy old tutorials, fix this name first.

7.2 Start a Vector Store (Qdrant)

You can run Qdrant locally with Docker Compose. Spring Boot can even start it for you on app startup. Add a small compose file and point Spring AI at it.

# compose.yaml
services:
  qdrant:
    image: 'qdrant/qdrant:latest'
    ports:
      - '6333:6333'   # REST API
      - '6334:6334'   # gRPC API, used by Spring AI
# application.properties
spring.ai.openai.api-key=${OPENAI_API_KEY}
 
spring.ai.vectorstore.qdrant.host=localhost
spring.ai.vectorstore.qdrant.port=6334
spring.ai.vectorstore.qdrant.collection-name=eazybytes
spring.ai.vectorstore.qdrant.initialize-schema=true

A few quick notes on this setup:

  • Port 6334 is the gRPC port, which Spring AI uses to talk to Qdrant.
  • The initialize-schema flag lets Spring AI create the collection on startup.
  • Keep your API key in an environment variable, never in Git.

7.3 Load and Chunk Your Documents

Before you can retrieve anything, you must fill the store. You read a document, split it into chunks, and add those chunks. Spring AI does the embedding for you behind the scenes.

@Component
public class HrPolicyLoader {
 
    @Value("classpath:Eazybytes_HR_Policies.pdf")
    private Resource policyFile;
 
    private final VectorStore vectorStore;
 
    public HrPolicyLoader(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }
 
    @PostConstruct
    public void load() {
        // 1. Read raw text from the PDF
        var reader = new TikaDocumentReader(policyFile);
        List<Document> docs = reader.get();
 
        // 2. Split into small, searchable chunks
        var splitter = TokenTextSplitter.builder()
                .withChunkSize(100)
                .withMaxNumChunks(400)
                .build();
 
        // 3. Store the chunks (Spring AI embeds them for you)
        vectorStore.add(splitter.split(docs));
    }
}

Chunk size matters more than beginners expect. Tiny chunks lose context, while huge chunks bring back noise. So start around 100 tokens, then tune it for your own content.

One more tip from experience. Load your documents only once, not on every request. A @PostConstruct loader like this runs at startup, which is exactly what you want. If you re-embed the same PDF on each call, you pay the embedding cost again and again.

7.4 The Manual Way: Search, Then Stuff the Chunks

Here is the nice part. RAG is really prompt stuffing with a search step in front. To prove it, let us do the search by hand first. You query the store, join the top chunks, and stuff only those into the prompt.

@GetMapping("/document/chat")
public String documentChat(@RequestParam String message) {
 
    // 1. Retrieve the most relevant chunks
    SearchRequest request = SearchRequest.builder()
            .query(message)
            .topK(3)
            .similarityThreshold(0.5)
            .build();
    List<Document> similar = vectorStore.similaritySearch(request);
 
    // 2. Join them into a small context block
    String context = similar.stream()
            .map(Document::getText)
            .collect(Collectors.joining(System.lineSeparator()));
 
    // 3. Stuff only that context (not the whole PDF) into the prompt
    return chatClient.prompt()
            .system(s -> s.text(hrSystemTemplate).param("documents", context))
            .user(message)
            .call()
            .content();
}

Look closely, and you will see the link. This is the same .param(“documents”, …) call from section 3.2. Only the source of that text changed. Earlier it was the whole policy. Now it is just the top three chunks.

💡 Interview Insight
A sharp interviewer may ask how RAG relates to prompt stuffing. Do not treat them as rivals. Say that RAG is prompt stuffing plus a retrieval step. You still inject context into the prompt. The difference is that a similarity search picks the small, relevant slice instead of sending everything.

7.5 The Easy Way: QuestionAnswerAdvisor

Writing the search by hand works, but it is repetitive. Spring AI can do all of it for you with an advisor. The QuestionAnswerAdvisor runs the similarity search and injects the context automatically.

@Bean
public ChatClient ragChatClient(ChatClient.Builder builder, VectorStore vectorStore) {
 
    var qaAdvisor = QuestionAnswerAdvisor.builder(vectorStore)
            .searchRequest(SearchRequest.builder()
                    .topK(3)
                    .similarityThreshold(0.5)
                    .build())
            .build();
 
    return builder.defaultAdvisors(qaAdvisor).build();
}

After this, your controller gets very thin. You just send the user message as usual. The advisor quietly searches the store and grounds the answer for you.

@GetMapping("/qa/chat")
public String qaChat(@RequestParam String message) {
    return ragChatClient.prompt()
            .user(message)
            .call()
            .content();
}

No manual search, no joining strings, no template juggling. The advisor handles the retrieval and the augmentation. For most basic RAG needs, this is all you need.

7.6 The Flexible Way: RetrievalAugmentationAdvisor

Sometimes you want more control over the retrieval. For that, Spring AI offers the RetrievalAugmentationAdvisor from the spring-ai-rag module. It follows a modular design, so you can plug in extra steps later.

@Bean
public RetrievalAugmentationAdvisor ragAdvisor(VectorStore vectorStore) {
    return RetrievalAugmentationAdvisor.builder()
            .documentRetriever(VectorStoreDocumentRetriever.builder()
                    .vectorStore(vectorStore)
                    .topK(3)
                    .similarityThreshold(0.5)
                    .build())
            .build();
}

You then register this advisor on your ChatClient, just like before. The basic result looks the same as QuestionAnswerAdvisor. The real gain is room to grow, which we cover next.

8. Naive RAG vs Advanced RAG

What we built so far is called Naive RAG. You retrieve chunks and pass them straight to the model. It works well for clean data and clear questions.

Advanced RAG adds extra steps around the retrieval. These steps clean up the query before the search and the chunks after it. The RetrievalAugmentationAdvisor is built exactly for this.

8.1 Pre-Retrieval: Fix the Query First

Users rarely ask tidy questions. Pre-retrieval steps rewrite a messy query into a cleaner one. They can also expand a single question into a few variants, so the search covers more ground.

8.2 Post-Retrieval: Clean the Chunks After

Raw search results are not always perfect. Post-retrieval steps rerank, filter or compress the chunks before they reach the model. This helps with long context and the lost-in-the-middle issue we met earlier.

You do not need all this on day one. Start with Naive RAG and ship it. Then add pre and post steps only when your answers need the extra polish.

9. Best Practices and Common Mistakes

Let me share a few lessons from building these pipelines. They will save you some painful debugging later.

9.1 Best Practices

  • Tune chunk size and topK together, since both shape answer quality.
  • Set a sensible similarity threshold, so weak matches get dropped early.
  • Log the retrieved chunks during testing, which makes bad answers easy to trace.
  • Keep the same embedding model for indexing and querying, or search will misfire.
  • Measure token usage per call, so you can prove the savings over plain stuffing.

9.2 Common Mistakes

  • Using RAG for a tiny FAQ, where simple prompt stuffing would be easier and cheaper.
  • Copying the old spring-ai-advisors-vector-store name instead of the new 2.0 artifact.
  • Setting chunks too large, which brings back noise and wastes tokens.
  • Forgetting to load the vector store, so every search returns nothing.
  • Ignoring retrieval quality, then blaming the model for a weak answer.
💡 Interview Insight
A common follow-up is “how do you know your RAG is actually good?”. Point at retrieval, not just the model. Track whether the correct chunk appears in the top results. Also watch token usage and latency per call. If the right chunk never gets retrieved, no model can save the answer.

10. FAQ’s on prompt stuffing vs rag

Q: What is prompt stuffing in Spring AI?

A: Prompt stuffing means adding your reference text straight into the prompt, next to the user’s question. In Spring AI you do this by filling a system message with a placeholder, such as a {documents} slot. The model then answers using that extra text. It is also called in-context learning, and it works best for small, stable data.

Q: What is the difference between prompt stuffing and RAG?

A: Prompt stuffing sends all of your documents on every call. RAG sends only the few chunks that actually match the question. So the core question of prompt stuffing vs RAG is really about scale: stuffing is simpler but costs more tokens, while RAG stays small, cheap and accurate as the data grows.

Q: When should I use prompt stuffing instead of RAG?

A: Use prompt stuffing when your text is small and rarely changes, like a short FAQ or one policy page. It needs no vector store and no indexing, so the setup stays minimal and latency stays low. Move to RAG once the knowledge base is large, changes often, or you handle many questions per day.

Q: Is RAG just prompt stuffing with extra steps?

A: In a way, yes. RAG still injects context into the prompt, exactly like stuffing. The difference is a retrieval step in front. A similarity search picks the small, relevant slice of text first, instead of sending the whole document set every time.

Q: Which Spring AI advisor should I use for RAG?

A: Start with QuestionAnswerAdvisor from the spring-ai-vector-store-advisor module. It runs the similarity search and injects the context for you. Move to RetrievalAugmentationAdvisor from the spring-ai-rag module when you need modular control, such as query rewriting or reranking.

Q: What is the “lost in the middle” problem in prompt stuffing?

A: When you stuff a very long context, the model often misses facts placed in the middle of it. Accuracy drops even though the answer is right there. This is the lost-in-the-middle problem, and it is one big reason RAG beats prompt stuffing on large data.

11. Conclusion

So, where does the prompt stuffing vs RAG debate land? The honest answer is that both have a place. They are two points on the same line, not enemies.

Prompt stuffing is the quick, simple choice for small and stable data. RAG is the scalable choice once your data grows or changes often. Under the hood, RAG is still stuffing, just with a smart search in front.

Here is a simple path to follow:

  • Start with prompt stuffing for a small, fixed set of text.
  • Watch your token cost and your context window as data grows.
  • Move to RAG with a vector store once stuffing starts to strain.
  • Begin with QuestionAnswerAdvisor, then grow into modular RAG when needed.

Build it in that order, and you keep things simple at every stage. You add power only when the problem truly asks for it.

My last bit of advice is to stay practical. Many real apps even mix both ideas in one codebase. A small, fixed prompt handles simple cases, while RAG handles the big knowledge base. So treat these as tools in the same box, and pick the one each job needs.

12. Further Reading

Leave a Comment