Chapter 5
The backend API
FastAPI routes, streaming over Server-Sent Events, chat history in SQLite, and the protective layer (rate limits, CORS, input limits) that every public AI endpoint needs.
FastAPI in five minutes
In FastAPI a route is a Python function with type hints. The framework reads those hints to parse and validate the
request, convert the return value to JSON, and generate interactive docs at /docs. A request body
is a Pydantic model: if the JSON doesn't match (missing field, wrong type, mode not "text" or "voice"),
FastAPI answers 422 before your code runs.
Dependencies (Depends) are reusable checks that run before a route: here, "read and
validate the X-Client-Id header", "apply this rate limit", "require the admin token". A route lists what it needs and FastAPI wires it up.
Build once, share everywhere
Loading models and building the index takes seconds, so it happens once at startup in the lifespan
function, and every request reuses the result through a shared state object. Voice models are warmed up
on a background thread so the server is ready for text chat immediately.
Streaming with Server-Sent Events
An HTTP response normally arrives in one piece. For streaming we keep the response open and write to it as
tokens arrive. Server-Sent Events (SSE) is a tiny text format for doing that: each event is a few
field: value lines followed by a blank line. Here's an actual response, captured with curl:
event: meta
data: {"conversation_id": "77d8…", "sources": [{"n": 1, "title": "Lesson scheduling optimizer…", "url": "/experience/drivago-pfe"}, …]}
event: delta
data: {"text": "Amine built "}
event: delta
data: {"text": "the scheduler as a constraint-"}
…
event: done
data: {"message_id": 4, "cited": [2, 1]}
StreamingResponse takes an async generator and sends each yielded string as soon as it's produced.
The two headers matter in production: Cache-Control: no-cache stops anything from caching a stream, and
X-Accel-Buffering: no tells nginx not to collect the whole response before forwarding it. Forget that,
and in production the answer appears all at once at the end, even though it streamed fine on your laptop.
WebSockets give a two-way channel; SSE is one-way (server → browser) over plain HTTP. A chat answer is exactly one request and one streamed reply, so SSE is the simpler fit: it works through every proxy and CDN, needs no special server support, and it's what OpenAI, Anthropic and Google use for their own streaming APIs. You'd reach for WebSockets for continuous two-way traffic, like streaming microphone audio up while audio streams down.
Async, briefly
FastAPI runs on an event loop: one thread juggles many requests by switching between them whenever
one waits on I/O (the network, the LLM). async def + await mark those waiting points. The rule:
never block the loop with long CPU work, or every visitor freezes. Whisper and Kokoro are pure CPU work, so
voice.py runs them with asyncio.to_thread on worker threads. A semaphore limits them to 2 at a
time, so ten simultaneous visitors queue rather than thrash the CPU. SQLite calls take well under a millisecond, so
they're fine inline.
Conversation history
History is two SQLite tables: conversations, and their messages. SQLite is a full SQL database in a single file
(data/assistant.db): no server to run, trivially backed up, thousands of writes per second. That's plenty
until several server processes need to write at once, which is when you'd move to Postgres.
Who owns a conversation? Visitors don't log in. The browser generates a random UUID once, stores
it in localStorage, and sends it as X-Client-Id. Every conversation query is filtered by it. It isn't
authentication (anyone who copied the id could read that history), but a random 122-bit id can't be guessed, which
is the right level for anonymous portfolio chats. Note the API returns 404, not 403, for someone
else's conversation: it doesn't even confirm the conversation exists.
You're storing what visitors type. Keep it minimal (no IPs are stored, just the text), mention it on the site,
and decide how long to keep it. A cron job running DELETE FROM conversations WHERE updated_at < …
is a fine retention policy. In return, reading these logs is the best way to discover the questions your eval set
is missing.
Ratings, and a migration in four lines
The 👍 / 👎 under each answer (chapter 4 explains why they matter) is one nullable column on
messages: 1, -1 or NULL. Adding a column to a table that already
has data is a schema migration. CREATE TABLE IF NOT EXISTS won't do it (the table exists,
so the statement is skipped), so on startup the code asks SQLite which columns exist and adds the missing one:
Bigger projects use a migration tool (Alembic for SQLAlchemy) that keeps numbered, ordered migration files; the idea is the same. Rating an answer checks ownership inside the SQL, so one query both authorizes and updates, and a visitor can only rate answers in their own conversations:
PUT rather than POST: setting a rating is idempotent (sending 👎 twice leaves the
same state as once), which is exactly what PUT means. That's also why CORS now allows PUT. Admin routes
(reindex, reading the ratings) share one dependency instead of copy-pasting the token check:
Rate limiting
A public endpoint that calls a free-tier API is an open tap: one script could burn a day's Gemini quota in a minute and the assistant would be down for everyone. So each IP gets 10 chat requests per minute and 150 per day.
The algorithm is a sliding-window log: remember each IP's recent request times; a new request is allowed if fewer than limit of them fall inside the window.
Two subtleties. First, check consults all limiters before recording in any, so a request
refused by the daily limit doesn't use up the per-minute budget (there's a test for exactly that). Second, behind
nginx every request comes from 127.0.0.1, so uvicorn runs with --proxy-headers to take the real IP from
X-Forwarded-For. That header is only trustworthy because the container port is bound to localhost,
where nothing but nginx can reach it. The counters live in memory, so they reset on restart and aren't shared
between processes; with several servers you'd keep them in Redis.
CORS
The site is on aminehajji.dev; the API will be on api.aminehajji.dev, a different
origin. By default browsers don't let a page read responses from another origin (otherwise any site you visit
could read your bank's API with your cookies). The server opts in with CORS headers, but only for the origins
you list:
CORS is a browser rule, not a security wall: curl and scripts ignore it, which is why the rate limit exists too.
Configuration
Every setting is a typed field in one class. pydantic-settings fills it from environment variables
and .env, converting and validating types at startup. A typo like RATE_LIMIT_CHAT_PER_MINUTE=ten
fails immediately with a clear error instead of at 3 a.m.
Secrets (the API key) live only in .env, which .gitignore keeps out of git.
.env.example is the committed template showing what to set.
Answers stream word by word on your laptop, but in production they appear all at once after a few seconds. Most likely cause?
The classic SSE deployment bug. The app streams correctly; something between it and the browser collects the whole thing first.
Why do Whisper and Kokoro run in asyncio.to_thread instead of directly inside the async route?
async helps with waiting (I/O), not with computing. CPU-heavy work goes to threads (or processes) so the loop stays responsive.
Go further
- docsFastAPI tutorial Excellent, short chapters. Read "Dependencies" and "Lifespan Events".
- docsMDN: Using server-sent events The format, precisely.
- docsMDN: CORS
- docsSQLite write-ahead logging Why WAL mode lets readers and a writer coexist.
- docspydantic-settings
- articleCloudflare: how they count requests for rate limiting Sliding windows at scale.