Build a Document Q&A App with Amazon Bedrock Knowledge Bases and S3 Vectors

Recently, I taught a live session to students at Information Technology University (ITU) in Lahore. The question I opened with was simple:
How do you get a reliable answer out of a 200 page PDF without reading the whole thing every time?
Ctrl+F finds words. It does not find meaning. And if you paste the whole document into a chat model, you pay for every page on every question, and the model may still make things up.
The fix is Retrieval Augmented Generation (RAG). In this post I will walk through the app I built for that session, called Poocho AI ("poocho" means "ask" in Urdu). Students upload their own notes, ask questions, and get an answer with the file name and page number it came from.
Code is public:
- Backend: https://github.com/usman-gen-ai/itu-rag-document-backend
- Frontend: https://github.com/usman-gen-ai/itu-rag-document-frontend
What we are building
The app does four things:
- A student uploads a PDF, DOCX or TXT file.
- The file is split into chunks and turned into embeddings automatically.
- The student asks a question in plain language.
- The app answers only from that student's files and shows the source page.
Poocho AI chat answering a question about a semester roadmap, with the source file and page numbers shown
In the screenshot, I uploaded a degree roadmap and asked which subjects are in semester 1. The answer lists the subjects and cites the file with pages 1 and 9.
The RAG idea in three steps
You do not retrain the model. You hand it the right pages.
- Retrieve the chunks of your document that are closest in meaning to the question.
- Augment the prompt by placing those chunks next to the question.
- Generate an answer that is allowed to use only that text.
Four terms come up all the time, so here they are in one line each. A chunk is a small piece of a document. An embedding is a list of numbers that captures the meaning of a piece of text. A vector store is a database that finds text with similar meaning. A prompt is the question plus the retrieved chunks, sent to the model.
Architecture
The whole backend is serverless. There is no server to patch and nothing running when nobody is asking questions.
The services involved:
| Service | Job |
|---|---|
| Amazon S3 | Stores the uploaded files |
| Amazon SQS | Collects upload events so syncs can be batched |
| AWS Lambda | Runs the Express API and the sync worker |
| Amazon Bedrock Knowledge Bases | Chunking, embedding, retrieval |
| Titan Text Embeddings V2 | Turns text into vectors |
| Amazon S3 Vectors | Stores and searches the vectors |
| Amazon Nova Micro | Writes the final answer (default in my config) |
The API is an Express app wrapped with serverless-http and exposed through a Lambda Function URL, so I did not need API Gateway. That kept the workshop setup short, but the URL is public with no authentication, which I come back to at the end.
Step 1: Upload without sending files through Lambda
The frontend never posts the file to my API. It asks for a presigned URL, then uploads straight to S3.
curl -s -X POST $API/api/upload-url \ -H 'Content-Type: application/json' \ -d '{"userId":"student_42","fileName":"physics notes.pdf","fileType":"application/pdf"}' Along with the URL, the API writes a small companion file next to the document, called physics_notes.pdf.metadata.json. It holds the userId and the file name. Bedrock Knowledge Bases reads these metadata files and attaches the values to every chunk. That one detail is what makes per user search possible later.
Step 2: Chunking and embeddings
The data source is configured with fixed size chunking:
ChunkingConfiguration: ChunkingStrategy: FIXED_SIZE FixedSizeChunkingConfiguration: MaxTokens: 300 OverlapPercentage: 20 Each chunk is at most 300 tokens, and neighbouring chunks share 20 percent of their text so a sentence cut at a boundary still appears whole in one of them.
For embeddings I used Titan Text Embeddings V2 with 1024 dimensions, and the S3 Vectors index uses cosine distance with float32 values.
Chunk size is the first knob to turn when answers feel off. Small chunks are precise but can lose context. Large chunks keep context but bring in noise. I kept 300 tokens because student notes and course outlines are short and dense.
Step 3: Syncing without tripping over yourself
Knowledge Bases need an ingestion job to read new files. The problem is that only one job can run at a time, and in a class everyone uploads at once.
So uploads do not start jobs directly. The flow is:
- S3 sends an
ObjectCreatedevent to SQS. - SQS waits about 20 seconds to collect a batch.
- The
syncWorkerLambda starts one ingestion job, which covers every pending file. - If a job is already running, the message goes back to the queue with exponential backoff, from 30 seconds up to 10 minutes.
- After 15 failed attempts the message lands in a dead letter queue.
The worker also ignores the .metadata.json files, otherwise every upload would trigger two syncs.
Step 4: Asking questions, only on your own files
Chat uses the RetrieveAndGenerate API. The important part is the filter:
retrievalConfiguration: { vectorSearchConfiguration: { numberOfResults: 15, filter: buildFilter(userId, documents), }, } Because every chunk carries the userId from its metadata file, the search only looks at that student's vectors. The API also checks that every returned citation lives under uploads/{userId}/ before showing it, as a second layer.
The response includes the answer, the sources with document name and page number, and a sessionId. Sending the sessionId back lets the student ask follow up questions.
Page numbers come from the x-amz-bedrock-kb-document-page-number metadata that Bedrock adds for PDFs. For TXT and DOCX files there is no page, so the field comes back empty.
Step 5: Making the model stay honest
A normal RAG prompt says "use the context if it helps". That still lets the model fall back on its own knowledge, which is exactly the hallucination problem we started with.
My prompt forces the model to begin every reply with one tag:
-
[GROUNDED]means the answer comes from the search results -
[CHAT]means a greeting or small talk that does not need documents -
[NOTFOUND]means the documents do not clearly contain the answer
The backend reads the tag and decides what to show. Sources appear only for grounded answers that have real citations. A [NOTFOUND] reply says it could not find the answer in the uploaded documents, instead of guessing.
The grounded rules are short: use only the search results, never invent names, numbers or pages, answer the supported part if the results are partial, and reply in the same language and script as the student. That last rule matters here, because students ask in English and in Roman Urdu.
There is one rule for list questions as well. Asking for "all courses with 3 credit hours" is easy to answer badly, because a model tends to stop at the first match. The prompt tells it to go through every search result and include every match.
I also added a STRICT_RAG switch. Set it to false and the app uses a loose prompt that lets the model answer from general knowledge. In the live session I flipped it to show students the same question answered both ways. Seeing a confident wrong answer next to a grounded one teaches more than any slide.
Testing in the Bedrock playground first
Before writing backend code, I tried the candidate models in the Bedrock playground with the same prompts. It is the fastest way to compare tone, speed and cost, and it costs nothing in code. There is also a debug route in the API, /api/debug/retrieve, that runs retrieval alone without the generation model. When an answer is wrong, that tells you quickly whether retrieval or generation is the culprit.
Things I would fix before real users
This was built for a workshop, so a few shortcuts are worth naming:
- Exposing the Lambda Function URL publicly is fine for a workshop demo, but it is not the right setup for production. It uses
AuthType: NONE, so anyone who finds it can call the API, and every chat request costs model usage. CORS only restricts browsers, not other clients. For real users, put API Gateway with a Cognito or JWT authorizer in front, or keep the Function URL private withAWS_IAMauth behind CloudFront, and add throttling. -
userIdcurrently comes from the request body. Anyone who guesses another id could query that person's files. A real deployment should put Cognito or a JWT authorizer in front and read the id from the token. - Add a Bedrock Guardrail, rate limiting and a CloudWatch alarm on the dead letter queue.
- Delete resources after practice. Empty the source bucket first, then remove the stack.
What the students took away
The part that surprised them most was how little code the retrieval side needs. Pointing Knowledge Bases at an S3 bucket replaces the chunking code, the embedding calls and the vector database you would otherwise run yourself. The real work moved to the parts that decide whether the app can be trusted: isolation between users, a strict prompt, and sensible sync handling.
If you try this, start with one PDF, one question, and the retrieval debug route. Once you can see which chunks come back, everything else gets easier to reason about.
I also shared the session highlights on LinkedIn: LINKEDIN_POST_LINK
If you build your own version, I would like to hear what chunk size worked for your documents.