Lesson 5 of 59How backends work
How Backends Work
Follow one request from the browser to a server and database and back, and know what each part does.
Your editor, uv, linters and debugger are ready. Now you need something to point them at. Every app you use has a backend: the program that checks your password, saves your order, and decides what you are allowed to see. Before you write one with FastAPI, you need a clear picture of what a backend actually does with a request, because every bug you will chase later lives somewhere on that path.
What a backend is for
The frontend is the code that runs on the user's device: a web page, a phone app. It draws buttons and reacts to clicks. It cannot be trusted, because the user controls the device and can change anything that runs there.
The backend is the code that runs on a computer you control, called a server. It does the jobs that need trust or shared data:
- Store data that outlives one visit (accounts, posts, orders) in a database.
- Enforce rules: is this password right, does this user own this note, is the cart total correct.
- Talk to other services: send email, charge a card, call an AI model, with secret keys the browser must never see.
- Expose an API: a set of URLs the frontend (or a phone app, or another server) calls to do all of the above.
A backend for a todo app might expose GET /todos to list todos and POST /todos to create one. The frontend never touches the database. It asks the backend, and the backend decides.
The life of a request
Here is what happens when the todo app loads your list. Step through it.
You open the app. The JavaScript in the page decides it needs your todos and prepares GET /todos.
Notice that the server does three distinct jobs in the middle: parse, route, serialize. A web framework like FastAPI exists mostly to do those three for you, so you only write the part in between: the logic.
Put the server's work on one request in order.
- Tap the steps below in the right order.
Processes and ports
A backend is just a process: a running program with its own memory. When you start it, it asks the operating system to listen on a port, a number from 1 to 65535 that says which program on the machine should get incoming connections. An IP address finds the machine; the port finds the program on it.
| Port | Who usually listens there |
|---|---|
| 443 | HTTPS (web servers, load balancers) |
| 80 | Plain HTTP (usually just redirects to 443) |
| 8000 | Python dev servers like Uvicorn, by convention |
| 5432 | PostgreSQL |
| 6379 | Redis |
Only one process can listen on a given port at a time. That is why you sometimes see address already in use when an old server is still running in another terminal.
# Start a FastAPI app on port 8000 (you will do this for real in two lessons)uvicorn app.main:app --port 8000# On macOS or Linux, see which process holds port 8000lsof -i :8000Routing: from a path to a function
Routing means mapping a method and path to the function that should handle it. Most routes have path parameters, parts of the URL that vary, like the 7 in /todos/7. Frameworks write these as /todos/{todo_id}.
Underneath, a router is not magic. It is a list of patterns and a loop. Run this tiny one.
Press Run (⌘ Enter) to see what happens.Try adding a POST /todos route. You have just built the core of what @app.get(...) does in FastAPI. The decorator stores the function; the dispatcher finds it later.
Using the router above, what does this print?
print(dispatch("GET", "/todos/42/comments"))Serialization: objects become text
Your handler works with Python objects: dicts, lists, dates, class instances. HTTP only carries bytes. Serialization is turning objects into a text format (almost always JSON for APIs) and deserialization is the reverse.
JSON only knows strings, numbers, booleans, null, arrays and objects. Anything else needs a rule.
Press Run (⌘ Enter) to see what happens.The first call fails because JSON has no date type. Passing default=str turns the date into "2026-04-15". FastAPI does this for you with its jsonable_encoder, and Pydantic models (a later lesson) give you exact control over the output shape.
Match each piece of backend work to what it does.
Stateless servers
A stateless server keeps nothing about you in its own memory between requests. Every request carries what the server needs to know: who you are (a token in a header) and what you want (method, path, body). Anything that must last goes in the database.
Why bother? Because in production you run many copies of the same server behind a load balancer, and request 1 might hit copy A while request 2 hits copy B. If copy A kept your shopping cart in a Python dict, copy B would show an empty cart. Stateless servers can also crash and restart without losing anything, and you can add copies when traffic grows.
sessions = {} dict in the server process. It works on their laptop. What breaks in production with 4 server processes?Practice
Parse a raw HTTP request
Before any framework can route a request, something has to turn raw text into fields. Write parse_request(raw) that takes the text of an HTTP/1.1 request and returns a dict:
{"method": ..., "path": ..., "query": {...}, "headers": {...}, "body": ...}The format:
GET /todos?done=true&limit=5 HTTP/1.1\r\n
Host: api.example.com\r\n
Accept: application/json\r\n
\r\n
<body, possibly empty>Rules:
- Lines end with
"\r\n". The first empty line separates headers from the body. The body is everything after it (it may itself contain blank lines). - The first line is
METHOD TARGET VERSION. Split the target at?intopathand the query string. querymaps each name to its value, with percent-encoding decoded (oat%20milkbecomes"oat milk").urllib.parse.parse_qslhelps.headerskeys are lowercase; split each header line at the first colon and strip spaces from the value.
Match a route pattern
Routers compare a request path against patterns like /todos/{todo_id}. Write match_route(pattern, path):
- Return a dict of captured path parameters (as strings) if the path matches.
- Return
{}for a match with no parameters. - Return
Noneif it does not match.
match_route("/todos/{todo_id}", "/todos/42") -> {"todo_id": "42"}
match_route("/todos", "/todos") -> {}
match_route("/todos/{todo_id}", "/notes/42") -> NoneRules: a {name} segment matches any one non-empty segment. Other segments must match exactly. The number of segments must be equal. Ignore a trailing slash (/todos/42/ matches like /todos/42).
- backend
- Code on a server you control that stores data, enforces rules and exposes an API.
- port
- A number that tells the OS which listening process should receive a connection, like 8000 or 5432.
- routing
- Mapping a method and path such as
GET /todos/{todo_id}to the function that handles it. - serialization
- Turning Python objects into text (usually JSON) to send over HTTP. Deserialization is the reverse.
- stateless server
- A server that keeps no per-user memory between requests, so any copy can serve any request.