Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Explain the steps of retrieval-augmented generation for a Java service that answers questions from internal policy documents.

Retrieval-augmented generation has two phases. Ingestion reads the policy documents, splits them into chunks, computes an embedding for each chunk and stores the chunks with metadata in a vector store; in Spring AI, a DocumentReader, a TextSplitter such as TokenTextSplitter, an EmbeddingModel and a VectorStore cover this. At question time we embed the question, search for the most similar chunks, add the top results to the prompt as context, and ask the model to answer only from that context and cite its sources. Quality depends on chunking, metadata filters and retrieval at least as much as on the model.

Why this question is asked

A model trained on the public internet has never read our travel policy, and if we ask it how much we may spend on a hotel in Berlin, it will produce a confident, plausible and wrong number. Retrieval-augmented generation, or RAG, fixes that by finding the relevant passages in our own documents and giving them to the model with the question. It is the most common pattern for internal assistants, which is why interviewers ask us to walk through it. In this answer, we will build the ingestion phase step by step, then the question phase, write the prompt that keeps the model honest, and finish with the factors that decide quality.

1A Quick Recap: Why Retrieval Helps

A language model can only use what is in its training data or in the prompt. We cannot retrain it every time a policy changes, and we cannot paste 3,000 pages of policy into every prompt, because prompts have a size limit and every token costs money and time. RAG takes the middle path: for each question, find the five or so passages most likely to contain the answer, and put only those in the prompt.

Finding passages by meaning rather than exact words uses embeddings, lists of numbers that represent the meaning of a text, computed by an embedding model. A question about accommodation costs and a passage about hotel expense limits have similar embeddings even though they share few words. A vector store is a database that stores these embeddings and quickly finds the nearest ones to a given vector.

2Ingestion: Read, Split, Embed, Store

Ingestion runs ahead of time, and again whenever documents change. First we read each document into text with a DocumentReader, for example the Tika reader for Word and PDF files. Then we split it into chunks of a few hundred tokens, because a whole document would be too large for the prompt and its embedding would blur many topics together. Then we store the chunks; the vector store calls the EmbeddingModel to compute each chunk's embedding as it adds them.

Java
@Service
class PolicyIngestion {
private final VectorStore vectorStore;
PolicyIngestion(VectorStore vectorStore) { this.vectorStore = vectorStore; }
void ingest(Resource file, String policyId, String title) {
List<Document> docs = new TikaDocumentReader(file).get(); // 1 document, 14 pages of text
docs.forEach(d -> d.getMetadata().putAll(Map.of(
"policyId", policyId, "title", title, "country", "DE"))); // metadata for filters and citations
List<Document> chunks = new TokenTextSplitter().apply(docs); // 38 chunks of about 800 tokens
vectorStore.add(chunks); // embeds each chunk and stores it
}
}

Notice the metadata. The chunks inherit the policy id, title and country from their document. We need the title and id to cite sources later, and fields like country to filter the search so that a question from a German employee does not retrieve the US travel policy. Chunk size is a real decision: TokenTextSplitter's defaults are a reasonable start, and we tune them after measuring.

3Query: Embed, Search, Add to the Prompt

When a question arrives, we embed it with the same embedding model, search the vector store for the nearest chunks, and build a prompt that contains those chunks as context. Spring AI can do this for us with a retrieval advisor, but writing it out once shows what happens.

Java
String answer(String question, String country) {
List<Document> hits = vectorStore.similaritySearch(SearchRequest.builder()
.query(question) // embedded with the same EmbeddingModel
.topK(5)
.similarityThreshold(0.5)
.filterExpression("country == '" + country + "'") // country from the user's profile
.build());
// hits: 5 chunks, from "Travel Policy DE" sections 4.1 and 4.2, scores 0.81 to 0.62
String context = hits.stream()
.map(d -> "[" + d.getMetadata().get("title") + "] " + d.getText())
.collect(Collectors.joining("\n\n"));
return chatClient.prompt()
.system(SYSTEM_RULES)
.user(u -> u.text("Context:\n{context}\n\nQuestion: {question}")
.param("context", context).param("question", question))
.call().content();
}
Step throughThe two phases of RAG
  1. Read documentsDocumentReader, for example Tika
  2. Split into chunksTokenTextSplitter, metadata copied
  3. Embed and storeEmbeddingModel + VectorStore
  4. Embed the questionsame embedding model
  5. Search similar chunkstop 5, filtered by metadata
  6. Prompt with contextanswer only from it, cite sources

