00.5 How Web Apps Work: Client, Server and Database

FoundationsLesson 5 of 919,714 words7 parts
Module 00 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9

Almost everything you will build as an AI engineer is a web app: a program split between something the user touches (usually a browser) and something you run on a computer somewhere else (usually a server), with data stored in a database. Every LLM provider — OpenAI, Anthropic, Gemini, OpenRouter — is reached through this same machinery: an HTTP request from your code to a server on the internet, answered with JSON. This lesson builds the mental model that makes the rest of the path legible: what a client and a server actually are, what happens between the moment someone types a URL and the moment pixels appear, how state and login survive a protocol that forgets everything between requests, the vocabulary of production architecture, and where an LLM API call sits inside all of it.

You will not write a web framework here, and you will not memorise status codes — lesson 00.6 owns HTTP, REST and JSON in depth, and lesson 00.7 owns SQL. What you get here is the map: enough that when a later lesson says "your backend calls the provider", "the browser streams SSE", or "the job goes on a queue", you know exactly which piece of the machine is being talked about.

What you'll learn

  • The journey a URL takes: DNS lookup, TCP connection, TLS handshake, HTTP request, HTML parsing and rendering — and the failure symptom of each step
  • What IP addresses, ports, domains, localhost, 127.0.0.1 and 0.0.0.0 mean, and why a server "listens"
  • The three tiers — front end, back end, database — and the four families of databases, including where vector databases fit
  • How a stateless protocol still powers login: cookies, sessions, JWTs, API keys, OAuth and the difference between authentication and authorisation
  • Why HTTPS matters, what CORS actually does, and why an API key must never ship to a browser
  • Production vocabulary: monoliths vs services, queues and webhooks, load balancers and CDNs, containers, environments, logs and monitoring, latency, throughput, availability and timeouts — and the eight fallacies of distributed computing
  • Where LLMs fit: the model as "just another API your backend calls", why the browser never talks to the provider directly, why responses take seconds and cost money, and how streaming reaches the page
  • Where code runs in production, how domains and certificates work, and why "it works on my machine" is a bug report waiting to happen
  • How to trace a real request through every layer, twice: a password reset and a question to an AI assistant

What you don't need

  • Any programming experience beyond what Module 01A covers — and even that isn't required; the only code you run is short standard-library Python shown in full
  • An API key, an account, or any paid service. Everything here runs on your own machine or is labelled illustrative
  • Prior knowledge of HTTP. Lesson 00.6 goes deeper on methods, status codes, headers and REST; this lesson stays at the level of "a request goes out, a response comes back"
  • A fast connection or a powerful computer. The heaviest thing you do is open a browser's developer tools

Setup

No API key needed. You need:

  • A terminal and a text editor — set up in lesson 00.1, used daily in lesson 00.2
  • A modern browser (Chrome, Edge, Firefox or Safari — any will do; the DevTools walkthrough in 2.6 names the menus for each)
  • Python 3.11+ for the handful of standard-library snippets — python3 --version should print 3.11 or newer; the outputs in this lesson were produced on Python 3.14
  • The ai-path folder from earlier lessons (~/code/ai-path/), used as the example site in the DevTools exercise — any folder of files works if yours doesn't exist yet

The only command you will definitely run is serving a folder of static files with Python's built-in server, which needs no installation:

bash
cd ~/code/ai-path
python3 -m http.server 8000

Then open http://localhost:8000 in your browser. Press Ctrl+C in the terminal to stop it. (On Windows PowerShell the commands are identical; see 00.1 if Python isn't on your PATH yet.)


What you must be able to do after this lesson#

  • Trace what happens between typing a URL and seeing a page
  • Name the front end, back end and database tiers and what each does
  • Explain how cookies, sessions and tokens give a stateless protocol a login
  • Explain why an API key must never ship to a browser
  • Describe where an LLM call fits in a web app
  • Read a request trace and say where a failure happened

Why this matters for an AI engineer#

You will hear these phrases in every job, every tutorial and every incident review. Each one is a piece of the machinery this lesson builds:

You'll hear... You'll understand it after...
"The request timed out." 4.9 Latency, throughput, availability, timeouts
"It's a 502 from the gateway." / "We got a 429." 1.5 Failure symptoms — and then 00.6 for the full status-code table
"The frontend can't call the LLM API directly." 5.3 Why the browser never calls the provider
"Put the key in a .env / secret manager, never in the client." 3.8 CORS and secrets in the browser
"The model call goes on a queue / background job." 4.3 Synchronous vs asynchronous work
"Stream the answer back over SSE." 5.5 Streaming to the browser — the wire format is 03.3
"It works on my machine." 6.4 Reproducibility
"We deployed to a container / serverless / a PaaS (platform-as-a-service)." 6.1 Where code runs
"The vector store is just another service." 2.5 Databases and 06.5
"Add retries with backoff and a timeout." 4.9 here; the engineering is 01B.9 and 03.8
"Check the trace / the logs / the dashboard." 4.8 Configuration, logs and monitoring and 11A.1

Part 1: The big picture — what happens when you type a URL#

1.1 The cast of characters#

Strip away the jargon and the web is three roles and a wire:

  • A client is whatever initiates the exchange: your browser, a phone app, a Python script, another server's code. The client asks.
  • A server is a program that waits for requests and answers them. "Server" is not a kind of computer — it's a role. The same laptop can be a client when it asks Google for a page and a server when python3 -m http.server answers localhost:8000. (Julia Evans has a whole post on why "server" is hard to define; it's the right intuition: a server is software that listens and responds.)
  • The network is everything between them: your Wi-Fi, your ISP, routers, cables, and on the public internet, other people's networks.
  • A database (or any other backing service) is where the server keeps things that must survive a restart: user accounts, orders, tickets — and, in AI products, conversation history, embeddings and usage records.
flowchart LR
    subgraph client_side ["The client: whatever the person is holding"]
        B["Browser or mobile app<br/>(HTML, CSS, JavaScript)"]
    end
    subgraph net ["The internet: a network of networks"]
        direction TB
        DNS["DNS lookup:<br/>name to IP address"]
        N1["Routing, firewalls,<br/>TLS encryption"]
    end
    subgraph server_side ["The server: a program that listens"]
        S["Web server + app code<br/>(routing, business logic, auth)"]
    end
    subgraph data_side ["State and services"]
        DB[("Database")]
        EXT["Other services:<br/>payments, email, LLM APIs"]
    end
    B -->|"1. type URL or tap button"| DNS
    DNS --> N1
    N1 -->|"2. HTTP request"| S
    S -->|"3. queries / calls"| DB
    S -->|"3. calls"| EXT
    DB --> S
    EXT --> S
    S -->|"4. HTTP response"| N1
    N1 --> B

Every web app you will ever debug is some arrangement of these four boxes. The skill this lesson builds is being able to look at a symptom — "the page won't load", "the answer never arrived", "the button does nothing" — and name which box and which arrow is failing.

1.2 Addresses: IP addresses, ports and listening#

Computers on a network find each other by IP address (Internet Protocol address) — a number like 203.0.113.10 (IPv4) or 2606:4700:4700::1111 (IPv6). IPv4 gives every device a 32-bit number written as four octets; IPv6 uses 128 bits written in hex groups. You don't need to memorise either format — you need to know three ranges:

Range / address What it is
127.0.0.1 (and ::1) Loopback: "this computer itself". A request to 127.0.0.1 never leaves your machine.
10.x.x.x, 172.16–31.x.x, 192.168.x.x, 169.254.x.x Private addresses: used inside homes, offices and cloud networks. Your laptop's Wi-Fi address is one of these; the internet can't route to it directly — home and office networks hide these ranges behind NAT (Network Address Translation: many private devices share one public address).
Everything else (e.g. 8.8.8.8) Public addresses: reachable across the internet.

Python's standard library can tell you which is which:

python
# ip_kinds.py — run with: python3 ip_kinds.py
import ipaddress

for ip in ["127.0.0.1", "::1", "192.168.1.20", "10.0.0.5", "8.8.8.8", "203.0.113.9"]:
    a = ipaddress.ip_address(ip)
    kind = ("loopback" if a.is_loopback
            else "private" if a.is_private
            else "global" if a.is_global
            else "reserved/documentation")
    print(f"{ip:16} {kind}")
Output6 lines
127.0.0.1        loopback
::1              loopback
192.168.1.20     private
10.0.0.5         private
8.8.8.8          global
203.0.113.9      private

An IP address alone isn't enough to find a service, because one computer runs many programs at once. That's what a port is for: a 16-bit number — 1–65535 for connecting to a service; port 0 is special and means "pick any free port" when binding — that says which program on this machine. The convention is IP:port, so 203.0.113.10:443 means "the program listening on port 443 of that machine". Some ports are well-known — everyone agrees what they mean:

Port Service Notes
22 SSH remote login
53 DNS name lookups (mostly UDP, TCP for big answers)
80 HTTP plain web traffic
443 HTTPS web traffic inside TLS
3306 MySQL database
5432 PostgreSQL database
6379 Redis in-memory cache / key-value store
27017 MongoDB document database
8000, 8080, 3000, 5173 development whatever you or a framework picked — not standard, just popular choices

When a server program starts, it binds to an address and port and listens — it parks itself waiting for connections. python3 -m http.server 8000 binds all interfaces — on modern Python (3.8+) that shows up as ::, the dual-stack wildcard that also accepts IPv4 connections (0.0.0.0 is the IPv4-only spelling of the same idea; check with lsof -i :8000 and you'll see TCP *:8000). Either way it means "every network interface this machine has", so both localhost and your LAN IP can reach it. Binding only 127.0.0.1:8000 would mean "only this machine can connect" — which is what you want for a dev server that has no authentication. 0.0.0.0/:: is not an address you connect to; it's the "all interfaces" wildcard. (Technically 0.0.0.0 is "this host, unspecified address" — the listening socket accepts on every interface.)

localhost itself is a name, not an address: it usually resolves to 127.0.0.1 but can resolve to ::1 (IPv6 loopback) instead, depending on the OS and resolver configuration — so a server bound to only one loopback family can refuse the other. That's the classic "works on 127.0.0.1:8000, fails on localhost:8000" bug; 7.4 has it in the table.

IPv6 adds one more practical wrinkle: the two families have separate port spaces. A process listening on [::1]:8000 does not stop another binding 127.0.0.1:8000, and vice versa — so "address already in use" can mean the other family holds the port. When a bind fails mysteriously, lsof -i :8000 (or ss -tlnp on Linux) shows which address family each listener is actually on.

1.3 Names instead of numbers: DNS and domains#

Nobody memorises 203.0.113.10. Humans use domain names like api.openai.com, and a global directory called DNS (Domain Name System) translates names to addresses. DNS is itself a client-server protocol: your machine asks a resolver (usually run by your ISP, your router, or a public service like 8.8.8.8), which may ask other servers, which may ask the domain's authoritative nameservers, until an answer — an A record for IPv4, AAAA for IPv6 — comes back.

Three details worth keeping:

  • Caching everywhere. Every resolver caches answers for the record's TTL (time to live, in seconds). When people say "DNS propagation takes up to 48 hours", they mean "cached copies haven't expired yet" — the authoritative record changes instantly, the world's caches drain at their own pace. Julia Evans' post DNS "propagation" is actually caches expiring is the canonical explanation.
  • It's a lookup, not routing. DNS only answers "what IP is this name?". After you have the IP, completely different machinery (TCP/IP routing) carries the actual traffic.
  • You can skip it. Typing http://203.0.113.10/ in the browser works — DNS is a convenience layer for humans, not a requirement of the web.

Names have structure: api.openai.com is a subdomain of openai.com, which is a second-level domain under the .com top-level domain (TLD). When you register openai.com you control everything to its left — that's how api., status., platform. all belong to the same owner. (The .com TLD itself is run by a registry; the hierarchy is delegated, which is why you can't register com.)

1.4 From keystroke to pixels: the five acts#

Here is the whole journey, at the level you need. Each act can fail, and each failure has a signature symptom — that's why 1.5 matters.

