Stage 6 · Architecture at scale · Medium · 15 min
LLM serving and retrieval (RAG)
An app answers from your own documents with a language model. See how to index them in chunks, retrieve the closest ones, and keep cost and wait time down.
What each interview level is expected to knowEmerging topicPart of the AI track: start with AI basics
Learn first: Search indexes and autocomplete, Caching strategies, Rate limiting
In AI systems: AI basics, in plain English, How a model writes, one token at a time, Prompt, retrieve or fine-tune, Security: prompt injection and data boundaries
After this lesson you can:
- Follow a question through indexing, retrieval and answer writing.
- Explain where cost and latency come from, and how to control them.
- Enforce who may read which document inside the search, not after it.
Start here
See it in 60 seconds
Look it up, then answer
Retrieval-augmented generation finds the chunks of your documents that best match a question, and gives them to the model to answer from.
Scene 1 of 6 · Split the documents
The help pages are split into 6 short chunks, and each chunk is stored in an index.
- You — healthy
- Help app — healthy
- Chunk index — healthy
- Language model — healthy
| Chunk | Text |
|---|---|
| c1 | Reset: hold the reset button for 10 seconds to restore factory settings. |
| c2 | Wi-Fi password: find it on the sticker under the router. |
| c3 | Lights: a red light means there is no internet connection. |
| c4 | Updates: the router installs updates every night at 3 am. |
| c5 | Warranty: a broken router is covered for two years. |
| c6 | Guest network: turn it on in the app under Settings. |
- Split the documents. The help pages are split into 6 short chunks, and each chunk is stored in an index.
- A question comes in. You ask the help app: "How do I reset my router?"
- Find the closest chunks. The app finds the 2 closest chunks; here a simple word match stands in for real meaning search.
- Add them to the prompt. It sends the model the question plus those chunks, and asks it to answer only from them.
- Answer with sources. The model answers from chunk c1 and names it as the source, so you can check the answer.
- Noise in the results. c2 matched only on router, so it is noise; if search misses the right chunk, the model may guess.
- Now you try. Pick a question, and see which chunks the word match finds. For example: Best match: c5, with 3 word matches; c2 comes next with 1. c2 only shares a word many chunks have, so it is noise; real systems mostly compare meanings, often alongside word match.
Scene 1 of 6: Split the documents. The help pages are split into 6 short chunks, and each chunk is stored in an index.
Key points
- Documents are split into short chunks, and the chunks are stored in a searchable index.
- For each question, the closest chunks are found and added to the prompt.
- The model answers from those chunks, and can name them as its sources.
- If search misses the right chunk, the answer suffers, so retrieval quality matters most.
In plain words
Say a help app for a home (A network device that passes each packet on, one step at a time, towards the machine it is addressed to.) gets the question "How do I reset my router?". The app first searches the router's help pages, which are stored as six short chunks. It picks the two closest chunks. Then it sends the question and those chunks to a large language model (LLM), a program that writes text one small piece at a time. The model answers from chunk c1, which says to hold the reset button, and it names c1 as its source. This pattern is called retrieval-augmented generation (RAG): retrieve the text first, then generate the answer from it. The parts around it are ordinary system design: search, caching, streaming and limits.
Some of the work happens before any question arrives. The help pages are cut into chunks, and each chunk is turned into a list of numbers, called an embedding, that captures its meaning. When the question comes in, it gets the same treatment, and the search finds the chunks whose numbers are closest. A wrong or missing chunk leads to a wrong answer, so the search needs as much care as the model.
The problem it solves
A model on its own has three limits. It does not know private or recent data. It can state something false in a confident voice. And each call can take seconds, and costs money for the text going in and coming out. A first design sends every request to the largest model, with no retrieval, (A small, fast store that keeps copies of popular data, so most reads skip the slower database.) or limit. It is slow and costly, and it cannot answer from your own data.
Why it matters
A language model knows only the text it was trained on. It has not seen your help pages, your orders or last week's price change. Ask it about them and it may give a wrong answer that sounds right. So an app that must answer from your data looks the facts up first and hands them to the model. A model call is also slow and costly next to a database query, so the calls need caches and limits.
A worked example
A model call might take roughly 2 seconds and cost roughly $0.01, rough figures that vary by provider and model size. Handling 10,000 questions a day then costs about 10,000 × $0.01 = $100 a day, very roughly. Looking up the right passages first typically adds only about 100 ms, small next to the model's own 2 seconds.
Think of it like…
Think of a helpdesk agent who has not memorised every policy. Before answering a hard question, they open the manual at the right page and read from it.
Where this analogy stops working
Looking it up first, then answering, is the useful part. But an agent notices when the manual has no answer, and says so. A model may still write a sure-sounding answer when the passage is wrong or missing. So the search step needs testing, and the answer should name its source.
Try it
See it working
Emerging topic
- Documents — source of truth — healthy
- Chunker — + metadata, ACLs — healthy
- Embedding model — healthy
- Search indexes — vector + keyword — healthy
- User — healthy
- API gateway — auth · quotas · cache — healthy
- Retriever — hybrid search — healthy
- Reranker — healthy
- LLM — streams tokens — healthy
- Guardrails — checks + logging — healthy
- Request/response
- Asynchronous
Step 1 of 6 — User. A user asks a question in the product.
- How it fails
- Users paste huge inputs or try to override instructions (prompt injection).
- Typical time
- —
Timings are rough ranges for reasoning about a latency budget, not measurements. They vary widely with model size, hardware and prompt length.
Run the pipeline yourself
Runs for every question a user asks.
On: the search returns 5 chunks, and a second check picks which to keep.
- User — healthy — NOW
- Application — runs each step — healthy
- Language model — writes the answer — healthy
- Embedding model — text to vector — healthy
- Vector index — chunks and vectors — healthy
- Reranker — turned off — IDLE
- Request
- Search
- Response
Step 1 of 6 · User
Done: The user asks a question
- What happens
- The user sends a question to the application.
- Why
- The model was not trained on this shop's help pages. The application has to look the answer up first.
- What changes
- The application now holds the question: "Can I return a sale item after 20 days?"
- Next
- Turn the question into a vector
Event log
5 more to go. Press a line to go back to that step.
The chunks found, the prompt and the answer show here as the run reaches them.
Step 1 of 6: User. The user asks a question. The user sends a question to the application.
Things to try
- Keep 1 passage for the sale question. The closest chunk is the 30-day rule, so the answer is wrong.
- Now turn the reranker on. The 14-day chunk moves to place 1 and the answer is right again.
- Ask about price matching. The pages do not cover it, yet the search still returns its closest chunks.
- Set the chunk size to 4 sentences. Whole pages go into the prompt, and its size grows.
- Ask about Canada with chunks of 2 sentences and keep 1. The Canada sentence shares a chunk with the address rule, which pulls that chunk away. The chunk that says 3 to 5 days wins, so the answer is wrong.
- Now keep 2 chunks, or turn the reranker on. The Canada chunk reaches the prompt and the answer is right.
What this simplifies. The help pages, the map places and the answers are made up for teaching. A real embedding has hundreds of numbers, worked out by a model. Here a chunk's place is the average of its sentences' places, which were set by hand. The reranker uses grades set by hand, where a real one is a second model. The answer follows a fixed rule: it is right when the passage with the answer is in the prompt. A real model usually follows its passages, but not always. Token counts come from this track's teaching splitter.
Also try: Rate limiting · Caching · Serving a language model
Mechanics
How it works
The pictures follow a support assistant that answers questions from a company's help pages.
Index your documents
Split each document into chunks: short passages, often a few hundred words or less. An embedding model turns each chunk into an embedding, a list of numbers that stands for its meaning. Chunks with a similar meaning get lists that are close together. Store each one in a vector (An extra structure, kept sorted or grouped, that lets a database find matching items without reading all of them.), with its text, its source and who may see it.
Retrieve at question time
Pick a case to follow belowWith this case: Vector search alone left out the chunk that names E-1042, so the answer was vague.
Assistant, builds prompt Assistant builds prompt Vector index, by meaning, NOW Vector index by meaning searching NOW Keyword index, exact words Keyword index exact words Language model, writes answer Language model writes answer - Assistant — builds prompt — healthy
- Vector index — by meaning — healthy — NOW — searching
- Keyword index — exact words — healthy
- Language model — writes answer — healthy
- Question or prompt
- Chunks or answer
Step 1 of 3Step 1 of 3 · Vector index
Done: The question is turned into an embedding
- What happens
- The assistant asks the vector index for the 2 nearest chunks.
- Why
- Vector search finds text with a similar meaning.
- What changes
- The index ranks the chunks by meaning.
- Next
- It returns two chunks about payment errors
E-1042 chunk in the promptnoWatch: left outStep 1 of 3: Vector index. The question is turned into an embedding. The assistant asks the vector index for the 2 nearest chunks.
Turn the question into an embedding too, and ask the index for the nearest chunks. This vector search finds similar meaning, but it can miss an exact string such as an error code. Keyword search finds exact words. Hybrid search runs both and merges the two lists. A second, smaller model called a reranker can then keep the best few.
In the picture, a user asks "What does error E-1042 mean?" Vector search keeps the 2 nearest chunks, both about payment errors in general. The chunk that names E-1042 ranks third, so the answer is vague. Hybrid search adds keyword search, which finds the exact code.
Generate with the context
Build a prompt from the instructions, the retrieved chunks and the question. Ask the model to answer only from those chunks and to name the ones it used. A model reads and writes text in small pieces called tokens. Send each token to the user as it is made, which is called streaming. The first words then show while the rest is still being written.
Control cost and latency
Pick a case to follow belowWith this case: A new question cost $0.0105 and about 2 seconds of model time.
Assistant, gets questions Assistant gets questions Answer cache, by question, NOW Answer cache by question miss NOW Language model, billed per token Language model billed per token - Assistant — gets questions — healthy
- Answer cache — by question — healthy — NOW — miss
- Language model — billed per token — healthy
- Cache lookup
- Question or prompt
- Saved answer
Step 1 of 3Step 1 of 3 · Answer cache
Done: The assistant checks the answer cache
- What happens
- Nobody has asked this question yet, so there is no answer stored.
- Why
- A cache can only return answers it has saved.
- What changes
- The question goes to the model.
- Next
- The model reads 2,000 tokens and writes 300
Model calls0Cost of this answer$0Wait for the answer–Step 1 of 3: Answer cache. The assistant checks the answer cache. Nobody has asked this question yet, so there is no answer stored.
A hosted model is billed per token, in and out, and a long answer takes seconds. Cache the answers to questions that repeat. A semantic cache also reuses an answer for a question worded another way. It needs a strict closeness limit, or a different question gets the wrong answer. Send easy requests to a smaller, cheaper model and hard ones to a larger one. Cap the tokens per request, and set a (A cap on how many requests a client can make in a given time; requests over the cap are delayed or rejected.) per user so one user cannot spend the whole budget.
In the picture, a prompt of 2,000 tokens and an answer of 300 tokens cost $0.0105. The prices are examples: $3 per million tokens in and $15 per million out. That is about 1 cent and 2 seconds. The same question again comes from the cache: $0 and about 5 ms.
Evaluate and protect
Pick a case to follow belowWith this case: With no permission filter, the HR chunk entered the prompt and the model showed it to the agent.
Support agent, not in HR Support agent not in HR asks Assistant, builds prompt, NOW Assistant builds prompt NOW Chunk index, with who may see Chunk index with who may see Language model, writes answer Language model writes answer - Support agent — not in HR — healthy — asks
- Assistant — builds prompt — healthy — NOW
- Chunk index — with who may see — healthy
- Language model — writes answer — healthy
- Question or prompt
Step 1 of 3Step 1 of 3 · Assistant
Done: The agent asks about pay rises
- What happens
- The assistant knows who is asking: a support agent, not someone in HR.
- Why
- Each request carries the user, so access can be checked.
- What changes
- The assistant searches the chunk index.
- Next
- Search finds 3 close chunks
Chunks in the promptnone yetHR chunk in the prompt–Step 1 of 3: Assistant. The agent asks about pay rises. The assistant knows who is asking: a support agent, not someone in HR.
What these pictures simplify. These pictures state the ranking, the times and the prices: $3 per million tokens in and $15 out. No real model runs. Real prices and times depend on the provider and the model. The hybrid search tool in the AI engineering track compares word and meaning search on example tickets.
Keep a test set of questions with known good answers, and score the system against it after each change. Filter chunks by the user's permissions before they enter the prompt. A document or a question may hold instructions that try to change what the model does. This is called prompt injection, so treat that text as data and not as orders.
In the picture, a support agent asks how pay rises are decided. A chunk from the HR salary page is close in meaning. With no permission filter it enters the prompt, and the model quotes it. Filtered first, it never reaches the model.
Use it when
- Questions about your own documents, which change often: update the index, and the next answer uses the new text.
- Answers that must show their source: the model names the chunks it used, so a reader can check them.
- More text than fits in one prompt: retrieval picks the few chunks that matter for each question.
- Design problems such as a support assistant, document search or a code helper: each is retrieval plus a model call.
Skip it when
- An exact lookup or a (A group of database changes that succeed or fail together: either all of them are saved, or none are.), such as an order status: query the database, which returns the stored value.
- A task that a rule or a small classifier can do, such as sorting tickets: it costs less and is easier to test.
- A wrong answer would do harm and nobody checks it: a model can state false things even with the right chunks.
Check yourself
Judgement
Trade-offs and how it fails
What you give up
- Quality
- A larger model and a reranker often give better answers. More chunks help only up to a point, because the extra ones can be noise. Measure each change on your own test set.
- Cost & latency
- Each added step costs time and money on every request: a second search, a reranker, a larger model, a longer prompt. A cache, and a smaller model for easy requests, win some of that back.
- Freshness
- The index is a copy of the documents, so it can be out of date. How far behind depends on when you re-index: on every change, or once a night.
Failure modes
- Retrieval misses the right chunk: the model still answers, from memory or from a wrong chunk, and sounds sure.
- Data leak: retrieval ignores permissions and puts another user's document in the prompt. Filter by the user's permissions during retrieval.
- Runaway cost: a very long prompt, or retries against a large model, multiply the bill. Cap the tokens and the retries.
- A stale index: a document changes or is deleted, but its old chunks stay in the index and are still retrieved.
- Prompt injection: a retrieved document says "ignore your instructions", and the model obeys. Limit what the model is allowed to do.
- A changed embedding model: old and new embeddings cannot be compared, so every chunk has to be embedded again.
In the real world
- The name comes from a 2020 paper by Patrick Lewis and others: "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks". Source: Lewis and others, the RAG paper (2020) (checked 14 October 2026)
- Vector search comes in two forms. Pinecone and Milvus are databases built for it. pgvector adds it to PostgreSQL, and OpenSearch and Elasticsearch have vector fields.
- Elasticsearch and OpenSearch both document hybrid search. It merges a keyword score, from a formula called BM25, with a vector score. Source: OpenSearch docs: hybrid search (checked 14 October 2026)
- The API guides from Anthropic and OpenAI describe streaming and prompt caching. With prompt caching, a repeated start of a prompt is billed at a lower price.
Trade-offs to be ready to discuss: Hybrid search vs vector only · Large model vs small model routing
Check yourself
Interview
What interviewers look for
- Start with the parts that are not AI: the request flow, storage, sign-in and rate limits. Then add retrieval and the model call.
- Say where permissions are checked: "Retrieval filters by the user's access, so restricted text does not enter the prompt."
- Give a cost per request: tokens in plus tokens out, times the price, times the requests per day.
- Say how you would measure quality: a test set of questions with known answers, scored after each change.
Say it out loud: Why combine vector search with keyword search for retrieval?
Expected depth by interview level
Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.
- JuniorBeyond this level
- What retrieval adds: the model answers from text the app looked up.
- MidUseful
- The retrieve-then-generate flow.
- SeniorUseful
- Hybrid search, caching, and the cost and wait of each request.
- StaffUseful
- Cost, quality tests and safety when many teams share one model service.
Practice
Apply it
Three harder questions
The first two use the idea on a new case. The last asks you to judge a design.
Apply it
Apply it
Judge a design
Go deeper
Sources and further reading
First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperEfficient Memory Management for Large Language Model Serving with PagedAttention (2023)Kwon et al., SOSPThe vLLM paper: storing the KV cache in pages so more requests fit on one GPU.
- Research paperOrca: A Distributed Serving System for Transformer-Based Generative Models (2022)Yu et al., USENIX OSDIScheduling each step of generation, so new requests join a batch without waiting for it to finish.
- Research paperRetrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020)Lewis et al., NeurIPSThe paper that named RAG: fetch passages, then generate an answer from them.