Spring AI – Prompt Stuffing vs RAG: When Context in the Prompt Isn’t Enough
-
Last Updated:
-
By: javahandson
-
Series

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.
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:
Let us start from the simplest setup of all.
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.
A plain model has three clear gaps. Knowing them helps you see why stuffing and RAG exist at all.
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.
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.
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:
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.
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.
Prompt stuffing scales badly. It is great for a page or two. But feed it a whole handbook, and four problems show up together.
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.
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.
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.
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. |
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.
The name itself is the recipe. RAG has three simple steps, and each one maps to a word:
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.

RAG was built to solve the exact pains we just listed. Because it sends only the relevant chunks, each problem gets smaller:
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.
Now we can answer the main question directly. Neither approach is “better” in every case. Instead, each one fits a different size of problem.
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.
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:
RAG earns its keep once the data grows. The extra setup pays off through lower cost and steadier accuracy.
Choose RAG when:
| 💡 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. |
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.
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.
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.
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.
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.
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.
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=trueA few quick notes on this setup:
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.
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. |
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.
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.
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.
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.
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.
Let me share a few lessons from building these pipelines. They will save you some painful debugging later.
| 💡 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. |
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.
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.
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.
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.
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.
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.
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:
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.