sequenceDiagram
    autonumber
    participant U as You
    participant BR as Browser
    participant DNS as DNS resolver
    participant SRV as Web server
    participant DB as Database

    U->>BR: types example.com and presses Enter
    BR->>BR: parses the URL, checks its caches
    BR->>DNS: "what is the IP for example.com?"
    DNS-->>BR: "93.184.216.34"
    BR->>SRV: TCP handshake (SYN, SYN-ACK, ACK)
    BR->>SRV: TLS handshake (only for HTTPS)
    BR->>SRV: GET / HTTP/1.1
    SRV->>DB: SELECT page content
    DB-->>SRV: rows
    SRV-->>BR: 200 OK + HTML + headers
    BR->>BR: parses HTML, fetches CSS/JS/images
    BR-->>U: paints the page

Act 1 — DNS. The browser (or OS) resolves the hostname to an IP. Usually instant because of caches; on a cold lookup it can take tens to hundreds of milliseconds, and on a dead resolver it fails with "site can't be reached" / DNS_PROBE_FINISHED_NXDOMAIN-style errors. Your own machine's /etc/hosts file (Windows: C:\Windows\System32\drivers\etc\hosts) can override DNS for one name — the classic dev trick for pointing mysite.test at 127.0.0.1.

Act 2 — TCP. The browser opens a TCP connection to IP:port: a three-way handshake — SYN, SYN-ACK, ACK — one round trip to establish. TCP gives you a reliable, ordered byte stream: packets may arrive out of order or be lost, and TCP reorders and retransmits silently. If the host is reachable but nothing listens on the port, you get connection refused immediately; if a firewall drops the packets, you wait for a timeout.

Act 3 — TLS (HTTPS only). For https:// URLs the browser and server perform a TLS (Transport Layer Security) handshake: they agree on a TLS version and cipher suite, the server proves its identity with a certificate signed by a trusted certificate authority (CA), and they derive shared session keys. After this, everything on the connection is encrypted — an eavesdropper sees ciphertext and metadata (destination IP, timing, roughly how much data), not the request contents. Certificates are what the padlock means; they say "this server proved it controls this domain", not "this site is honest". (Chrome's "Always Use Secure Connections" mode tries HTTPS first and asks before falling back to plain HTTP on public sites; Google's announcement made it the default in Chrome 154, scheduled for October 2026 — see Further resources.)

Act 4 — HTTP. The browser sends an HTTP (HyperText Transfer Protocol) request — a text message: a request line (GET /path HTTP/1.1), headers (Host, User-Agent, Accept, and for logged-in sites Cookie), a blank line, and optionally a body. The server runs your application code, which typically queries a database, calls other services, and assembles a response: a status line (HTTP/1.1 200 OK), headers (Content-Type, Set-Cookie, Cache-Control…), and a body — usually HTML (HyperText Markup Language) for a page, or JSON (JavaScript Object Notation) for an API. All of this anatomy is 00.6's subject; here you only need "request out, response back".