6 steps in order. Play them, or step through them one at a time.

Steps 1 to 3 run at ingestion time; steps 4 to 6 for every question.

In production we would replace this hand-written code with QuestionAnswerAdvisor or RetrievalAugmentationAdvisor, which do the same steps, but the shape stays the same. The country value comes from the authenticated user on the server, never from the question text.

4Keeping the Model to the Context

Retrieval gives the model the right passages, but it might still mix in what it remembers from training, or invent an answer when the passages do not contain one. So the system message says plainly: answer only from the context, cite the title of each policy you used, and if the context does not contain the answer, say you do not know and suggest contacting HR. Citations let the reader check the answer in seconds, and the not-found rule turns a confident wrong answer into an honest gap that we can then fix by adding documents.

Java
static final String SYSTEM_RULES = """
You answer questions about company policies.
Use only the information in the Context. Do not use other knowledge.
After each statement, cite the policy title in square brackets.
If the Context does not answer the question, reply exactly: "I could not find this in the policies."
""";
// Q: "Hotel limit in Berlin?" -> "Up to 150 EUR per night in Berlin [Travel Policy DE]."
// Q: "Can I bring my dog to the office?" -> "I could not find this in the policies."

5What Really Decides Quality

When a RAG assistant gives bad answers, the model is rarely the cause. Usually the right passage never reached the prompt. Chunks that are too small cut a rule away from its exceptions; chunks that are too large dilute the embedding so the search misses them. Missing metadata means the search returns the wrong country's policy. Old versions of a policy left in the store produce outdated answers. Tables and scanned PDFs read badly. So we measure retrieval on its own, with a set of real questions and the chunks that should come back, and tune chunking, filters and top-k against it before we blame or replace the model.

6Follow-up questions

How big should a chunk be?

There is no universal size. A few hundred tokens with a small overlap between neighbouring chunks is a common starting point for policy text. Splitting on headings, so each chunk is one section, often works better than splitting at a fixed size. We choose by measuring retrieval on our own questions.

Why not just use a model with a huge context window and send all documents?

Cost and latency grow with every token, so sending thousands of pages per question is expensive and slow, and models also use information in very long prompts less reliably. Retrieval keeps prompts small and focused, and it lets us filter by permissions.

What happens when a policy changes?

We re-ingest that document: delete its old chunks by its id, then read, split and embed the new version. Keeping a document id in the metadata is what makes that targeted update possible.

7Conclusion

In this answer, we followed the two phases of RAG. Ingestion read the policy documents with a DocumentReader, split them with TokenTextSplitter, kept metadata such as title and country, and stored the chunks in a VectorStore, which embedded them with the EmbeddingModel. At question time we embedded the question, searched with a metadata filter, put the top chunks in the prompt, and told the model to answer only from that context, cite sources and admit when it cannot find the answer. Finally we saw that chunking, metadata and retrieval decide quality more than the model.

What to say in the interviewAbout 80 seconds aloud

Open with

Retrieval-augmented generation has an ingestion phase and a query phase. In ingestion, I read each policy document into text with a DocumentReader, for example the Tika reader, attach metadata such as the document id, title and country, and split it into chunks of a few hundred tokens with a TextSplitter like TokenTextSplitter.

Then, if they want more

Then I add the chunks to a VectorStore, such as PGvector, which calls the EmbeddingModel to compute an embedding for each chunk and stores both.

At question time, I embed the question with the same embedding model, run a similarity search for the top five or so chunks, with a metadata filter for things like the user's country, and put those chunks into the prompt as context.

The system message tells the model to answer only from that context, to cite the policy title for each statement, and to say it could not find the answer if the context does not contain it. In Spring AI I would usually let QuestionAnswerAdvisor or RetrievalAugmentationAdvisor do the query side.

The important point is that quality depends mostly on retrieval: chunk sizes, good metadata and filters, removing outdated versions and measuring whether the right chunks come back for real questions, rather than on which model I choose.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring AI reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain the steps of retrieval-augmented generation for a Java service that answers...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/039a87c518/