Skip to content

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.

14 min read0/6 questions

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.

Quick check
A shopping site computes the order total in JavaScript in the browser and sends it to the server. What is the problem?
Need a nudge? A hint rules out a wrong answer.

The life of a request

Here is what happens when the todo app loads your list. Step through it.

One request, start to finish
Browser: todo appBrowsertodo appDNS: name to IPDNSname to IPAPI server: Python process :8000API serverPython process :8000Database: PostgreSQL :5432DatabasePostgreSQL :5432lookupHTTPSSQL

You open the app. The JavaScript in the page decides it needs your todos and prepares GET /todos.

1/7

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 it in order5 steps

Put the server's work on one request in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

PortWho usually listens there
443HTTPS (web servers, load balancers)
80Plain HTTP (usually just redirects to 443)
8000Python dev servers like Uvicorn, by convention
5432PostgreSQL
6379Redis

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 :8000
Quick check
Your API and your database run on the same laptop. How does the operating system know which program an incoming connection is for?
Need a nudge? A hint rules out a wrong answer.

Routing: 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.

Pythonrouter.py
routes = [] def route(method, pattern): def register(fn): routes.append((method, pattern.strip("/").split("/"), fn)) return fn return register def dispatch(method, path): parts = path.strip("/").split("/") for m, pattern, fn in routes: if m != method or len(pattern) != len(parts): continue params = {} for p, actual in zip(pattern, parts): if p.startswith("{"): params[p[1:-1]] = actual elif p != actual: break else: return 200, fn(**params) return 404, {"detail": "Not Found"} @route("GET", "/todos")def list_todos(): return [{"id": 1, "title": "Buy milk"}] @route("GET", "/todos/{todo_id}")def get_todo(todo_id): return {"id": int(todo_id), "title": "Buy milk"} print(dispatch("GET", "/todos"))print(dispatch("GET", "/todos/1"))print(dispatch("DELETE", "/todos/1"))
Output
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.

Predict the outputPython

Using the router above, what does this print?

print(dispatch("GET", "/todos/42/comments"))
Need a nudge? Hints walk you through it.

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.

Python
import jsonfrom datetime import date todo = {"id": 1, "title": "File taxes", "due": date(2026, 4, 15), "done": False} try: print(json.dumps(todo))except TypeError as err: print("Error:", err) print(json.dumps(todo, default=str))
Output
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 the pairs0/4 matched

Match each piece of backend work to what it does.

Choose an item, then its match on the other side.

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.

Quick check
A developer stores logged-in users in a global sessions = {} dict in the server process. It works on their laptop. What breaks in production with 4 server processes?
Need a nudge? A hint rules out a wrong answer.

Practice

ChallengeEasy

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 ? into path and the query string.
  • query maps each name to its value, with percent-encoding decoded (oat%20milk becomes "oat milk"). urllib.parse.parse_qsl helps.
  • headers keys are lowercase; split each header line at the first colon and strip spaces from the value.
Python
def parse_request(raw: str) -> dict: # Split head and body at the first blank line, then parse the request line and headers. pass
ChallengeEasy

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 None if 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")   ->  None

Rules: 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).

Python
def match_route(pattern: str, path: str) -> dict | None: # Split both into segments and compare them one by one. pass
Key terms
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.