Act 5 — Render. The browser parses the HTML into the DOM (Document Object Model — a tree of the page's elements), fetches the CSS and JavaScript it references (each its own HTTP request, usually many in parallel), applies styles, runs scripts, and paints pixels. Modern pages fire dozens of requests; the page "loads" progressively — HTML first, then styling, then interactivity.

1.5 When each step fails#

This table is the diagnostic heart of the lesson. Match the symptom to the act and you've found your culprit:

Symptom Failing act Typical cause
"This site can't be reached" / DNS_PROBE_… / NXDOMAIN 1 — DNS Wrong name, no such domain, dead resolver, captive portal, typo in the URL
"Connection refused" / ERR_CONNECTION_REFUSED 2 — TCP Nothing listening on that port; server crashed; wrong port (:3000 vs :8000)
Long hang, then "timed out" / ETIMEDOUT 2 — TCP Firewall or security group silently dropping packets; host down; wrong IP
"Your connection is not private" / certificate error 3 — TLS Expired or wrong certificate, system clock wrong, captive portal, or an actual man-in-the-middle (MITM) attack
404 Not Found 4 — HTTP Server is fine; the path doesn't exist. Most common "bug" on the web
500 Internal Server Error 4 — HTTP The server is the app and it crashed — check its logs
502 Bad Gateway / 503 Service Unavailable 4 — HTTP A proxy/gateway couldn't reach the app behind it — often deploys, overload, or a crashed instance
429 Too Many Requests 4 — HTTP You hit a rate limit — slow down and retry later (03.8 is the deep treatment)
Blank page / unstyled page / dead buttons 5 — Render JS error, blocked script, failed subresource — open DevTools
Page loads but data is stale/wrong 5 or 4 A cache served an old copy — browser cache, CDN, or server-side cache

Part 2: Front end, back end, database#

2.1 The three tiers#

Strip a web app to its skeleton and you get three tiers, each with one job:

flowchart TB
    subgraph tier1 ["Tier 1: the front end (runs in the browser)"]
        FE["HTML: structure<br/>CSS: appearance<br/>JavaScript: behaviour"]
    end
    subgraph tier2 ["Tier 2: the back end (runs on the server)"]
        RT["Routing: which code handles this URL"]
        BL["Business logic: the rules of the product"]
        AU["AuthN/AuthZ: who is this, what may they do"]
        VAL["Validation: is this input sane"]
    end
    subgraph tier3 ["Tier 3: data and services"]
        DB[("Database: durable state")]
        EXT["External APIs: payments, email, LLMs"]
        Q["Queues and caches: async work"]
    end
    FE -->|"HTTP requests (JSON or forms)"| RT
    RT --> BL
    BL --> AU
    BL --> VAL
    BL --> DB
    BL --> EXT
    BL --> Q
  • Front end — everything the user's browser downloads and runs: the page's structure, its styling, and the JavaScript that makes it interactive. It can display data and ask for data; it cannot be trusted with secrets or rules.
  • Back end — the program on the server that receives requests, decides what to do, talks to the database and other services, and sends back a response. This is where the product's rules live: "only admins can refund", "a ticket can't be closed without a resolution note", "this prompt costs money so check the quota first".
  • Database — durable storage: survives restarts, shared by all users, and the only place state lives that both sides can trust.

The front end and back end talk only through HTTP requests and responses — that boundary is the whole point of the architecture. The browser is untrusted territory: anyone can open DevTools and change what it sends. Every security decision lives behind the boundary, on the server.

2.2 HTML, CSS and JavaScript — what each does#

Three languages, three jobs, one page:

Language Job Analogy Example
HTML Structure and content: headings, paragraphs, buttons, forms, links The skeleton / the document's words <h1>Support tickets</h1><button>New ticket</button>
CSS Appearance: colours, layout, fonts, responsiveness The interior design body { font-family: sans-serif; } .urgent { border-left: 3px solid red; }
JavaScript Behaviour: what happens when you click, fetch data, update the page The electrician and the puppeteer fetch('/api/tickets').then(r => r.json())

A browser renders a page by combining all three. You can see the raw materials of any page: right-click → View Page Source shows the HTML the server sent; DevTools' Elements panel shows the live DOM after JavaScript has mutated it. The difference matters: view-source shows what arrived over the wire; the Elements panel shows what the page looks like now.

You do not need to write front-end code in this path — but you must read it, because debugging a web app means reading what the browser is doing. Three JavaScript ideas cover 90% of what you'll meet:

  • The DOM: the live tree of elements JavaScript can query and mutate (document.querySelector('.urgent')).
  • fetch(): the browser's built-in way to make an HTTP request and get a response back — the front end's only channel to your backend.
  • Event handlers: button.addEventListener('click', ...) — "when this happens, run this". Almost every interactive bug is an event handler that didn't fire, fired twice, or fired with the wrong data.

2.3 Static sites vs server-rendered vs single-page apps#

"A website" is not one architecture. Three broad patterns, and modern apps mix them:

Pattern How it works Good for Cost
Static site Pre-built HTML/CSS/JS files served as-is; no per-request code Docs, blogs, marketing pages, your python3 -m http.server demo Cheapest and fastest — a CDN can serve it from a datacentre next to the user
Server-rendered (SSR / multi-page) Server builds the HTML fresh for each request (template + data), sends a complete page; JS enhances it Content sites, dashboards, forms, anything SEO-sensitive One server does the work per request; simpler mental model
Single-page app (SPA) Server sends a nearly-empty HTML shell + a big JavaScript bundle; the app renders everything client-side and calls JSON APIs for data Highly interactive tools: editors, chat UIs, admin dashboards Fast navigation after first load; harder SEO, more client-side complexity, the "blank page until JS runs" failure mode

The honest summary: SPAs moved complexity from the server to the client. A page that used to be 12 server-rendered navigations becomes one app that fetches JSON. The trade-offs — initial bundle size, client-side state, harder caching of HTML — are why frameworks (React, Vue, Angular, Svelte, and meta-frameworks like Next.js and SvelteKit that do both) exist, and why "is it static, SSR or SPA?" is usually "all three, per route".

2.4 What a backend actually does#

"Backend" sounds like one thing; it's a list of responsibilities, and a real service does all of them:

  1. Routing — map POST /api/tickets to the function that creates a ticket. Frameworks (Express, FastAPI, Django, Rails, Spring…) make this declarative; the concept is just a lookup table from (method, path) to code.
  2. Validation — is this input the right shape? Is email an email, quantity a positive integer, is this field even allowed to be set by this user? Reject early, with a clear error. Never trust the client.
  3. Authentication — who is calling? (Login, sessions, tokens — all of Part 3.)
  4. Authorisation — what may they do? A logged-in user still can't refund orders or read other tenants' data.
  5. Business logic — the product's actual rules: price calculation, state machines (a ticket goes open → pending → resolved), inventory checks, the point where "the code" becomes "the product".
  6. Persistence — read and write the database, inside transactions when several writes must succeed or fail together (00.7 covers transactions properly).
  7. Integration — call other services: payment processors, email providers, LLM APIs, vector databases. Every one of these calls can be slow, fail, or cost money — which is why Part 4 exists.
  8. Response shaping — serialise results to JSON (or HTML), set status codes and headers, handle errors consistently.

A useful mental filter for any backend bug: which of these eight jobs is failing? "Users can create tickets but not close them" is business logic or authorisation. "The create call returns 422" is validation. "Everything 500s after the deploy" is integration or persistence.

2.5 Databases: four families#

A database is software that stores data durably and answers questions about it. Four families cover almost everything you'll meet:

Family Model Examples Best at Watch out for
Relational Tables of rows and columns, linked by keys; queried with SQL (Structured Query Language) PostgreSQL, MySQL, SQLite Structured business data: users, orders, tickets; joins and transactions Schema changes need migrations; not built for fuzzy similarity search
Document Collections of JSON-like documents; each record can have different fields MongoDB, DynamoDB, Firestore, Couchbase Flexible schemas, nested data, rapid iteration Joins and multi-document transactions are weaker; consistency models vary
Key-value A giant hash map: key → blob Redis, Memcached, DynamoDB (also document-ish), etcd Caching, sessions, queues, rate limits, leader election — microsecond reads No querying "inside" the value; RAM costs money
Vector Stores embeddings (lists of numbers) and finds nearest neighbours pgvector, Qdrant, Pinecone, Chroma, FAISS (library) Semantic search: "find documents similar to this question" Different consistency/scale trade-offs; the index is approximate, not exact

The vector family deserves a paragraph because it's the one AI engineers meet first and understand worst. A vector database stores each chunk of text as an embedding — a list of floats where similar meanings sit near each other — plus metadata (source, date, tenant). A query embeds the user's question and asks "which stored vectors are closest?" — that's how RAG retrieves relevant passages. Lesson 06.4 explains the indexes (HNSW, IVF) that make "closest of a million" fast, and 06.5 compares the products. The key mental note for this lesson: a vector database is a service your backend calls over the network, exactly like your Postgres or your LLM provider — it is not something the browser talks to.

Two adjacent pieces of storage infrastructure, concept-level for now:

  • Caches keep hot data close to the reader: the browser caches static files, a CDN caches pages near users, Redis caches query results or session lookups, and LLM providers cache prompt prefixes (you'll meet "prompt caching" in 03.7). Every cache trades freshness for speed — the art is knowing what may be stale and for how long.
  • Queues decouple "do this eventually" from "do this now". Instead of making the user wait 30 seconds for a PDF to generate, the server drops a job on a queue (Redis, RabbitMQ, SQS, Kafka…) and a worker process picks it up later; the user gets "we'll email you". Webhooks are the push-side cousin (4.4).

2.6 Watching a request: the Network tab#

Theory is cheap; the fastest way to make this real is to watch your own machine serve a page. With python3 -m http.server 8000 running in ~/code/ai-path (from the Setup section above):

  1. Open http://localhost:8000 in your browser.
  2. Open DevTools: F12 or Ctrl+Shift+I (macOS: Cmd+Opt+I), then click the Network tab.
  3. Check Disable cache (or keep the default; either is fine for this exercise), then reload with Cmd+R / Ctrl+R.

Those clicks use Chrome/Edge's names — every major browser has the same panels under different labels:

  • Firefox: Ctrl+Shift+E (macOS: Cmd+Opt+E) opens the Network Monitor directly — it records at the bottom of the window while it's open. Its throttling presets have different names — GPRS, Regular/Good 2G, Regular/Good 3G, Regular 4G/LTE, DSL, Wi-Fi, Offline — instead of Chrome's Slow/Fast 3G/4G.
  • Safari: DevTools are switched off until you enable them — Safari → Settings → Advanced → tick Show features for web developers. Then Cmd+Opt+I (or Develop → Show Web Inspector) opens Web Inspector, whose Network tab works the same way (it has a Disable Caches option too). Release Safari has no built-in throttling presets — Apple's Network Link Conditioner (part of Xcode's additional tools) slows the whole Mac instead.
  • Edge is Chromium-based: the Chrome instructions apply unchanged.

You'll see a waterfall of requests — one per file the page needs. Click the first one (usually the document, localhost:8000/). The detail pane shows you the anatomy from 1.4 made concrete:

  • Headers → General: the URL, the method (GET), the status (200 OK), the remote address (127.0.0.1:8000), and timing breakdowns.
  • Headers → Response Headers: what the server said about the response — Content-type: text/html, Last-Modified, Content-Length. This is where Set-Cookie, Cache-Control and Content-Security-Policy appear on real sites.
  • Response (or Preview): the actual bytes — for a document, the HTML source.
  • Timing: DNS lookup, TCP handshake, TLS (absent here — localhost is plain HTTP), "Waiting for server" (TTFB — time to first byte) and "Content download". On localhost everything is sub-millisecond; on a real site these numbers are where latency lives (4.9).

Try it — dissect a URL with Python. A URL (Uniform Resource Locator) is the complete address — scheme, host, port, path, query, fragment — and the standard library's urllib.parse splits one into its parts, the same job the browser does before Act 1:

python
# url_parts.py — run with: python3 url_parts.py
from urllib.parse import urlsplit, parse_qs

url = "https://api.openai.com:443/v1/responses?model=gpt-6-luna&stream=true"
u = urlsplit(url)

print("full URL :", url)
print("scheme   :", u.scheme)
print("hostname :", u.hostname)
print("port     :", u.port)
print("path     :", u.path)
print("query    :", u.query)
print("username :", u.username)   # None unless user:pass@ is in the URL
print("fragment :", u.fragment)
print()
print("parsed query:", parse_qs(u.query))
Output10 lines
full URL : https://api.openai.com:443/v1/responses?model=gpt-6-luna&stream=true
scheme   : https
hostname : api.openai.com
port     : 443
path     : /v1/responses
query    : model=gpt-6-luna&stream=true
username : None
fragment : 

parsed query: {'model': ['gpt-6-luna'], 'stream': ['true']}

Read it as the browser would: https selects TLS, api.openai.com is what DNS resolves, :443 is the port — the scheme implies it (https means port 443, http means 80), so you can omit it from the URL and the connection still lands there; but u.port itself returns None when no port is written, because urlsplit reports only what the URL says. Try deleting :443 and re-running to see the difference. /v1/responses is the path, and the query string carries parameters. parse_qs turns model=gpt-6-luna&stream=true into a dict — this is exactly how a backend reads ?page=2&filter=open from a URL. 00.6 formalises URLs (percent-encoding, fragments, query strings) and REST's use of them.

2.7 Caches and queues — the two invisible tiers#

Two more boxes appear in every serious architecture, worth naming now:

  • Cache: a fast layer that stores copies of expensive-to-produce data — rendered pages, query results, "the embedding for this document chunk". Browser cache, CDN edge cache, Redis, and provider-side prompt caches are all the same idea at different distances from the user. The engineering question is always the same: what may be stale, for how long, and how does a change invalidate it?
  • Queue / message broker: a durable to-do list between services. Producers add jobs; workers consume them at their own pace. This is how "send the welcome email", "generate the PDF", "run the nightly eval" happen without making any user wait. Queues also absorb bursts: if 10,000 users hit "ask the assistant" at once, the queue smooths the spike into a steady stream of LLM calls — at the cost of latency (the answer arrives when a worker gets to it) and the need for idempotency (a retried job must not charge the card twice — 03.8 covers this for LLM calls).

Part 3: State, sessions and authentication#

3.1 HTTP is stateless — and why that matters#

The single most important fact about the web's plumbing: HTTP has no memory. Every request is an independent message. The server doesn't know — and can't know — that request #47 came from the same person as request #46. No "current user", no "shopping cart so far", no "you are on step 3 of 5". Each request arrives cold: method, URL, headers, body. That's called statelessness, and it's a deliberate design choice — it lets any server handle any request, which is what makes load balancing and retries possible (4.5).

But applications need state: who's logged in, what's in the cart, which tickets belong to you. Since HTTP won't carry it, the application layer invents ways to smuggle identity through stateless requests. Everything in this part is one of those inventions.

3.2 Cookies: the browser's filing cabinet#

A cookie is a small key-value pair that a server asks the browser to store via a Set-Cookie response header, and that the browser then attaches to every later request to the same site in a Cookie header. The server gets its memory back — one request at a time.

text
# What the server sends in a response:
Set-Cookie: session=8f3k2-sessionid; Path=/; HttpOnly; Secure; SameSite=Lax

# What the browser sends on the next request to that site:
Cookie: session=8f3k2-sessionid; theme=dark; cart=3

A server reads that header with a few lines of standard-library Python:

python
# read_cookies.py — run with: python3 read_cookies.py
from http.cookies import SimpleCookie

# What a browser sends back on the next request to the same site:
header = "session=8f3k2-sessionid; theme=dark; cart=3"

jar = SimpleCookie()
jar.load(header)
for name, morsel in jar.items():
    print(f"{name!r:12} -> {morsel.value!r}")
print("session value:", jar["session"].value)
Output4 lines
'session'    -> '8f3k2-sessionid'
'theme'      -> 'dark'
'cart'       -> '3'
session value: 8f3k2-sessionid

Cookie attributes are where the security lives — they are set by the server, not chosen by the page:

Attribute Meaning
Path=/ Send this cookie only to URLs under / (scopes it within the site)
Domain=example.com Which host(s) may receive it — omit to pin it to the exact host that set it
Secure Send it only over HTTPS — never over plain HTTP
HttpOnly JavaScript cannot read it — blocks the classic "steal the session cookie with cross-site scripting (XSS)" attack
SameSite=Lax/Strict/None Controls cross-site sending: Lax/Strict stop other sites' requests from carrying it (cross-site request forgery — CSRF — defence); None requires Secure
Max-Age / Expires When it dies — session cookies (no expiry) die when the browser closes

CSRF (cross-site request forgery) is the attack SameSite exists to stop — worth understanding because it explains why cookies are dangerous. The browser attaches cookies to requests automatically — no JavaScript involved — so a malicious page on evil.example can make your browser fire POST https://yourapp.example/transfer, and it arrives carrying the user's session cookie, indistinguishable from a real one. SameSite=Lax/Strict tells the browser to withhold the cookie on cross-site requests (Lax still allows top-level navigations, like following a link). Where cookies must flow cross-site — or where SameSite can't help — apps use a CSRF token: a per-session secret embedded in forms or headers that the server verifies; the attacker's page can't read it (that's what CORS blocks — 3.8) so it can't forge it. Modern frameworks generate and check these automatically. Awareness-level takeaway: never ship a cookie-authenticated, state-changing endpoint without one of these two defences; Module 12 covers the security treatment properly.

3.3 Sessions: giving the stateless protocol a memory#

A cookie could hold anything — including "user_id=42, role=admin". Never do that: the browser is user-controlled, so anything in a cookie can be edited. Instead, the standard pattern is the session:

  1. User logs in; the server generates a long random session ID (128+ bits of entropy — guessability is the whole security model).
  2. The server stores session_id → {user_id, role, expires_at} in a fast store — Redis, a database table, or memory.
  3. The server sends Set-Cookie: session=<id> to the browser.
  4. Every later request carries the cookie; the server looks the ID up in the store and knows exactly who this is — and can revoke it instantly by deleting the row.

The cookie now holds a reference, not the data. A stolen session ID is absolutely usable — holding it is being you until the session expires or is revoked, which is why HttpOnly, Secure and a short expiry matter. What it can't do is be forged: an attacker can't mint a session for user_id=1 because they can't predict the random IDs.

Try it — cookies the way a server reads them is the read_cookies.py snippet in 3.2: SimpleCookie parses the Cookie header into name/value pairs. The inverse — building a Set-Cookie header — is just string formatting; frameworks do it for you.

3.4 Tokens: API keys, bearer tokens and JWTs#

Not every client is a browser. Scripts, mobile apps and — importantly for you — your backend calling an LLM provider authenticate differently:

  • API key: a long secret string issued by the service (sk-... for OpenAI-style keys). Sent in a header on every request. Simple, powerful, and bearer-equivalent: whoever holds it can spend your money. 03.1 covers provider keys in depth; the hygiene rules (03.1 §3.4) apply from day one — .env file, .gitignore, never in source.
  • Bearer token: the general mechanism — Authorization: Bearer <token> means "the holder of this token is authenticated". API keys are one kind of bearer token; OAuth access tokens and JWTs are others.
  • Basic auth: Authorization: Basic base64(user:pass) — the oldest scheme. Base64 is encoding, not encryption: anyone can decode it. It survives only because HTTPS encrypts the channel and it's still used for simple internal tools. Here's the encoding, for recognition:
python
# basic_auth.py — run with: python3 basic_auth.py
import base64

# Browsers/clients base64-encode "username:password" — NOT encryption.
creds = base64.b64encode(b"learner:correct-horse-battery").decode()
print("Authorization: Basic", creds)
print("decoded back  :", base64.b64decode(creds).decode())
Output2 lines
Authorization: Basic bGVhcm5lcjpjb3JyZWN0LWhvcnNlLWJhdHRlcnk=
decoded back  : learner:correct-horse-battery
  • JWT (JSON Web Token): a signed, self-contained token with three base64url parts — header.payload.signature. The payload is plain JSON (readable by anyone who has the token — JWTs are signed, not encrypted):
python
# jwt_decode.py — run with: python3 jwt_decode.py
# A JWT is just three base64url-encoded JSON chunks.
# (Signature chunk shown as a placeholder; real JWTs sign it.)
import base64, json

def b64url_encode(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()

header  = b64url_encode(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
payload = b64url_encode(json.dumps({
    "sub": "user-42", "name": "Asha", "exp": 1735689600,
    "iss": "https://auth.example.com",
}).encode())
token = f"{header}.{payload}.c2lnbmF0dXJlLXBsYWNlaG9sZGVy"

print("token:", token)
print()
for label, part in zip(["header", "payload"], token.split(".")[:2]):
    padded = part + "=" * (-len(part) % 4)          # base64 needs padding back
    print(label, "->", json.dumps(json.loads(base64.urlsafe_b64decode(padded)), indent=2))
Output12 lines
token: eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiOiAidXNlci00MiIsICJuYW1lIjogIkFzaGEiLCAiZXhwIjogMTczNTY4OTYwMCwgImlzcyI6ICJodHRwczovL2F1dGguZXhhbXBsZS5jb20ifQ.c2lnbmF0dXJlLXBsYWNlaG9sZGVy

header -> {
  "alg": "HS256",
  "typ": "JWT"
}
payload -> {
  "sub": "user-42",
  "name": "Asha",
  "exp": 1735689600,
  "iss": "https://auth.example.com"
}

The server verifies the signature with a shared secret (HS256) or a public key (RS256/ES256), then trusts the claims: sub = subject (user id), exp = expiry, iss = issuer. Because the token is self-contained, any of your server instances can verify it without a session lookup — the statelessness advantage. The cost: you can't revoke a JWT until it expires (short expiry + refresh tokens is the standard mitigation), and you must never put secrets in the payload — it's readable by its holder.

3.5 "Log in with Google": OAuth in one page#

When you click "Sign in with Google/GitHub", you don't hand your password to the app — you authorize it. OAuth 2.0 (RFC 6749; OAuth 2.1 is the modern consolidation, still stabilising as of November 2026) is the delegation protocol:

  1. Your app redirects the browser to the provider's login page with a client_id and a redirect_uri.
  2. The user authenticates with the provider and consents to the requested scopes ("read your email", "post on your behalf").
  3. The provider redirects back to your redirect_uri with a short-lived authorisation code.
  4. Your server exchanges that code (plus a client_secret) directly with the provider for an access token — and usually a refresh token for renewal.
  5. Your server calls the provider's API with the access token to fetch identity (sub, email, name) or act on the user's behalf.

The crucial design point: the token exchange happens server-to-server. The browser only ever sees the authorisation code, never the client secret or the access token — which is why OAuth secrets live in your backend's environment, not in JavaScript. For single-page apps there's a variant (authorisation code + PKCE — Proof Key for Code Exchange) that achieves the same without a client secret; the browser still never holds provider credentials it shouldn't.

3.6 Authentication vs authorisation#

Two words everyone mixes up, and the mix-up causes real bugs:

  • Authentication (AuthN): who are you? — the login check. Password+salt verify, session lookup, token signature check.
  • Authorisation (AuthZ): what may you do? — the permission check. "User 42 may read ticket 7 but not ticket 8"; "only role=admin may refund"; "this API key may call /v1/responses but not /v1/keys".

Every protected endpoint does both: authenticate the caller, then authorise the specific action — often per-object ("can this user touch this ticket?"), which is where IDOR bugs (insecure direct object reference: guessing /tickets/8 when you own only /tickets/7) come from. When you write or review an endpoint, ask both questions explicitly; "they're logged in" is not an authorisation answer.

3.7 HTTPS: what TLS actually protects#

https:// means the connection is wrapped in TLS (Transport Layer Security; SSL — Secure Sockets Layer — is the dead predecessor whose name stuck). Three properties:

  1. Encryption — eavesdroppers on the network see ciphertext, not your password, your session cookie, or the prompt you sent to an LLM API.
  2. Integrity — tampering in transit is detected (the connection fails loudly rather than silently swapping content).
  3. Authentication of the server — the certificate proves the server controls the domain name you typed (chain of trust back to a CA), which is what stops trivial man-in-the-middle impersonation.

What TLS does not do: it doesn't make the site trustworthy (phishing sites have valid certs — anyone can get one free from Let's Encrypt), it doesn't encrypt DNS lookups (unless DoH/DoT), and it doesn't protect against attacks inside the connection (XSS, injection, leaked keys — those are application problems).

Mechanically: after TCP connects, the TLS handshake negotiates version (TLS 1.3, RFC 8446, is the modern baseline; TLS 1.2 still exists for old clients) and cipher suite, the server sends its certificate, both sides derive session keys, and HTTP flows encrypted inside. Certificates are issued by certificate authorities; free automated ones (Let's Encrypt) renewed every ~90 days are why HTTPS is now universal — Chrome is moving to ask before opening plain-HTTP public sites by default (see Further resources), and browsers mark HTTP as "Not secure". A domain can make the HTTPS-only behaviour permanent for itself with the Strict-Transport-Security (HSTS) response header — browsers then upgrade or refuse plain-HTTP for that domain for the header's lifetime, with no ask-first step.

3.8 CORS and secrets in the browser#

CORS (Cross-Origin Resource Sharing) answers a narrow question: may JavaScript on https://app.example.com read the response from https://api.other.com? Browsers enforce the same-origin policy by default — scripts can only read responses from their own origin (scheme + host + port). For a cross-origin fetch(), the browser sends an Origin header; the server answers with Access-Control-Allow-Origin (and related headers) saying who's permitted. No header → the browser blocks your code from reading the response (the request may still have been sent — important nuance! CORS is a read-gate, not a send-gate).

Two consequences you'll hit constantly:

  • Preflight: "non-simple" requests (custom headers like Authorization, JSON bodies, non-GET/POST methods) trigger an automatic OPTIONS preflight request first. If your API doesn't answer it correctly, the real request never fires — a classic "works in curl, fails in the browser" bug.
  • CORS is not authentication or security. It stops other websites' JavaScript from reading your API through a visitor's browser. It does nothing against curl, mobile apps, or attackers calling your API directly — your API still needs real auth. And never try to "fix" CORS by disabling it server-side; you re-open every website to poke your API through your users' browsers.

This is also the moment to state the rule that governs every AI app you'll build: a provider API key must never ship to the browser. Anything in frontend JavaScript — a key, a "secret" endpoint, business logic — is public: view-source, DevTools, or fetch in the console hands it to anyone. The pattern is always browser → your backend → provider: the key lives in your server's environment (03.1 §3.5 is the full treatment, and 01B.2 covers .env and secret hygiene properly).

3.9 Passwords: hashing, salting and why "encrypted" is the wrong word#

When a user picks a password, you never store it — you store a hash: a one-way function output that can't be reversed but can be recomputed for comparison. Three requirements make it safe:

  • Slow, memory-hard algorithm — Argon2id (first choice), scrypt, bcrypt, or PBKDF2 where FIPS compliance demands it. Fast hashes like plain SHA-256 are useless here: GPUs try billions of guesses per second.
  • Unique salt per password — a random value stored next to the hash, so identical passwords don't produce identical hashes and precomputed rainbow tables die.
  • A work factor — iteration count / memory cost, tuned so verification takes ~hundreds of milliseconds: painful for attackers at scale, invisible to one login.
python
# password_hash.py — run with: python3 password_hash.py
import hashlib

password = b"correct horse battery staple"   # the user's password, as bytes
salt = bytes.fromhex("00112233445566778899aabbccddeeff")  # 16 random bytes, stored next to the hash
iterations = 600_000                          # OWASP's current PBKDF2-HMAC-SHA256 guidance

dk = hashlib.pbkdf2_hmac("sha256", password, salt, iterations)
print("stored hash :", dk.hex())
print("salt (hex)  :", salt.hex())
print("iterations  :", iterations)

# Verifying a login = run the same function with the same salt and compare.
check = hashlib.pbkdf2_hmac("sha256", b"wrong password", salt, iterations)
print("wrong guess matches?", check == dk)
Output4 lines
stored hash : 7c0123695eb46911838d4c16fa259d7280c59060c6031130b8269b624faacd02
salt (hex)  : 00112233445566778899aabbccddeeff
iterations  : 600000
wrong guess matches? False

Verify by recomputing with the stored salt and comparing — hmac.compare_digest in real code for constant-time comparison. OWASP's current guidance (as of November 2026) is Argon2id first, scrypt next, bcrypt for legacy, PBKDF2-HMAC-SHA256 at 600,000+ iterations where FIPS-140 applies. Real systems use libraries (argon2-cffi, bcrypt) rather than stdlib hashlib — this snippet exists so you can see the mechanics, not to ship.


Part 4: Architecture vocabulary#

Deep-dive

Production systems have a vocabulary, and half of it is metaphors that become literal when something breaks. This part is the dictionary — each term defined once, precisely enough to use in a design discussion or an incident review.

4.1 Monolith vs services vs serverless#

Monolith: one deployable program that does everything — routing, business logic, all the integrations. Easy to build, easy to reason about, one codebase, one deploy. Most products start here and should: the complexity of distributed systems is a cost you only pay when the monolith's limits bite (a team that can't ship without coordinating, a component that needs different scaling, a library that must be isolated).

Services / microservices: the monolith split into independently deployed programs that talk over the network (usually HTTP APIs). Each owns its data. You gain independent scaling and team autonomy; you pay in network calls everywhere, distributed debugging, data consistency across services, and operational surface. The honest advice for this path: start monolithic, extract a service only when a specific pressure demands it — "microservices" is a scaling answer, not a correctness answer.

Serverless (Functions-as-a-Service: AWS Lambda, Google Cloud Functions, Cloudflare Workers, Vercel/Netlify functions): you upload functions; the platform runs them per request and bills per invocation/millisecond. No server to manage, scales to zero. The trade-offs: cold starts, execution time limits, vendor-specific APIs, and state must live elsewhere (a database or object store — functions are ephemeral). It's a deployment shape, not a different architecture: your code still receives a request and returns a response.

Shape Deploy unit Scaling Operational burden Choose when
Monolith one app vertical (bigger machine) then horizontal (more copies) low almost everything you're building now
Services several apps per-service high teams/services genuinely diverge in scale or ownership
Serverless functions automatic, to zero lowest sporadic traffic, glue code, event handlers, small APIs

4.2 APIs as contracts#

An API (Application Programming Interface) is a contract: "send me a request of this shape, I'll do this, and I'll answer in that shape". Every boundary in a system is an API — your backend's HTTP API, the LLM provider's API, the database's query language, a queue's message format. Contracts matter because they're the only thing two independently-evolving pieces can rely on:

  • Explicitness: a good API says what it accepts, what it returns, what errors exist — in docs (OpenAPI specs, provider docs) or code (type signatures).
  • Stability vs evolution: once others depend on your API, changes break them. Versioning (/v1/), deprecation windows and additive-only changes are how contracts stay alive. LLM providers version their APIs and deprecate models; 00.8 teaches reading those changelogs.
  • The contract is the test surface: you can test your backend through its API without touching internals — the same property that makes provider APIs mockable in tests (03.10, 01B.8).

A subtlety worth internalising: an API contract includes its failure behaviour — timeouts, rate limits, partial results, idempotency. "What does this API do when it can't fulfil the request?" is half the contract, and the half people forget until production.

4.3 Synchronous vs asynchronous work: jobs and queues#

Synchronous: the caller waits for the answer before continuing. HTTP request/response is synchronous — your fetch() returns a promise that resolves when the server replies, and the caller awaits it while the rest of the program keeps running. Synchronous is simple and right when the work is fast and the caller needs the result now.

Asynchronous: the caller hands off work and moves on; the result arrives later through a different channel. Two flavours:

  • Async within a process: non-blocking I/O — while one request waits on the database, the server handles another. This is what async/await in Python (01B.3) and Node's event loop are for: thousands of concurrent slow operations on one machine. Crucially, async ≠ parallel: one thread juggles many waits.
  • Async across processes: queues and background jobs. The request returns 202 Accepted ("got it, working on it") immediately; a worker does the slow part — sends the email, generates the report, calls the LLM for the nightly digest — and notifies the user later (email, websocket, polling, webhook). Queues decouple arrival rate from processing rate and survive restarts; the cost is complexity (ordering, retries, idempotency, dead-letter queues for jobs that keep failing).

The decision rule: if the user needs the result to continue, do it synchronously; if they need acknowledgement, do it asynchronously. "Generate my monthly report" → queue. "What's the weather in Paris?" → synchronous API call.

4.4 Webhooks and callbacks#

A webhook is an API call you don't initiate: the provider calls your endpoint when something happens. Stripe charges a card → POSTs to https://yourapp.com/webhooks/stripe. GitHub gets a push → POSTs to your CI. An LLM provider finishes a long-running batch job → notifies your callback URL. The pattern inverts the usual direction: instead of polling "is it done yet?", you expose an endpoint and wait to be called.

Engineering consequences:

  • Your endpoint must be publicly reachable over HTTPS — which is why webhooks push you toward deployed infrastructure (Part 6).
  • Verify the sender: webhook endpoints are public URLs; anyone can POST to them. Providers sign payloads (Stripe's Stripe-Signature, GitHub's X-Hub-Signature-256); you verify the signature before trusting the body. An unverified webhook endpoint is an unauthenticated write API.
  • Handle duplicates and retries: providers retry failed deliveries, so your handler must be idempotent — processing the same event twice must not double-charge or double-email. 03.8 treats idempotency for LLM calls; the principle is universal.
  • Acknowledge fast: return 2xx quickly and do the slow work asynchronously, or the provider marks the delivery failed and retries — possibly while you're still processing.

4.5 Scaling out: load balancers, CDNs and replicas#

One server has finite CPU, memory and network. Scaling is adding capacity; the two axes:

  • Vertical: a bigger machine. Simple, has a ceiling, and bigger machines cost disproportionately more.
  • Horizontal: more copies of the app behind a load balancer — a traffic director that accepts requests and forwards each to a healthy instance (round-robin, least-connections, or by session affinity). This is why statelessness (3.1) matters so much: any instance can answer any request if shared state lives in the database/cache, not in the process.

Adjacent pieces of the same machinery:

  • CDN (Content Delivery Network): a worldwide network of caching servers (Cloudflare, Fastly, CloudFront, Akamai…). Static assets and cacheable pages are copied to datacentres near users, so a visitor in Sydney doesn't wait for a round trip to Virginia. CDNs also absorb DDoS traffic and terminate TLS at the edge. For LLM apps, the CDN caches your static assets — never the API responses (those are per-user and dynamic).
  • Reverse proxy: a server that sits in front of your app and forwards requests to it — load balancer, CDN, nginx, API gateway, all are reverse proxies. It terminates TLS, routes by path/host, rate-limits, caches, and shields the app. Your FastAPI app behind uvicorn behind nginx behind a CDN is four hops of this pattern; 11C.1 shows the real topology.
  • Replicas / high availability: running N copies so one can die. Health checks tell the balancer which instances are alive; failed instances get traffic pulled. "Availability" — the fraction of time the service actually answers — is bought with redundancy, and it's the S in the SLA/SLO vocabulary (11A.2).

4.6 Containers and why Docker exists (no hands-on)#

A container packages your app with its dependencies — language runtime, system libraries, config — into one image that runs identically on any Linux host. Docker is the tool that made containers mainstream; Kubernetes orchestrates them at scale. The problem containers solve is precisely "it works on my machine": your laptop has Python 3.13, the server has 3.11 and different system libs; the container ships your exact environment.

For this path: containers are deployment machinery, not a skill you need now — 11C.1 covers them when your services deploy. What you should carry forward is the idea: reproducible environments — a Dockerfile/pyproject.toml/lockfile that makes "the same code runs the same way everywhere" a property of the artefact, not a hope. 01B.1 gives you the Python-level version of this today.

4.7 Environments: dev, staging, prod#

Almost every real system runs the same codebase in at least three places:

Environment Purpose Data Traffic
Development (dev) You, locally or a dev box fake/sample data you only
Staging / preview A production-like copy for final checks before release anonymised or synthetic prod-like data internal testers
Production (prod) Real users real data the public

The rules that keep this sane: config differs per environment, code doesn't — database URLs, API keys, feature flags and log levels come from environment variables or a config file per deploy, never hard-coded and never shared between envs (01B.2). A staging environment that shares the production database is a loaded gun: a test run can corrupt real data. And "it works in staging" is the strongest pre-prod signal you get — which is why the gap between "dev" and "prod" should be as small as your risk tolerance allows, not as large as your fear of deploys.

4.8 Configuration, logs and monitoring (in concept)#

Three observability pillars, plus the data flow underneath:

  • Logs: timestamped records of what happened — "request 8f3k2 started", "LLM call took 4.2s", "error: card declined". Your first debugging tool and your last resort; structured logs (JSON per line) are what make them queryable at scale. Python's logging module (01A.8) is the foundation; 01B.10 makes it production-grade; 11A.1 is the LLM-specific observability stack.
  • Metrics: numbers over time — requests/sec, error rate, p50/p95/p99 latency, tokens consumed, cost per request. The difference between "the site feels slow" and "p99 latency tripled after the deploy" is a metrics pipeline.
  • Traces: one request's path across services — browser → your API → vector DB → LLM provider — as a tree of timed spans. When a request takes 9 seconds, a trace tells you which hop ate it; without one you're guessing.
  • Alerting: thresholds on metrics that page a human — error rate > 1%, p99 > 5s, queue depth growing. The art is alerting on user pain, not on every blip (11A.2).

The meta-rule for this whole part: you can't fix what you can't see. Every production concern — latency, cost, errors — becomes tractable only when it's instrumented. Build the habit of asking "how would I know this is happening?" before "how do I fix it?".

4.9 The physics of networks: latency, throughput, availability, timeouts#

A handful of terms describe every network interaction, and confusing them causes most "the API is slow" arguments:

Term Meaning Feels like
Latency Time for one round trip (request → response). Dominated by distance: ~0.5ms same machine, ~1–10ms same city, ~70–150ms cross-country, ~150–300ms intercontinental "the wait"
Throughput How much data per second the link carries (bandwidth) "the bulk"
Bandwidth The pipe's capacity; throughput is what you actually get the road width
Jitter Variance in latency — inconsistent delays "sometimes fast, sometimes weird"
Packet loss Dropped packets; TCP retransmits, adding latency random stalls
Availability Fraction of time the service answers ("five nines" = 99.999%) "is it up"

Timeouts are the engineering response to all of it: every network call needs some bound, or a hung peer hangs you forever. There are several distinct ones — connect timeout (how long to establish), read timeout (max gap between received bytes), total/request timeout (whole call ceiling), and pool-acquisition timeouts for connection reuse. 01B.9 implements them; 03.8 is the LLM-specific version where "the model is thinking" legitimately takes 30–120 seconds and your timeout must accommodate that, not a web page's expectations.

The practical takeaway for LLM apps: an LLM call is slow by design — seconds to minutes, not milliseconds — and expensive per call. Every architecture decision in Part 5 flows from that single fact.

4.10 The eight fallacies of distributed computing#

In the 1990s engineers at Sun Microsystems — Peter Deutsch listed the first seven in 1994, and James Gosling added the eighth around 1997 — wrote down assumptions engineers make about networks that are always false: "the eight fallacies". They're still the best checklist for "why did this work in dev and explode in prod":

  1. The network is reliable — it isn't; packets drop, links fail. → retries, timeouts, idempotency.
  2. Latency is zero — it isn't; even localhost has cost, cross-region has hundreds of ms. → async design, caching, colocation.
  3. Bandwidth is infinite — it isn't; large payloads (a 50-page PDF, a huge prompt) cost real time and money. → pagination, compression, chunking.
  4. The network is secure — it isn't; everything crosses hostile networks. → TLS everywhere, auth on every call.
  5. Topology doesn't change — it does; instances scale, die, move. → discovery, health checks, no hard-coded hosts.
  6. There is one administrator — there isn't; your app, the cloud, the CDN, the provider are different trust domains. → least privilege, defence in depth.
  7. Transport cost is zero — it isn't; every hop costs latency and money (data transfer fees are real cloud bills). → minimise chatty call patterns.
  8. The network is homogeneous — it isn't; TCP, UDP, HTTP/2, HTTP/3, different MTUs and middleboxes. → don't assume what works on your machine works everywhere (QUIC/HTTP-3 vs networks that block UDP is a live example).

Part 5: Where LLMs fit#

Everything in Parts 1–4 was generic web engineering. This part applies it to the thing the whole path is about: an LLM provider is not magic, not a different kind of software — it is an HTTPS API that returns text, reachable with the exact same client → server → database machinery as everything else you've met. The only differences are the ones that matter for design: calls take seconds instead of milliseconds, and each call costs money.

5.1 The model is "just another API your backend calls"#

When your backend needs an LLM answer, it makes an HTTP request — POST https://api.openai.com/v1/responses (or the Anthropic/Gemini/OpenRouter equivalent) with your prompt in the body and your API key in a header — and reads back generated text, usually as JSON. 03.1 shows the actual wire format for all four providers; you don't need it yet. What you need now is the placement: the LLM call is an outbound integration from your backend, sitting in the same tier as the database and the payment processor.

That single framing resolves most architecture questions:

  • It's synchronous by default — your code waits for the response (seconds). For work the user triggered and is waiting on, that's correct.
  • It's expensive and rate-limited — every call costs tokens; providers cap requests per minute. Both facts push work toward batching, caching and queues (03.9 covers batch APIs; 11B.1 is the cost model).
  • It's unreliable in the ordinary way — timeouts, 429s, 500s, truncated responses. It fails like every other network dependency, so it gets the same treatment: timeouts, retries with backoff, fallbacks (03.8, 01B.9).
  • It's stateful only through you — the model remembers nothing between calls; conversation history is data your backend stores and resends each time (02 explains why; 03.2 shows the mechanics).

5.2 The reference architecture: chat with your docs#

The canonical AI product — a user asks a question, the app answers from your documents — is a RAG pipeline, and every hop in it is machinery from this lesson:

sequenceDiagram
    autonumber
    participant U as User's browser
    participant APP as Your backend
    participant VDB as Vector database
    participant LLM as LLM provider API
    participant EV as Email / billing services

    U->>APP: "ask a question about our docs"
    APP->>APP: check auth, rate limits, build prompt
    APP->>VDB: embed question, search top-k chunks
    VDB-->>APP: relevant passages + scores
    APP->>LLM: prompt + passages (API key stays here)
    LLM-->>APP: answer tokens, streamed
    APP-->>U: answer streamed back (SSE)
    APP->>EV: log usage, update counters (async)

Read it as a web request that got longer: the browser asks your backend (hop 1); the backend fans out to a vector database for retrieval and to the LLM provider for generation (hops 2–3); the answer streams back (hop 4). 07.1 dissects this pipeline stage by stage — ingestion, chunking, embedding, indexing, retrieval, grounded generation — and 06.5 covers the vector store choice. For this lesson the point is architectural: three of the five hops are service-to-service calls your backend makes, and each inherits every concern of Part 4 — timeouts, retries, cost, observability.

5.3 Why the browser never calls the provider directly#

The obvious shortcut — let the browser fetch() the LLM API — fails on three independent grounds:

  1. The key. Provider keys are secrets. Anything shipped to the browser is public: view-source, DevTools, or one fetch in the console extracts it, and whoever has it spends your money (03.1 §3.5). There is no "hidden" key in client-side code.
  2. CORS, opt-ins and quotas. Whether a browser may read a provider's response at all is the provider's CORS decision, and providers differ. Some make you opt in on purpose: Anthropic's API expects an anthropic-dangerous-direct-browser-access: true request header, and the official OpenAI JavaScript SDK refuses to run in a browser unless you pass dangerouslyAllowBrowser. The alarming names are deliberate warnings. This behaviour lives in the vendors' SDK repositories rather than on the API reference pages: both openai-node and anthropic-sdk-typescript document dangerouslyAllowBrowser in their READMEs, and the Anthropic SDK's client source sends the anthropic-dangerous-direct-browser-access header when that option is on (checked 11 November 2026). Check each provider's current docs before you rely on it. Even where a direct call works, per-user rate limits and spend controls belong on your backend, not spread across every visitor's browser.
  3. Your logic lives server-side. Retrieval, prompt assembly, guardrails, logging, billing, conversation state — all of it must run where you control it. A browser calling the provider directly bypasses every layer of your product.

The pattern is always browser → your backend → provider, with your backend as the trusted middle: it holds the key, enforces auth and quotas, shapes the prompt, and returns only what the UI should see. This is the same reason you never put business rules in frontend JavaScript — the browser is a display and input device, not a trusted runtime.

5.4 What is slow and what is expensive#

Two numbers govern every LLM feature's UX and bill:

  • Latency: an LLM call takes seconds — a fast model on a short prompt might answer in 0.5–2s; a reasoning model or a long context can take 30–120s. Compare to a database query (milliseconds) or a static file (microseconds at the CDN). This is why "the spinner" is the defining UI element of AI apps, and why perceived-latency design (progressive rendering, skeleton states, streaming) matters more here than anywhere else in web dev. 11B.1 models both cost and latency precisely; 03.3 is the streaming deep-dive.
  • Cost: you pay per token (input + output, with cached-input discounts on some providers). A single call is fractions of a cent; a million calls is real money. Cost levers: smaller models for easy tasks, prompt caching for repeated prefixes, batch APIs for non-urgent work (typically ~50% cheaper), shorter contexts, and not calling the model when a lookup would do. 03.7 covers the pricing model; 11B.1 the optimisation.

The design consequence: LLM calls are the most expensive, slowest thing your backend does — treat them like database writes that cost money and take seconds, not like function calls that are free and instant. That means: cache aggressively where correctness allows, batch where latency allows, stream where attention requires, and measure everything (11A.1).

5.5 Streaming to the browser: SSE in concept#

When an LLM generates, tokens arrive one at a time over seconds. Two ways to deliver them to the user:

  • Wait for the whole answer, then send it — simple, but the user stares at a spinner for 10 seconds and can't tell "working" from "dead".
  • Stream it — the server sends each chunk as it's produced, and the UI appends text live. The standard mechanism is Server-Sent Events (SSE): a long-lived HTTP response with Content-Type: text/event-stream where the server writes data: {...}\n\n events as tokens arrive. One-directional (server → client), automatic reconnection, works through every proxy and load balancer that handles HTTP — which is why LLM providers and frameworks standardised on it.
text
# What an SSE stream looks like on the wire (abridged; the JSON shape is simplified —
# each provider names its events and fields differently, see 03.3):
data: {"type":"content_block_delta","delta":{"text":"Hello"}}

data: {"type":"content_block_delta","delta":{"text":" there"}}

data: {"type":"message_stop"}

The browser consumes it with EventSource (or fetch + a reader for POST bodies); your backend produces it with a streaming endpoint. 03.3 §2.1 is the wire-format deep-dive, and 01B.7 builds the FastAPI SSE endpoint. For this lesson: streaming is the same request/response pattern stretched over time — one HTTP response whose body arrives in pieces, and the UI renders incrementally. It's why chat UIs feel alive while the model is still "thinking".

5.6 Where this goes next#

The vocabulary is now in place for the whole path:

  • 03.1 — the actual HTTP requests to all four providers, keys and headers on the wire
  • 03.3 — SSE wire format, provider stream events, parsing partial JSON
  • 07.1 — the full chat-with-docs pipeline this section sketched
  • 11C.1 — where the backend actually runs
  • 11A.1 — how you see what the request did
  • 11B.1 — the cost/latency model in detail

Part 6: Deployment — where the code actually runs#

Deep-dive

"Deployment" is the moment your code stops being a folder on your laptop and becomes a service on the internet. No hands-on here — this is the map of where code can live and what has to be true for the world to reach it.

6.1 Where code runs: laptop, VM, PaaS, serverless, containers#

Home What it is You manage Best for Trade-off
Your laptop / a server you own A machine you control everything: OS, security patches, uptime, backups learning, internal tools, dev it's off when you close the lid; you're the on-call
VM (virtual machine) / bare metal in a cloud (EC2, GCE, Azure VMs, Hetzner) A virtual machine you rent OS upwards: packages, firewall, TLS, deploys full control, long-running stateful services, learning infra you are the sysadmin
PaaS — platform-as-a-service (Render, Railway, Fly.io, App Engine, Elastic Beanstalk) Platform runs your app from a repo/Dockerfile app code + config; they handle OS, TLS, scaling basics the sweet spot for small teams and this path's projects less control, vendor pricing, some lock-in
Serverless / FaaS — function(s)-as-a-service (Lambda, Cloud Functions, Workers, Vercel functions) Functions invoked per request function code + triggers sporadic traffic, glue, event handlers cold starts, time limits, ephemeral state, vendor APIs
Containers on orchestrators (Kubernetes, ECS, Nomad) Packaged apps on a container platform images, config, scaling rules; platform handles placement many services, teams, strict isolation the most operational complexity — earn it
Static hosting + CDN (GitHub Pages, Cloudflare Pages, S3+CloudFront, Netlify) Files served from edge caches the files docs, marketing, SPAs' static shells no per-user logic — pair with an API for dynamic parts

The decision rule from 4.1 applies: start where the operational burden is lowest that meets your needs — a PaaS or static host for a prototype, a VM when you need control, containers/Kubernetes when you have the team and the scale to justify them. 11C.1 §1.3 works through this for LLM services specifically.

6.2 Domains, DNS records and HTTPS certificates#

For https://yourapp.com to reach your server, three things must line up:

  1. A domain — registered with a registrar (Namecheap, Porkbun, Cloudflare…), which puts it in the global DNS.
  2. DNS records pointing at your host — an A/AAAA record mapping the name to your server's IP (for a VM/PaaS), or CNAME (canonical-name) records pointing at the platform's hostname (for PaaS/static hosts, where the provider gives you a target like yourapp.onrender.com). TTLs control how fast changes propagate (the caching from 1.3).
  3. An HTTPS certificate — the TLS credential proving you control the domain. PaaS platforms and CDNs issue them automatically (usually via Let's Encrypt); on a VM you use certbot/ACME or put a CDN/reverse proxy in front. Without it, browsers show the "not private" warning — and Chrome now asks before opening plain-HTTP public sites when its "Always Use Secure Connections" default is on, so HTTPS is effectively mandatory for a public app.

The subdomain trick you'll use constantly: app.yourdomain.com for the web app, api.yourdomain.com for the API, status.yourdomain.com for status page — all CNAMEs or A records under one domain you control. Cookies scoped to .yourdomain.com then work across them (with the Domain attribute from 3.2).

6.3 Environment variables in production#

Your laptop reads .env; production reads the platform's env-var store or secret manager — same mechanism (os.environ / process.env / your settings object), different storage. The rules:

  • Never commit secrets — .env is gitignored from day one (00.3, 00.4); production secrets live in the platform's encrypted store, not in the repo, not in CI logs, not in screenshots.
  • Different values per environment — dev points at localhost/tickets.db, staging at staging resources, prod at prod — same variable names, different values (4.7).
  • Validate at startup — a missing OPENAI_API_KEY should fail loudly on boot, not on the first user request at 3am. pydantic-settings (01B.2) makes this declarative.
  • Rotate, don't reuse — a leaked key is rotated, not "cleaned up"; 03.1 §3.7 is the first-hour checklist.

6.4 "It works on my machine" and reproducibility#

The most quoted bug report in software: "it works on my machine." It's not a joke — it's a reproducibility failure. The code didn't change; the environment did: different Python version, different dependency versions, different OS libraries, a .env you have that CI doesn't, a file path that exists locally but not in the container. The fixes are all forms of making the environment part of the artefact:

  • Pin dependencies — pyproject.toml + a lockfile (uv.lock) so "the same versions" is a file, not a memory (01B.1).
  • Declare the runtime — .python-version, Docker base image, or platform runtime setting: Python 3.13 everywhere, not "whatever's installed".
  • Config via environment, not files — paths, hosts, keys come from env vars (6.3), so the same image runs in dev/staging/prod.
  • Containers when it matters — the Dockerfile is the ultimate "same environment everywhere" (4.6).
  • CI runs the same checks — tests, lint, build run on every push in a clean environment (00.4 introduces Actions; 11C.2 is the LLM version), so "works on my machine" fails before it reaches prod.

The mindset shift: "works on my machine" means "the artefact doesn't capture its environment" — and the fix is always to move another piece of environment into version control.

6.5 Decision table: which architecture for which app#

The app is… Start with Because
Docs, blog, portfolio, marketing site Static files + CDN (GitHub Pages, Cloudflare Pages, Netlify) No per-user logic; fastest, cheapest, most reliable
Internal tool / dashboard for a small team Monolith on a PaaS (Render, Railway, Fly.io) + managed DB One deploy, one codebase, you need it working not elegant
Public web app with user accounts Monolith + managed Postgres + auth (or managed auth like Clerk/Auth0) on a PaaS Standard three-tier; PaaS handles TLS/scaling basics
Real-time collaboration / chat with live updates Above + WebSocket or SSE endpoint; consider a managed realtime service Persistent connections need sticky routing or a service designed for it
Sporadic/event-driven workloads (webhooks, scheduled jobs, glue) Serverless functions + queues Scales to zero, pay per invocation, no idle cost
Many teams, many services, strict isolation Services on containers/Kubernetes Only when team scale or compliance demands the operational cost
AI/LLM feature on any of the above The app's architecture + an LLM call behind your backend The model is an integration, not an architecture (Part 5)

Part 7: Request traces — two walkthroughs#

Deep-dive

Theory ends here; tracing begins. A request trace is the discipline of following one request through every layer — and the two examples below are the ones you'll actually meet: a mundane web flow and an AI flow.

7.1 Trace 1: "Reset my password"#

A user clicks "Forgot password" on app.example.com. Watch every hop:

# Actor What happens Machinery from this lesson
1 Browser GET /forgot-password → server returns a form Act 4 HTTP; SSR or SPA render
2 Browser User submits email → POST /forgot-password with {email} Validation on server (never trust the form)
3 Backend Checks user exists — same response either way ("if that email exists…") to avoid account enumeration Business logic + security
4 Backend Generates a random token, stores token → user_id, expiry in DB/Redis, builds link https://app.example.com/reset?token=… Session-store pattern from 3.3
5 Backend → email provider POST to the email API (SendGrid/SES/Resend) with the link — synchronous or queued Integration call; queue if slow (4.3)
6 Browser (minutes later) User clicks link → GET /reset?token=… → server validates token (exists, unexpired, unused) → shows new-password form Token-as-capability; single-use, short expiry
7 Browser POST /reset with token + new password → server hashes it (3.9), updates DB, invalidates token + all sessions AuthN write; session revocation
8 Browser Redirect to login → POST /login → session cookie set (3.3) The full auth loop

Notice what's not there: the email provider never sees your DB; the token never appears in logs (it's a credential); step 3's identical response is deliberate security. Every row maps to a section you just read — that's what "tracing" means: naming the machinery at each hop.

7.2 Trace 2: "Ask the assistant"#

Same user, now logged in, asks "why was ticket #4471 escalated?" in your AI assistant. This is the 5.2 pipeline with auth and state:

# Actor What happens Machinery
1 Browser POST /api/ask {question} with session cookie → your backend AuthN via session lookup; CSRF/CORS checks
2 Backend Authorise: is this user allowed to ask? Rate limit: calls/min per user? Quota: budget left? AuthZ + abuse control — the expensive-call guardrails
3 Backend Load conversation history for session_id from DB (last N turns) Stateful app on stateless protocol (3.1)
4 Backend → embedding API POST question → embedding vector (or reuse a cached one) Another provider call — same machinery, smaller cost
5 Backend → vector DB similarity search top-k chunks filtered by tenant_id Retrieval; metadata filtering (06.6)
6 Backend Assemble prompt: system + history + retrieved passages + question; enforce context budget Prompt engineering (04)
7 Backend → LLM provider POST /v1/responses (or equivalent) with key from env; stream response The expensive, slow call (5.4)
8 Backend → Browser SSE stream: each token chunk → data: event → UI appends Streaming (5.5, 03.3)
9 Backend (async) Write the turn to conversation history; log tokens/cost/latency; update usage counters Observability (4.8, 11A.1)

Two traces, same lesson: every hop is either "the browser↔backend HTTP exchange" or "a backend→service integration" — and every integration inherits timeouts, retries, auth and cost. When this trace breaks, the failure table from 1.5 plus "which hop?" is your debugging method (00.9).

7.3 Reading a HAR / DevTools capture (illustrative)#

A HAR (HTTP Archive) file is a JSON recording of every request a page made — DevTools' Network tab → right-click → Save all as HAR with content. It's the flight recorder for "what did the browser actually send and get?". An illustrative excerpt for our POST /api/ask:

json
{
  "log": {
    "entries": [
      {
        "request": {
          "method": "POST",
          "url": "https://app.example.com/api/ask",
          "headers": [
            {"name": "Cookie", "value": "session=8f3k2-sessionid"},
            {"name": "Content-Type", "value": "application/json"}
          ],
          "postData": {"text": "{\"question\":\"why was ticket 4471 escalated?\"}"}
        },
        "response": {
          "status": 200,
          "statusText": "OK",
          "headers": [{"name": "Content-Type", "value": "text/event-stream"}],
          "content": {"mimeType": "text/event-stream", "text": "data: {...}\n\ndata: {...}"}
        },
        "time": 8420
      }
    ]
  }
}

(Example output (illustrative — your exact output will differ): the shape is real — HAR is JSON with log.entries[], each having request, response, timings and time.)

Read it like the trace tables: request.method+url is the hop, headers shows auth (the cookie, Authorization), postData is the body, response.status is the outcome, time is total ms. When a bug report says "it's broken", the HAR answers "what did the browser actually do" without reproducing anything. Caveat: HAR files contain cookies and tokens — treat them as secrets; don't paste them into tickets or chat.

Symptoms you'll actually meet, mapped to the hop that owns them:

Symptom Likely hop First check
"Site can't be reached" DNS nslookup yourdomain.com / try another network
Works on laptop, not on phone (same Wi-Fi) Server bind / firewall Is the server bound to 127.0.0.1 only? Is the port open?
Works on 127.0.0.1:8000, fails on localhost:8000 Bind / loopback family localhost resolved to ::1 but the server listens only on 127.0.0.1 (or the reverse) — bind ::/dual-stack or use the literal IP
Login works, then randomly logs out Session store Multiple server instances, in-memory sessions, short TTL
API works in curl, fails in browser CORS / preflight DevTools Network → look for the OPTIONS request and its response headers
Page loads, buttons dead Render/JS Console tab for JS errors; check blocked scripts
"Ask" returns empty after 30s LLM hop Provider timeout, rate limit (429), key invalid — check backend logs
Answer streams then cuts off SSE/proxy Proxy buffering the stream; read timeout shorter than generation time
Works in dev, fails in prod Environment Env vars present in prod? Same Python/deps? Domain/cookie scope (localhost vs real domain)?
Intermittent 502s Infrastructure Instance crash, deploy in progress, health-check flapping
Slow everything Any hop Tracing/metrics — which span is slow? (11A.1)

Common misconceptions#

Misconception Reality
"The server is a computer." It's a program that listens and responds — the same laptop is a client when it browses and a server when http.server runs. "The server" behind Gmail is hundreds of machines; the word means the role, not the box.
"localhost is a website." It's a name for your own machine — 127.0.0.1/::1 loopback, and it can resolve to either family depending on the OS. localhost:8000 means "the program on this computer listening on port 8000" — which is why a server bound to only 127.0.0.1 can refuse a localhost request that resolved to ::1.
"HTTPS means the site is safe/trustworthy." TLS encrypts the pipe and proves domain control — nothing more. Phishing sites have valid certificates; the padlock is necessary, not sufficient.
"The browser talks to the database / the LLM directly." Never. The browser talks only to your backend; the backend talks to the database and to provider APIs. That's the trust boundary everything else hangs on.
"An API key in frontend code is fine if it's 'hidden'." There is no hidden client-side code — view-source, DevTools and fetch in the console expose everything shipped to the browser. Keys live in your backend's environment, period.
"Cookies are sent to every website." Cookies are scoped by domain (and path). A cookie set by app.example.com goes back only to matching hosts — which is also why localhost cookies don't work on your real domain.
"A 404 means the server is down." A 404 is a successful response: the server answered "no such route". Down means no response at all — DNS, TCP or TLS failed before HTTP began.
"HTTP/3 / QUIC replaced HTTP." HTTP/3 is a new transport (over QUIC/UDP) carrying the same HTTP semantics. URLs, methods, status codes and headers are unchanged — only how bytes move got faster.
"You need a server to have a website." Static files + a CDN is a website — docs, blogs, marketing sites and SPAs' shells need no per-request code at all. "Server" is needed only when per-user or dynamic work exists.
"JWTs are encrypted, so they're safe to read." JWTs are signed, not encrypted — the payload is plain base64 JSON anyone can read. The signature proves it wasn't tampered with; it doesn't hide contents. Never put secrets in a JWT payload.
"DNS propagation means the record is travelling." Nothing travels — the authoritative record changes instantly; the delay is caches expiring at resolvers worldwide at their own TTLs.
"More microservices = more professional." Microservices buy independent scaling and team autonomy at the cost of network calls, distributed debugging and consistency. Most products should start as a well-factored monolith and extract only on real pressure.

Key takeaways#

  • A web app is client → network → server → data/services; every bug is a failure of one hop, and the symptom table in 1.5 is how you find which.
  • Typing a URL runs five acts — DNS, TCP, TLS, HTTP, render — each with a distinct failure signature.
  • IP addresses locate machines, ports locate programs on them; 127.0.0.1 is yourself, 0.0.0.0 means "all interfaces", and a server "listens" on a bound port.
  • The three tiers are front end (HTML/CSS/JS in the browser), back end (routing, validation, auth, business logic, integrations), and data (databases, caches, queues, external services).
  • HTTP is stateless; login works because cookies carry a session reference, tokens carry proof, and OAuth delegates authentication to a provider — all so the server can reconstruct "who is this" per request.
  • The browser is untrusted: secrets, business rules and provider keys live only in your backend. CORS is a read-gate for browsers, not a security boundary for your API.
  • Production vocabulary is a dictionary for incidents: monolith vs services vs serverless, sync vs async, queues and webhooks, load balancers and CDNs, containers, dev/staging/prod, logs/metrics/traces, latency/throughput/availability/timeouts, and the eight fallacies.
  • An LLM provider is just another HTTPS API your backend calls — slow (seconds) and expensive (per-token), which is why it gets timeouts, retries, streaming, caching and cost controls like every other integration, only stricter.
  • Deployment is making the environment part of the artefact: pinned deps, declared runtime, env-var config, secrets in a manager, CI checks — so "works on my machine" stops being a bug report.
  • The request trace — following one request through every layer — is the debugging method everything else serves.

Where you'll use this in the AI path#

This lesson is the map every later module assumes you can read:

  • 03.1 — the LLM call as an HTTP request on the wire, keys in headers, .env hygiene (§1.1, §3.4–3.5)
  • 03.3 — SSE, the streaming mechanism from 5.5, in full (§2.1)
  • 07.1 — the chat-with-docs pipeline from 5.2 built for real (§2.1)
  • 06.5 — the vector database from 2.5 as a chosen service (§1.2)
  • 01B.7 — the backend tier from 2.4 implemented in FastAPI, including the SSE endpoint
  • 11C.1 — Part 6 applied to LLM services (§1.3)
  • 11A.1 — the observability from 4.8 for LLM requests
  • 12 — the auth, secrets and browser-trust decisions from Part 3 under adversarial conditions
  • 13B — the capstone product is a web app with an LLM backend: every layer from this lesson appears in it

Terms introduced in this lesson#

Term Meaning
Web app A program split between a client (usually a browser) and a server, exchanging HTTP requests/responses, with state in a database.
Client Whatever initiates an exchange — browser, mobile app, script, or another server.
Server A program that listens for requests and responds; a role, not a kind of computer.
Front end / back end The part that runs in the browser (HTML/CSS/JS) vs the part that runs on the server (routing, logic, integrations).
HTML / CSS / JavaScript Structure / appearance / behaviour of a web page; JS also runs on servers (Node.js etc.).
DOM The live tree of page elements that JavaScript queries and mutates.
fetch() The browser's built-in HTTP client — the front end's only channel to a backend.
Static site Pre-built files served as-is; no per-request code.
Server-rendered (SSR) Server builds HTML per request from templates + data.
Single-page app (SPA) Shell HTML + JS bundle renders everything client-side, fetching JSON APIs.
IP address Numeric machine address: IPv4 (32-bit, dotted) or IPv6 (128-bit, hex).
Private vs public IP Private ranges (10/8, 172.16/12, 192.168/16, loopback) aren't routable on the public internet — home/office networks hide them behind NAT.
NAT / CGNAT Network Address Translation — many private devices share one public address; carrier-grade NAT (100.64.0.0/10) is the ISP-scale version.
Loopback 127.0.0.1/::1 — "this computer itself"; traffic never leaves the machine.
Port 16-bit number selecting which program on a machine receives a connection; IP:port.
Well-known port Conventionally assigned ports: 22 SSH, 53 DNS, 80 HTTP, 443 HTTPS, 3306 MySQL, 5432 Postgres, 6379 Redis.
Listen / bind A server parks on an address+port waiting for connections; 0.0.0.0 binds all interfaces.
DNS The global name→address directory; resolvers answer A/AAAA queries with TTL-bound caching.
Domain name Human-readable name (api.example.com) mapped to IPs via DNS; subdomain/TLD structure.
URL Uniform Resource Locator — the complete address: scheme, host, port, path, query, fragment.
TTL Time-to-live on a DNS record — how long resolvers may cache the answer.
TCP Reliable ordered byte-stream protocol; three-way handshake (SYN, SYN-ACK, ACK) per connection.
UDP Connectionless packet protocol — faster, unreliable; DNS and QUIC/HTTP-3 use it.
TLS / SSL Encryption + integrity + server authentication for a connection; SSL is the dead predecessor's name.
HTTPS HTTP inside TLS — the https:// scheme; certificate proves domain control.
HSTS Strict-Transport-Security — a response header that makes HTTPS-only behaviour permanent for a domain.
Certificate / CA The server's domain credential, signed by a trusted certificate authority (e.g. Let's Encrypt).
TLS handshake Negotiates version/ciphers, verifies the certificate, derives session keys — one extra round trip.
HTTP request / response Method+URL+headers+body out; status+headers+body back. (Deep dive: 00.6.)
HTTP/1.1, /2, /3 Protocol revisions: text (1.1), binary multiplexed (2), QUIC/UDP transport (3).
QUIC UDP-based transport underpinning HTTP/3 — faster handshakes, connection migration.
Render / paint Browser turns HTML+CSS+JS into pixels; the DOM is the live element tree.
Three tiers Front end (browser), back end (server logic), data (DB + services).
Backend responsibilities Routing, validation, authentication, authorisation, business logic, persistence, integration, response shaping.
Relational / document / key-value / vector DB Tables+SQL / JSON docs / key→blob map / embedding similarity store.
Vector database Stores embeddings and answers "nearest neighbours" — the retrieval engine of RAG.
Cache Fast copy of expensive data; trades freshness for speed at every layer.
Queue / message broker Durable to-do list decoupling producers from workers; absorbs bursts.
Stateless / stateful Remembers nothing between requests vs does; HTTP is stateless by design.
Cookie Server-set key-value the browser returns per domain; attributes (Secure, HttpOnly, SameSite) carry the security.
Session Server-side session_id → user data store; the cookie holds only the random ID.
Session ID Long random token identifying a session — guessability is the security model.
API key Long secret identifying/billing your account; bearer credential sent in a header.
Bearer token Authorization: Bearer <token> — "holder is authenticated".
Basic auth Authorization: Basic base64(user:pass) — encoding, not encryption; HTTPS-dependent.
JWT Signed (not encrypted) header.payload.signature token carrying claims like sub, exp, iss.
OAuth 2.0 / OIDC Delegation protocol for "log in with X"; OIDC adds the identity (ID token) layer.
Access / refresh / ID token OAuth credentials: call-the-API, renew-the-access, prove-who-you-are.
Scope / consent What permissions an OAuth grant asks for and the user approves.
Authentication vs authorisation Who are you (AuthN) vs what may you do (AuthZ) — both checked per request.
RBAC / IDOR Role-based access vs guessing object IDs you don't own — the per-object authZ bug.
Password hash / salt / work factor One-way slow KDF output + per-password random salt + tuned cost; Argon2id/scrypt/bcrypt/PBKDF2.
PBKDF2 Password-based key derivation — OWASP's FIPS fallback at 600k+ iterations (HMAC-SHA256).
CORS Browser read-gate for cross-origin fetch; preflight OPTIONS for non-simple requests.
Same-origin policy Scripts may read responses only from their own scheme+host+port by default.
Preflight Automatic OPTIONS request before "non-simple" cross-origin requests.
XSS / CSRF Script injection in a page vs forged cross-site requests — the attacks HttpOnly/SameSite mitigate.
Monolith / microservices / serverless One deployable app / independently deployed services / per-request functions.
API contract The agreed request/response shape including failure behaviour; versioned, tested through.
Sync vs async Caller waits for result vs hands off and continues; async ≠ parallel.
Background job / worker Queued slow work done off the request path by a separate process.
Webhook Provider-initiated callback to your endpoint on events; needs signature verification + idempotency.
Load balancer / reverse proxy Traffic director / front-door forwarder (also CDN, gateway, nginx).
CDN Worldwide edge cache network serving static/cacheable content near users.
Replica / health check Redundant app copies; checks tell the balancer who's alive.
Container / Docker App+deps packaged to run identically anywhere; orchestrators (K8s) at scale.
PaaS / FaaS / VM Managed app platform / per-request functions / rented virtual machine.
dev / staging / prod Local / production-like test / live environments — config differs, code doesn't.
Environment variable Per-environment config (os.environ); secrets belong in a manager, never in git.
Secret manager Encrypted store for credentials; rotation without redeploying code.
Logs / metrics / traces / alerts Event records / numbers over time / per-request paths / threshold pages — the observability pillars.
Latency / throughput / bandwidth / jitter / packet loss Round-trip time / data rate / pipe capacity / delay variance / dropped packets.
Availability Fraction of time a service answers; bought with redundancy ("nines").
Timeout (connect/read/total) Bounds on how long a network call may wait; every call needs one.
Eight fallacies Sun engineers' list of always-false network assumptions (Deutsch 1994, the eighth added by Gosling) — the prod-debugging checklist.
HAR HTTP Archive — DevTools' JSON recording of every request/response a page made.
Request trace Following one request through every layer to name the failing hop.
SSE Server-Sent Events — one-directional text/event-stream for live server→client data.
DevTools / Network tab Browser inspector; Network shows every request/response/timing — the web debugger.
"Works on my machine" Reproducibility failure: environment not captured in the artefact.

Exercises#

  1. URL anatomy. Without running anything, split https://api.anthropic.com:443/v1/messages?beta=true&max_tokens=100#top into scheme, host, port, path, query and fragment. Then run the url_parts.py pattern from 2.6 on it, once as written and once with :443 deleted — what does u.port print each time, and why does the connection still target port 443?
Solution

scheme https, host api.anthropic.com, port 443, path /v1/messages, query beta=true&max_tokens=100, fragment top. With :443 written, u.port is 443; delete it and u.port becomes None — urlsplit reports only what the URL literally contains; it does not fill in scheme defaults. The connection still targets 443 because the scheme carries the default (https → 443, http → 80), which the browser applies at connect time. The port is part of the scheme's contract, not just the authority string.

  1. Address kinds. Run the ip_kinds.py script from 1.2 with these addresses added: 192.168.0.1, 172.16.5.4, 172.32.0.1, 169.254.1.1, 100.64.0.1. Predict each classification first, then check. Which surprises you?
Solution

192.168.0.1 private, 172.16.5.4 private (172.16–31 is the private range), 172.32.0.1 global (outside 172.16/12 — a classic off-by-one trap), 169.254.1.1 private (link-local), 100.64.0.1 → reserved/documentation — the 100.64.0.0/10 carrier-grade NAT block is the one range where is_private and is_global are both False in Python's ipaddress (an explicit exception in its IANA-registry bookkeeping), so it falls into the fallback branch. It is still not publicly routable — but "not global" ≠ "private" here. The 172.16–31 boundary and this is_private/is_global gap are the two things people get wrong.

  1. The five acts. You're on hotel Wi-Fi and https://example.com fails with "connection timed out" but http://example.com (port 80) loads. Which act failed, and what's the most likely cause? What would you check next?
Solution

TCP/TLS path: port 443 is blocked or the TLS handshake is being interfered with (captive portal, firewall, ISP filtering, or a MITM attempting handshake interception). Port 80 works, so DNS and routing are fine. Next: try curl -v https://example.com to see where it stalls, check for a captive-portal page, try a different network, and check whether the certificate presented is yours.

  1. DevTools walkthrough. Start python3 -m http.server 8000 in ~/code/ai-path (the Setup section above), open http://localhost:8000, open DevTools → Network, reload. Find the document request and report: its method, status, Content-type response header, and total time. Then throttle to "Slow 3G" and reload — what changes?
Solution

The first entry is GET / → 200 OK, Content-type: text/html (Python's http.server sends Content-type: text/html both for .html files and for directory listings), time in the low single-digit ms on localhost. Under Slow 3G — Chrome's preset name; Firefox offers GPRS/3G/4G tiers instead, and release Safari has no built-in throttling — every request's timing inflates and the waterfall spreads out: on localhost the server work is identical; you're seeing the simulated link latency. That's the point of throttling: it separates "slow server" from "slow network".

  1. Cookies. A response (served over HTTPS) contains Set-Cookie: prefs=theme%3Ddark; Path=/; Max-Age=3600, Set-Cookie: session=abc; HttpOnly; Secure; SameSite=Strict and Set-Cookie: analytics=xyz; SameSite=None; Secure. (a) What does the browser send back on the next request to the same site? (b) Which cookies can page JavaScript read? (c) Which are sent on a cross-site POST from another origin? (d) Which are sent on a cross-site top-level GET navigation to your site?
Solution

(a) Cookie: prefs=theme%3Ddark; session=abc; analytics=xyz — the browser returns every cookie scoped to the site (values may be sent encoded; the browser stores and returns them verbatim). (b) prefs and analytics — session has HttpOnly. (c) Only analytics: session has SameSite=Strict, and prefs has no SameSite attribute — Chromium-based browsers treat that as Lax (see the caveat in 3.2: other engines may not), and Lax withholds cookies from cross-site POSTs (it allows them on same-site requests and cross-site top-level GET navigations only). (d) prefs and analytics: Lax allows cross-site top-level safe-method (GET) navigations and None allows everything; Strict still sends nothing cross-site.

  1. JWT. Run jwt_decode.py from 3.4. Now answer: if you changed one character in the payload segment, what would a verifying server conclude? Why can't the attacker just re-sign it? What claim would you check first to reject an expired token?
Solution

The signature no longer matches the payload → verification fails → the token is rejected as tampered. The attacker can't re-sign because they don't have the HS256 secret (or the private key, for RS256/ES256). exp is checked first (or alongside nbf/iat): a correctly-signed but expired token is still invalid — signature proves integrity, exp proves freshness.

  1. Password storage. In password_hash.py, change the password to b"correct horse battery staple!" and predict whether the stored hash changes. Then explain why the salt matters even though it's public: what attack does a unique salt per user stop?
Solution

The hash changes completely — PBKDF2 output depends on password+salt+iterations. The salt being public is fine because it's not secret; its job is uniqueness. Without it, two users with the same password get identical hashes, so one cracked hash reveals every account sharing that password — and precomputed rainbow tables work at all. With per-user salts, each hash must be attacked independently.

  1. Request trace. Trace "a logged-in user uploads a CSV and asks the assistant to summarise it" through the layers: list each hop, name the machinery, and flag where a queue would help.
Solution

Browser POST /api/upload (session cookie → AuthN) → backend validates file type/size (AuthZ + validation) → store file (S3/object storage or disk) → POST /api/ask with file reference → backend retrieves file, chunks it, embeds + stores or retrieves relevant chunks (vector DB) → assembles prompt → LLM call (expensive/slow — candidate for a queue if summarisation can be async: return 202 + notify when done) → SSE stream back → async: write history, log usage/cost. The queue helps at the LLM hop if the user doesn't need to watch it live — and always for post-processing (embeddings, logging).

  1. CORS. Your FastAPI backend at api.example.com must be called from app.example.com. A fetch('https://api.example.com/data', {headers: {'Authorization': 'Bearer x'}}) fails in the browser but the same call works in curl. Explain precisely what fails, what the browser sends first, and the two header changes that fix it.
Solution

The Authorization header makes it a non-simple request → the browser first sends an OPTIONS preflight. The API doesn't answer it with CORS headers, so the browser blocks the read of the real response (the request may still reach the server — check server logs). Fix: the API must respond to OPTIONS with Access-Control-Allow-Origin: https://app.example.com (or * only for public data) and Access-Control-Allow-Headers: authorization, content-type (plus Access-Control-Allow-Methods if needed). curl sees no CORS because CORS is enforced by the browser, not the server.

  1. Architecture choice. For each, pick a starting architecture from 6.5 and justify in one line: (a) a personal recipe blog; (b) an internal expense tracker for 5 people; (c) a webhook receiver that emails you when a package ships; (d) a real-time collaborative whiteboard.
Solution

(a) Static site + CDN — content changes rarely, no per-user logic. (b) Monolith on a PaaS + managed DB — small team, standard three-tier, lowest ops. (c) Serverless function + queue — event-driven, sporadic, scales to zero. (d) Monolith + WebSocket/SSE + sticky sessions or managed realtime — persistent bidirectional connections need more than plain request/response.

  1. Failure diagnosis. A teammate reports: "the app works, but logins randomly fail — users get logged out after a few minutes, and only sometimes." Give three hypotheses ordered by likelihood and the check for each.
Solution

(1) Multiple server instances with in-memory sessions — request 2 hits an instance that never saw the login → shared session store needed (Redis/DB). Check: count instances; do failures correlate with deploys or specific instances? (2) Session TTL/cookie Max-Age too short or clock skew between instances — check cookie attributes and server clocks. (3) Load balancer without session affinity + a second bug (e.g. token signed with per-instance secret) — check whether JWT/session secrets are shared across instances.

  1. The LLM placement. A junior dev proposes calling api.openai.com directly from browser JavaScript "to save a backend hop". List the three independent reasons this fails, and describe the correct pattern.
Solution

(1) The API key is public — view-source/DevTools/fetch extracts it; anyone can spend your money. (2) CORS and opt-in switches — whether the browser may read the provider's reply is the provider's choice (Anthropic requires an explicit anthropic-dangerous-direct-browser-access header, the OpenAI JavaScript SDK refuses to run in a browser without dangerouslyAllowBrowser), and even a technically working call leaves quotas unenforced. (3) Your product logic (auth, quotas, retrieval, prompt assembly, logging, billing) lives server-side and would be bypassed. Correct pattern: browser → your backend (holds key in env, enforces auth/quota, builds prompt, calls provider, returns only what UI needs) → provider.

Check yourself#

  1. What are the five acts between pressing Enter on a URL and seeing pixels, in order?
  2. Why does 127.0.0.1 never leave your machine, and what is 0.0.0.0 in a bind address?
  3. What does a port number select, and name three well-known ports with their services.
  4. What three jobs do HTML, CSS and JavaScript each do on a page?
  5. What's the difference between a static site, a server-rendered page and a single-page app — and which is cheapest to host?
  6. List the eight backend responsibilities from 2.4.
  7. Name the four database families and one example each; which one powers semantic search?
  8. Why does a cookie hold a session ID rather than user_id=42, role=admin?
  9. What's the difference between authentication and authorisation, and what bug does confusing them cause?
  10. Why must an LLM provider key never ship to the browser — give two independent reasons.
  11. What does CORS actually gate, and why doesn't it protect your API from curl?
  12. A request takes 9 seconds end-to-end. Name the four network-quality numbers that could explain it and the tool that tells you which hop is slow.
  13. Why is "it works on my machine" a reproducibility bug rather than a joke, and what's the general fix?
  14. In the "ask the assistant" trace, which hop is the most expensive and slowest, and what three controls does it need?

Further resources#


← 00.4 — GitHub and Collaboration | Module 00 overview | 00.6 — HTTP, REST and JSON →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close