Capstone: build the document Q&A service
Build upload, ingestion, polling, tenant-aware retrieval, streamed chat with citations and a minimal UI on a fake model.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.
In short
This milestone turns the design into a running service: upload and ingestion, job polling, tenant-aware retrieval, streamed chat with citations and a minimal browser page, all on a deterministic fake model. Everything runs locally with Docker Compose, so it costs nothing and gives the same answers every time. A real model provider can be plugged in later behind the same adapter.
Explained simply
Now you build the service you designed. Start with the plumbing: a Docker Compose file that runs Postgres with the pgvector extension, Redis and a local folder or MinIO for files. Then add the FastAPI app and a separate worker process that share the same code.
Build uploads next. The API checks the file, saves it, records a document and a job, and hands the job ID to the queue. The worker picks it up, pulls out the text, cuts it into chunks, turns each chunk into a list of numbers called an embedding, and saves everything to Postgres.
Then build chat. The API looks up the user's tenant, finds the most similar chunks for that tenant only, and streams an answer back piece by piece, sending the sources first so the page can show them as the text appears.
All of this runs on a fake model and a fake embedder that always give the same output for the same input. That keeps it free and makes tests reliable. The last piece is a tiny web page with an upload form, a status line and a chat box.
Press Play on a diagram to walk through it one step at a time.
- 1Minimal UI
Static page: upload form, job status, chat with citations
- 2FastAPI app
Routers for documents, jobs, chat and health
- 3Services
Retrieval, model adapter, storage adapter, auth
- 4Worker
Pulls job IDs, extracts, chunks, embeds, indexes
- 5Infrastructure
Postgres with pgvector, Redis queue, local object store
- Queue to Worker A: job j11job j1
- Worker A to Postgres: Claim j1: queued to running (wins)2Claim j1: queued to running (wins)
- Queue to Worker B: job j1 again (redelivery)3job j1 again (redelivery)
- Worker B to Postgres: Claim j1: no row updated4Claim j1: no row updated
- Worker B to Queue: Ack and skip5Ack and skip
- Worker A to Postgres: Upsert chunks; mark j1 succeeded6Upsert chunks; mark j1 succeeded
- Free and offline
- Same output for the same input
- Failure modes on demand
- Answers built from chunk text only
- Usually paid per token
- Output varies between runs
- Real 429s, timeouts and outages
- Needs a key from the secret store
In depth
Project layout and the local stack
Use one Python package with clear modules: routers for HTTP, services for business logic, adapters for storage, queue and model, and a worker entry point. The API and the worker run from the same image with different commands, which keeps their models and settings in sync.
Prerequisites: Docker with Compose, Python 3.12 or newer, and about 2 GB of free memory. The pgvector/pgvector image ships Postgres with the extension available; your first Alembic migration runs CREATE EXTENSION IF NOT EXISTS vector. Settings come from environment variables through pydantic-settings, with MODEL_PROVIDER=fake as the default. Expected evidence after docker compose up: /healthz returns 200 and /readyz returns 200 once Postgres and Redis answer.
- app/routers: documents, jobs, chat, health
- app/services: ingestion, retrieval, chat
- app/adapters: storage, queue, model, embedder
- app/worker.py: the job loop
- Same image, two commands: uvicorn and python -m app.worker
Upload, ingestion and job status
The upload route reads the file in a streaming way and rejects it with 413 once it passes the size limit, then checks the type against an allowlist such as PDF, plain text and Markdown. It writes the file to tenants/{tenant}/docs/{document_id}, then in one transaction inserts the document and a queued job. Only after the commit does it push the job ID to Redis.
If the API crashes between commit and enqueue, the job would wait forever. A small sweeper fixes that: every minute it re-enqueues queued jobs older than a few minutes, and moves running jobs whose lease has expired back to queued. The worker claims jobs with a conditional UPDATE, upserts chunks, and marks the job succeeded, or failed with a safe error code after the last attempt.
- 1queued
Row committed; job ID on the queue
- 2running
Claimed by one worker; lease starts
- 3Retryable error
Timeout or crash; attempts below the limit
- 4Back off
Sweeper re-queues after the lease or delay
- Back to step 1
Tenant-aware retrieval with a deterministic embedder
The fake embedder lowercases text, splits it into words, hashes each word into one of 256 slots and normalises the vector to length one. Texts that share words score close under cosine distance, which is enough to test the whole pipeline without a real model. Store embedding_version with every chunk, so that switching to a real embedder later means re-indexing into a new version rather than mixing incompatible vectors.
Retrieval runs one query: filter by tenant_id and the requested document IDs, order by cosine distance to the question vector, limit k. Drop results above a distance threshold; if none remain, use the no-source path. Add an HNSW index on the embedding column with vector_cosine_ops once you have more than a few thousand chunks.
- Same question, same vector, same results every run
- embedding_version on every chunk
- Filter first, then order by distance
- Threshold decides the no-source path
Streaming chat with citations and cancellation
The chat route returns a StreamingResponse with media type text/event-stream. Its async generator sends citation events first, then delta events as the model yields text, then complete. Each event is two lines, event and data, followed by a blank line. Add Cache-Control: no-cache, and X-Accel-Buffering: no if Nginx sits in front.
When the browser aborts, the server cancels the task running the generator, and CancelledError appears at the next await. Catch it in a try and finally block: mark the message cancelled with the partial text, close the provider stream, and re-raise. A provider failure after retries becomes an error event, and the message is saved as failed. The browser uses fetch with an AbortController, because the built-in EventSource only supports GET.
The fake model, the real adapter and the minimal UI
Define one ModelClient protocol with a stream method that takes the question and chunks and yields text pieces plus usage. The fake implementation builds an answer from the first sentence of each chunk, adds [n] markers that match the citation numbers, and yields it word by word. It can also fail on purpose: FAKE_MODEL_FAILURES=429,timeout makes the first two calls fail, which drives the failure tests.
A real provider adapter is optional and usually paid; it reads its key from settings and maps provider errors to your own retryable and fatal types. If no key is set, the app falls back to the fake model and logs that once at startup. The UI is a single static page served by FastAPI: an upload form, a job status line that polls, and a chat box that renders events.
Learn it in 5 short steps
About 2h 25m each. Track them with a timer in your plan.
- 1Build upload and ingestion~2h 25m
- 2Add polling and job status~2h 25m
- 3Implement tenant-aware retrieval~2h 25m
- 4Stream chat with citations~2h 25m
- 5Add a minimal UI and the fake model~2h 25m
Key points
- Build the ingestion path first; chat is useless without indexed chunks.
- The worker claims a job with a conditional UPDATE, so two deliveries of the same job do the work once.
- Retrieval always takes the tenant from the auth dependency, never from the request body.
- Chat streams citation events before delta events, so the UI can show sources as text arrives.
- The fake model and fake embedder are deterministic, so tests and evals give stable results.
Key terms
Tap a card to flip it. 0/5 known
Examples
async def claim(db, job_id) -> bool:
result = await db.execute(
update(Job)
.where(Job.id == job_id, Job.status == "queued")
.values(status="running", attempts=Job.attempts + 1)
)
await db.commit()
return result.rowcount == 1 # False: someone else has it, or it is doneOnly one worker can move a job from queued to running.
A deterministic fake model with failure injection
Step 1: the chat service calls model.stream(question, chunks). Step 2: with FAKE_MODEL_FAILURES unset, the fake yields a cited answer built from the chunks, one word at a time. Step 3: with FAKE_MODEL_FAILURES=429, the first call raises a retryable error, and the retry wrapper's second call succeeds. Step 4: a test asserts the trace shows two attempts and the stream ends with complete.
class FakeModel:
def __init__(self, failures: list[str]):
self.failures = list(failures) # e.g. ["429", "timeout"]
async def stream(self, question: str, chunks: list[Chunk]):
if self.failures:
kind = self.failures.pop(0)
raise ProviderRetryable(kind)
if not chunks:
yield "I could not find this in your documents."
return
parts = [f"{c.text.split('.')[0]} [{i}]." for i, c in enumerate(chunks, 1)]
for word in " ".join(parts).split(" "):
yield word + " "The chat stream with cancellation handling
Prerequisites: retrieval and the model adapter work in isolation. Step 1: the route resolves the user through the auth dependency and retrieves chunks for that tenant. Step 2: the generator sends citations, then deltas. Step 3: if the browser aborts, CancelledError lands at an await, the finally block saves the partial message as cancelled, and the error re-raises so the server cleans up. Evidence: the messages table shows status cancelled with partial content.
def sse(event, data): return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def events(msg, chunks, model, question):
status = "failed"
try:
for n, c in enumerate(chunks, 1):
yield sse("citation", {"n": n, "chunk_id": c.id, "document_id": c.document_id})
async for piece in model.stream(question, chunks):
msg.content += piece
yield sse("delta", {"text": piece})
status = "complete"; yield sse("complete", {"message_id": msg.id})
except asyncio.CancelledError:
status = "cancelled"
raise
finally:
await save_message(msg, status)Quick reference
- docker compose up -d --build, then alembic upgrade head, then seed both tenants
- First migration: CREATE EXTENSION IF NOT EXISTS vector
- Commit document and job rows, then enqueue the job ID
- Claim jobs with UPDATE ... WHERE status = 'queued'; check rowcount
- Sweeper re-queues stale queued jobs and expired running leases
- SSE event = event line + data line + blank line; media type text/event-stream
- Browser: fetch + AbortController for POST streams; EventSource is GET only
- MODEL_PROVIDER=fake by default; FAKE_MODEL_FAILURES drives failure tests
Common mistakes
- Enqueuing the job before the database commit, so a fast worker finds no row.
- Calling the fake model with a different interface from the real one, so swapping providers breaks routes.
- Forgetting to stop work when the browser disconnects, which keeps paying for tokens nobody reads.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write GET /jobs/{job_id} so it returns 404 when the job belongs to another tenant.
- Exercise 2medium
Write a deterministic hashing embedder that returns a normalised 256-number vector.
- Exercise 3hard
Write the sweeper query that re-queues running jobs whose lease expired, and fails them after 3 attempts.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need MinIO, or is a local folder enough?
- A local folder behind a storage adapter is enough for the capstone. MinIO is useful if you want to test S3-style calls before deploying.
- Which Redis queue library should I use?
- Any simple option works, such as arq, RQ, or a plain Redis list with BLMOVE. What matters is that job state lives in Postgres and processing is idempotent.
- Can I use a real model instead of the fake one?
- Yes, behind the same adapter, but it usually costs money and makes outputs vary. Keep the fake as the default for tests and evals.
- Why not run ingestion inside the upload request with BackgroundTasks?
- Background tasks die with the process and have no retry or status. A queue plus a job table survives restarts and lets you scale workers separately.