Capstone: design the document Q&A service
Write the architecture, API and event contracts, data model, failure paths and evaluation fixtures.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 13 minutes to read.
In short
Before writing code, you write down how the document Q&A service will work: the two main paths through the system, the HTTP and event contract, the data model, which failures it must handle and the fixtures you will test against. Two demo tenants, contoso and fabrikam, share one synthetic document set so every design choice can be checked for tenant isolation. A one-page design like this keeps the build focused and gives reviewers something concrete to challenge.
Think of it like this: It is the architect's drawing and the plumbing plan before the builders arrive: cheap to change on paper, expensive once the concrete is poured.
Explained simply
The capstone is a small but complete product: people upload documents, the system reads and indexes them, and then users ask questions and get answers that point to the exact source. Two pretend companies, contoso and fabrikam, use it at the same time, and neither may ever see the other's documents.
Before building, you write a short design. It shows two pictures: how a question travels from the browser to an answer, and how an upload travels from the browser to a searchable index. It also lists every endpoint, what it accepts and what it returns.
The design names which part of the system is in charge of each piece of information. The database owns document and job records. The queue only carries job IDs. The browser owns what is on screen. Being clear about this prevents two places from disagreeing about the truth.
Finally, the design lists what can go wrong and what the system promises in each case, and it describes the test data. You will use one small set of made-up documents for both tenants, plus a list of questions with known correct answers.
Press Play on a diagram to walk through it one step at a time.
- 1Browser
POST /chat with question and bearer token
- 2API
Validates body, assigns request ID
- 3Auth
Verifies token; resolves user, tenant and allowed documents
- 4Retrieval
pgvector top-k filtered by tenant_id
- 5Model
Fake model locally; adapter for a real provider later
- 6Response
SSE events: citation, delta, complete or error
- 1Upload
POST /documents returns 202 with document and job IDs
- 2Object store
Original file under tenants/{tenant}/docs/{id}
- 3Job queue
Job ID enqueued after the DB commit
- 4Worker
Extracts text and splits it into chunks
- 5Embeddings and index
Chunk vectors upserted with an embedding version
- 6Status
Job marked succeeded or failed; client polls GET /jobs/{id}
- Full success
- 202, job succeeded
- citation, delta, complete
- Cross-tenant denial
- 404 on fabrikam job
- No fabrikam chunks retrieved
- No-source answer
- Fixed safe message
- No citation events
- Retryable provider error
- Bounded retries with jitter
- error event, retryable true
- Duplicate delivery
- Second claim updates no row
- Chunks upserted once
- Mid-stream cancellation
- Model call cancelled
- Message saved as cancelled
- Browser to API: POST /chat {question}1POST /chat {question}
- API to Postgres: Top-k chunks WHERE tenant_id = contoso2Top-k chunks WHERE tenant_id = contoso
- Postgres to API: 3 chunks above threshold33 chunks above threshold
- API to Browser: event: citation (x3)4event: citation (x3)
- API to Fake model: Generate with chunks as context5Generate with chunks as context
- Fake model to API: Text pieces6Text pieces
- API to Browser: event: delta (repeated)7event: delta (repeated)
- API to Browser: event: complete {message_id, usage}8event: complete {message_id, usage}
In depth
The HTTP and event contract
Keep the API small. POST /documents takes a multipart upload, checks size and type, and returns 202 with a document_id and job_id. GET /jobs/{id} returns the job status: queued, running, succeeded or failed, with attempts and a safe error code. GET /documents lists the caller's documents with cursor pagination. POST /chat takes a question and optional document IDs, and answers with a text/event-stream response.
The stream uses four event types. citation carries a source reference with document_id, chunk_id and a short label. delta carries a piece of answer text. complete carries the message ID and token usage. error carries a stable code and a retryable flag, because once streaming starts the HTTP status is already 200. Health is split: /healthz says the process is alive, /readyz says the database and queue are reachable.
- 413 for files over the limit, 415 for unsupported types
- 404 for another tenant's document or job, never 403
- 422 for invalid bodies, using FastAPI's default error shape
- 429 with Retry-After when a user's quota is used up
- Events: citation, delta, complete, error
The data model
Every table that holds customer data carries tenant_id, and composite indexes start with it so tenant filters stay fast. Documents and jobs are separate: a document is the thing the user owns, a job is one attempt to process it, so re-indexing creates a new job without touching the document. Chunks store the text, its position, an embedding_version and the vector, with a unique key on document, position and version so retries can upsert instead of duplicating.
Conversations and messages store chat history. A message has a status of streaming, complete, cancelled or failed, so a cancelled stream still leaves an honest record. An audit_events table records deletions and security events.
- tenants and users
- id, name
- user email, role
- documents
- filename, content type, size
- storage key
- status
- jobs
- document_id, kind
- status, attempts
- error_code, updated_at
- chunks
- document_id, position
- text, embedding_version
- embedding vector(256)
- conversations and messages
- role, content
- status, token usage
- cited chunk IDs
- audit_events
- actor, action
- request_id, details
Who owns which state
Confusion about ownership causes the worst bugs: a UI that shows done while the job failed, or a queue message treated as the record of truth. Write one owner per piece of state and make everyone else read from it. The queue can lose or repeat messages, so it holds only job IDs; the job row in Postgres is the truth. The provider owns nothing you depend on later: anything you need, such as token usage, is copied into your own tables.
- 1Browser
Form input, current job ID, rendered stream, abort controller
- 2API
Request ID, verified identity; no state between requests
- 3Queue (Redis)
Job IDs waiting for a worker; may deliver twice
- 4Database
Documents, jobs, chunks, messages, audit: the source of truth
- 5Object store
Original files and extracted text
- 6Worker
The job it has claimed, only while it runs
- 7Model provider
Nothing durable for you; may retain requests per its terms
Supported failure paths
List each scenario with the promised behaviour. Full success: upload, job succeeds, chat streams citations, deltas and complete. Cross-tenant denial: a contoso user asking for a fabrikam job or document gets 404, and retrieval never returns fabrikam chunks. No-source answer: when no chunk passes the similarity threshold, the service streams a fixed "I could not find this in your documents" message with no citations instead of guessing. Retryable provider error: a 429 or timeout is retried a bounded number of times with jitter; if it still fails, the stream sends an error event with retryable true. Duplicate delivery: the same job ID arriving twice is processed once. Mid-stream cancellation: the browser aborts, the server stops the model call, and the message is saved as cancelled with the partial text.
Fixtures for two tenants
Write a handful of short synthetic documents per tenant: a contoso travel policy and invoice guide, a fabrikam onboarding handbook and security policy. Give each a few unique facts, such as "Contoso reimburses hotel stays up to 150 EUR per night", and plant one canary phrase per tenant, such as CANARY-FAB-7, that must never appear in the other tenant's answers.
Then write the eval set as JSON: each case has a tenant, a question, the expected document and chunk, key phrases the answer must contain, or a flag saying no answer exists. Include at least one no-source question per tenant and one question that only the other tenant's documents could answer. Because the fake model and embedder are deterministic, these cases give the same scores on every run.
- 3 to 5 documents per tenant, all made up
- One canary phrase per tenant
- 15 to 25 eval cases with expected sources
- No-source and cross-tenant cases for each tenant
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Draw the request and ingestion diagrams~50m
- 2Specify the HTTP and event contract~50m
- 3Design the data model~50m
- 4List supported failure paths~50m
- 5Prepare fixtures for two tenants~50m
Key points
- The contract is POST /documents, GET /jobs/{id}, GET /documents, POST /chat, plus /healthz and /readyz.
- Every table that holds customer data has a tenant_id column, and every query filters on it.
- Write down six failure paths up front: success, cross-tenant denial, no source, retryable provider error, duplicate delivery and mid-stream cancellation.
- Say which component owns each piece of state: browser, API, queue, database, provider or worker.
- Fixtures and expected answers are designed now, so the build has a target to hit.
Key terms
Tap a card to flip it. 0/5 known
Examples
Sample payloads for upload and polling
Step 1: a contoso user uploads travel-policy.pdf. The API stores the file, writes document and job rows in one transaction, enqueues the job ID and returns 202. Step 2: the browser polls the Location URL every two seconds. Step 3: the job moves from queued to running to succeeded. Step 4: a fabrikam user asking for the same job ID gets 404 with the same body as for an ID that does not exist.
POST /documents (multipart, file=travel-policy.pdf)
202 Accepted
Location: /jobs/job_01J9X2
{"document_id": "doc_01J9X1", "job_id": "job_01J9X2", "status": "queued"}
GET /jobs/job_01J9X2
200 OK
{"id": "job_01J9X2", "status": "succeeded", "attempts": 1, "error_code": null}
GET /jobs/job_01J9X2 (as a fabrikam user)
404 Not Found
{"detail": "Not found", "request_id": "req_7f3a"}Two chat streams: a cited answer and a no-source answer
Step 1: a contoso user asks about the hotel limit. Retrieval finds a matching chunk, so the stream sends a citation, then deltas that mark the source as [1], then complete. Step 2: the same user asks about parental leave, which no contoso document covers. No chunk passes the threshold, so the stream sends the fixed no-source text and complete, with no citation event. The UI renders both from the same event handler.
event: citation
data: {"n": 1, "document_id": "doc_01J9X1", "chunk_id": "chk_14", "label": "travel-policy.pdf p.2"}
event: delta
data: {"text": "Hotel stays are reimbursed up to 150 EUR per night [1]."}
event: complete
data: {"message_id": "msg_88", "usage": {"input_tokens": 412, "output_tokens": 14}}
--- no-source case ---
event: delta
data: {"text": "I could not find this in your documents."}
event: complete
data: {"message_id": "msg_89", "usage": {"input_tokens": 0, "output_tokens": 0}}Quick reference
- POST /documents -> 202 {document_id, job_id}; GET /jobs/{id} -> status
- POST /chat -> text/event-stream with citation, delta, complete, error
- /healthz = process alive; /readyz = database and queue reachable
- Other tenant's resource -> 404, never 403
- Every customer table has tenant_id; indexes start with it
- Queue carries job IDs only; the job row is the truth
- Unique (document_id, position, embedding_version) lets ingestion retry safely
- Fixtures: two tenants, canary phrases, no-source and cross-tenant eval cases
Common mistakes
- Designing only the happy path, then discovering streaming errors cannot change the HTTP status once headers are sent.
- Returning 403 for another tenant's job, which confirms that the ID exists; 404 reveals nothing.
- Fixtures with only one tenant, which can never catch a cross-tenant leak.
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 the Pydantic v2 response models for POST /documents and GET /jobs/{id}.
- Exercise 2medium
Write six eval cases in JSON covering success, cross-tenant and no-source questions for both tenants.
- Exercise 3hard
Write the design table for all six failure paths: trigger, how you simulate it locally, expected API behaviour and the evidence you will capture.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why use a fake model instead of a real one for the capstone?
- It is free, works offline and gives the same output every run, so tests and evals are reliable. The adapter interface lets you plug in a real provider later.
- Should I use WebSockets instead of SSE for chat?
- SSE over a POST is enough here because the server is the only one streaming. WebSockets help when both sides need to send messages continuously.
- Why poll for job status instead of pushing updates?
- Polling is simple, works through every proxy and recovers from page reloads. You can add push updates later without changing the job model.
- How detailed should the design document be?
- Enough that someone else could build the same contract: diagrams, endpoints with sample payloads, tables, failure paths and fixtures. One to three pages is typical.