Architecture Library · Web systems
Web Server & Python Framework Architecture
Follow an HTTP request from the browser to a Python endpoint and back. The goal is to understand the responsibilities and boundaries of each component—not just memorize framework terminology.
The guide starts in Plain English. Choose Technical for implementation details or Show both to compare. Use the diagrams to inspect each component.
Start here · The whole system
The complete request path
When you open a website or call an API, your browser does not directly call a Python function. Several layers cooperate. The browser creates an HTTP request, the operating system moves bytes over a network connection, a server-side program accepts those bytes, and a Python application eventually receives structured request information.
Select a component to read its role and jump to the relevant section.
Plain English
Think of a request as a parcel. The browser writes the address and contents; networking delivers the parcel; the web server receives it; the framework decides which part of your application should handle it.
Technical
HTTP defines application-level semantics. TCP provides an ordered byte stream. The server parses protocol data and invokes an application through an interface such as ASGI. The framework handles routing, dependency resolution, validation, endpoint execution, and response serialization.
01 · The route to a machine
From browser to server: DNS, IP, and ports
A browser starts with a URL such as https://api.example.com/items/42. The hostname is useful to humans, but network packets need an IP address. DNS (Domain Name System) lets the client discover an address associated with the hostname. DNS does not send the HTTP request itself; it helps the client find where to connect.
What the URL contributes
- Scheme:
httpsindicates HTTP protected by TLS. - Host:
api.example.comidentifies the destination name. - Port: HTTPS normally uses 443; HTTP normally uses 80. A URL can specify a different port.
- Path and query:
/items/42?include=owneridentify the resource and optional query parameters.
After resolving the hostname, the client establishes a transport connection to an IP address and port. With HTTPS, a TLS handshake also establishes encryption and authenticates the server certificate before HTTP application data is exchanged.
What does the server bind to?
A server process usually asks the operating system to listen on a local address and port. 127.0.0.1 means this machine only; 0.0.0.0 means listen on all IPv4 interfaces. A process listening on port 8000 is not automatically public—the machine's network, firewall, routing, and hosting configuration still matter.
Plain English
DNS is like looking up a business address. The IP tells the network which machine to reach; the port tells that machine which listening service should receive the connection.
Technical
Name resolution returns address records. The client then connects to an address/port tuple. A TCP listener is associated with a local socket address; routing and firewall rules determine whether remote clients can reach it.
02 · Operating-system boundary
Sockets and TCP: how programs exchange bytes
A socket is an operating-system communication endpoint that an application can use through a programming interface. For a typical TCP server, Python asks the OS to create a socket, bind it to an address, mark it as listening, and accept incoming connections.
Server-side socket operations
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 8000))
server.listen()
client_socket, client_address = server.accept()
data = client_socket.recv(4096)
client_socket.sendall(b"received")
client_socket.close()
AF_INET selects IPv4 addressing. SOCK_STREAM requests a stream socket, commonly TCP. bind() claims a local address/port, listen() makes the socket a passive listener, and accept() returns a new connected socket when a client connects. The original listening socket remains available to accept more connections.
TCP is a byte stream—not a message system
TCP provides reliable, ordered bytes. It does not preserve the boundaries of your application's writes. If a sender calls sendall() three times, the receiver may read those bytes in one call, several calls, or partial chunks. The receiver must know the application protocol's framing rules—for example, a delimiter, a fixed-size header, or a length prefix.
TCP also handles retransmission, ordering, flow control, and congestion control. Your application should not attempt to rebuild those mechanisms. It should correctly read the bytes it needs and interpret them according to its protocol.
Plain English
The listening socket is the front entrance. accept() gives you a separate conversation line for one visitor. TCP delivers a stream of bytes, not ready-made sentences.
Technical
A TCP connection is identified by endpoint tuples. The listening socket remains in the listen state while accepted sockets represent established connections. Stream reads can return fewer bytes than requested; applications implement framing above TCP.
03 · Application protocol
HTTP: the language of web requests
HTTP defines how clients and servers describe requests and responses. It is an application-layer protocol carried over a transport connection. HTTP/1.1 commonly uses a textual message format; HTTP/2 and HTTP/3 use different framing mechanisms, but preserve HTTP's core request/response semantics.
An illustrative HTTP/1.1 request
GET /items/42?include=owner HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer <token>
The request line contains a method, target, and protocol version. Headers carry metadata such as host, accepted media types, credentials, and content information. A request with a body—such as a JSON POST—also carries content after the header section.
An illustrative response
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 27
{"id":42,"name":"Keyboard"}
The status code communicates the outcome category. The headers describe the response, and the body carries the representation. Common examples include 200 success, 201 created, 204 no content, 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, and 500 server error.
HTTP does not decide how Python functions run
HTTP describes the message exchanged between client and server. It does not define FastAPI routing, Python coroutines, database sessions, or how many worker processes should run. Those responsibilities belong to the server, interface, framework, and application layers.
Plain English
HTTP is the agreed format of the conversation: what the client wants, extra details, what happened, and any data returned.
Technical
HTTP semantics define methods, status codes, fields, and message behavior. The wire framing depends on the HTTP version and its transport mapping. A framework receives parsed request information rather than raw Ethernet or TCP packets.
04 · Server responsibilities
What a web server actually does
A web server is the program or server layer that accepts client connections and handles HTTP communication. Depending on the software and deployment, it may terminate TLS, parse HTTP, serve static files, enforce limits, route requests, proxy traffic to an application server, or invoke an application directly.
Web server versus application framework
- Web server: manages network connections and HTTP protocol handling.
- Application server / interface server: hosts or invokes application code through an agreed interface.
- Framework: provides routing, request objects, validation, middleware, and response construction.
- Your application: implements domain behavior such as creating an order or reading a user profile.
These are conceptual responsibilities, not always separate products. Uvicorn combines an HTTP server with an ASGI application runner. Nginx or Caddy may sit in front as a reverse proxy. FastAPI is the framework that defines the Python application.
Reverse proxy: common, but optional
A reverse proxy accepts traffic on behalf of an upstream application. It can handle public TLS certificates, request-size limits, compression, static assets, routing, and upstream health checks. It forwards requests to Uvicorn over a private network or local socket. It does not replace FastAPI; it sits in front of it.
Plain English
The web server is the reception desk for network traffic. The framework is the office that understands the business request and decides what work should happen.
Technical
Protocol parsing, connection management, TLS termination, proxying, application invocation, and endpoint logic are separable concerns. A deployment can combine or distribute them across processes and hosts.
05 · Handling many clients
Concurrency, threads, processes, and async I/O
A server needs a strategy for making progress when many clients are connected. A slow client should not necessarily prevent every other client from being served. Concurrency is about overlapping progress; parallelism is about work happening at the same instant on multiple execution units.
Three common execution models
- Processes: separate operating-system processes have independent memory spaces. Multiple worker processes can use multiple CPU cores and provide process-level isolation.
- Threads: multiple threads share a process's memory. Threads can be useful for blocking I/O and libraries, but shared state requires care.
- Async tasks: one event loop can coordinate many tasks. When a task awaits non-blocking I/O, the event loop can run another ready task.
What async and await mean
An async def function creates a coroutine function. Calling it produces a coroutine object; it does not automatically run the function to completion. An event loop schedules coroutine tasks. When a task reaches an await on an operation that can suspend, control can return to the event loop until the awaited operation is ready.
async def get_item(item_id):
row = await database.fetch_one(
"SELECT * FROM items WHERE id = :id",
{"id": item_id}
)
return row
This can free the event loop while the database operation waits for I/O—provided the database driver is genuinely asynchronous. Calling a blocking function directly inside an async endpoint can block the event loop and delay unrelated requests. CPU-heavy Python work also does not become parallel merely because a function is declared async.
Why servers use more than one worker
Multiple worker processes can use multiple CPU cores and provide resilience if one worker exits. Each worker may run its own event loop and handle many concurrent connections. More workers also consume more memory and may multiply database connections, so worker counts and connection pools must be sized together.
Plain English
Async is like pausing one task while it waits for a reply, then doing useful work elsewhere. It is not the same as making the waiting task run faster.
Technical
Async I/O uses cooperative scheduling. Tasks yield at suspension points; the event loop drives readiness and resumes them. Blocking calls monopolize the loop thread unless offloaded. Processes provide parallel execution across cores.
06 · Python server
Uvicorn: the server that runs an ASGI app
Uvicorn is an ASGI server. It listens for client connections, handles HTTP and WebSocket protocol events, and invokes an ASGI application using the ASGI callable contract. It is not FastAPI, and it does not decide your application's business rules.
Starting a FastAPI app
uvicorn main:app --host 127.0.0.1 --port 8000
main:app tells Uvicorn to import the Python module named main and use the object named app. The host and port determine the local listening address. For local development, loopback binding is useful; public deployments need an appropriate interface and network configuration.
What happens inside the server?
- Uvicorn creates and starts its listening server.
- The operating system reports incoming connection activity.
- Uvicorn reads and parses protocol data from the connection.
- It builds an ASGI scope describing the connection/request.
- It calls the ASGI application with
scope,receive, andsend. - It translates application response events back into HTTP protocol output.
Uvicorn supports HTTP and WebSocket protocols and can use different event-loop and HTTP parsing implementations depending on installed extras and configuration. Those implementation details can change; the ASGI boundary is the stable conceptual contract.
Plain English
Uvicorn is the adapter between network traffic and your Python application. It understands the connection and HTTP conversation, then hands the request to the app in a standard shape.
Technical
Uvicorn implements the ASGI server side. It owns protocol connections and invokes the application callable per scope. The app communicates asynchronously through receive/send event channels.
07 · The contract between server and app
WSGI and ASGI: how servers talk to Python apps
Web servers and Python frameworks need a shared interface. Without one, every server would need custom integration for every framework. WSGI and ASGI define standard calling conventions that let compatible servers and applications work together.
WSGI: synchronous request/response
WSGI is the traditional Python interface for synchronous web applications. A WSGI server calls an application with an environment dictionary and a start_response callable. The application returns an iterable of response body bytes. This model fits classic synchronous request/response applications.
def application(environ, start_response):
body = b"Hello"
start_response(
"200 OK",
[("Content-Type", "text/plain"),
("Content-Length", str(len(body)))]
)
return [body]
ASGI: asynchronous and event-based
ASGI extends the model to asynchronous applications and connection types such as long-lived WebSockets. The application is an async callable receiving three values:
async def app(scope, receive, send):
# scope describes this connection or request
# receive gets incoming events
# send emits outgoing events
...
scope: metadata about the connection or request, such as type, method, path, headers, and server/client details.receive: an awaitable callable that returns incoming event messages, including HTTP request body events.send: an awaitable callable used to emit response-start and response-body events.
ASGI is an interface, not a server and not a framework. Uvicorn is a server implementation. FastAPI is an ASGI application framework. Starlette provides much of the ASGI web toolkit underneath FastAPI.
Plain English
WSGI and ASGI are like standard plug shapes. A compatible server knows how to connect to a compatible app without knowing the app's internal code.
Technical
WSGI uses a synchronous callable and iterable response body. ASGI uses an async callable and message events over receive/send channels, enabling asynchronous HTTP and WebSocket handling.
08 · Python framework
FastAPI: from ASGI events to your endpoint
FastAPI is a web framework built on Starlette and Pydantic. It receives an ASGI scope and events, matches the request to a route, resolves parameters and dependencies, validates input, invokes your endpoint, and converts the result into an HTTP response.
A small application
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
The decorator registers route metadata. It does not mean Uvicorn directly calls read_item by looking up the Python function name. The framework's router matches the incoming method and path, then orchestrates the endpoint call.
What the framework contributes
- Routing: matches the HTTP method and path to a route.
- Parameter extraction: obtains path, query, header, cookie, and body values.
- Validation: uses type information and Pydantic models to parse and validate data.
- Dependency injection: resolves declared dependencies such as authenticated users or database sessions.
- Endpoint execution: calls your synchronous or asynchronous Python function.
- Serialization: converts the returned value into a response, commonly JSON.
- Exception handling: turns handled exceptions and validation failures into appropriate HTTP responses.
Middleware and the request path
Middleware wraps application handling. It can inspect or modify requests and responses, measure duration, add headers, or handle cross-cutting concerns. Middleware ordering matters: requests pass through the stack in one direction and responses unwind through it in the opposite direction.
FastAPI endpoints can be async def or ordinary def. Async endpoints run in the event-loop context. Ordinary synchronous endpoints are run in a thread pool by the framework so blocking synchronous code does not directly block the event loop. This does not make CPU-heavy work automatically scalable; heavy jobs often belong in a separate worker system.
Plain English
FastAPI is the coordinator. It reads the request details, checks them, finds the right function, supplies what that function needs, and packages the result as a response.
Technical
FastAPI builds on Starlette's ASGI application and routing primitives. It uses dependency graphs and Pydantic validation/serialization around endpoint invocation, then emits an ASGI response through the server interface.
09 · Put the layers together
One request, from socket to endpoint and back
Imagine a client requests GET /items/42. This sequence connects the lower-level networking concepts to the framework behavior you see while building an API.
- Resolve the hostname. The client uses DNS to discover an IP address for the API hostname.
- Establish transport. The client connects to the destination IP and port using TCP. For HTTPS, TLS negotiates encryption and authenticates the server.
- Send HTTP. The client sends the method, path, headers, and any request body using the negotiated HTTP version.
- Accept and parse. The server-side listener accepts or reuses a connection; the HTTP implementation parses the incoming protocol data.
- Create ASGI context. Uvicorn creates the request scope and supplies receive/send callables.
- Enter the application. Uvicorn awaits the FastAPI ASGI application.
- Run framework handling. Middleware, routing, parameter extraction, validation, dependencies, and endpoint execution take place.
- Build the response. FastAPI serializes the endpoint result and emits ASGI response-start and response-body events.
- Write protocol output. Uvicorn turns those events into HTTP response bytes and writes them to the connection.
- Receive the response. TCP delivers ordered bytes to the client; the browser or API client interprets the HTTP status, headers, and body.
The endpoint is only one step in a larger system. If a request is slow, the delay could be in DNS, connection setup, TLS, proxying, application middleware, dependency work, database I/O, CPU work, or response transfer. Observability should measure these boundaries rather than treating every delay as “FastAPI is slow.”
Plain English
Your endpoint is not the front door. It is the handler reached after the network and framework have delivered a properly understood request.
Technical
The request traverses name resolution, transport, HTTP parsing, ASGI invocation, framework middleware/routing/dependency resolution, endpoint execution, response serialization, and protocol transmission.
10 · Beyond localhost
Production architecture and supporting components
A local command such as uvicorn main:app --reload is a development setup, not a complete production architecture. Production adds operational concerns: process supervision, TLS, secrets, health checks, logging, monitoring, resource limits, and controlled deployments.
A common deployment shape
Important supporting components
Database connection pool
A pool reuses a limited number of database connections. It avoids creating a new connection for every query, but its size must be considered across all application workers. Ten workers with a pool maximum of ten can potentially open around one hundred connections.
Cache
A cache stores data for faster reuse. It can reduce repeated database work, but introduces invalidation, expiration, consistency, and failure-handling questions. A cache should not silently become the only durable copy of important data.
Background task worker
Long-running work such as report generation, email delivery, or media processing may be placed on a queue and processed by separate worker processes. This keeps request/response handling from waiting for every task to finish. In-process background tasks are not a replacement for a durable job queue when reliability matters.
Observability
Logs record events, metrics show aggregate behavior, and traces connect work across services. Request IDs and trace context help connect a client request to proxy logs, application logs, database calls, and background work.
Worker count and resource limits
Workers consume memory and may each create database pools. Choose counts based on CPU, memory, blocking work, traffic, and database capacity—not a universal magic formula. Add timeouts and limits for uploads, requests, and concurrency.
Development and production are different
--reload watches source files and restarts the development server when code changes. It is intended for development. Production should use a deliberate process manager or container platform, stable configuration, TLS at an appropriate layer, health checks, graceful shutdown, and a deployment strategy that can recover from process or host failure.
Reference
Glossary and official references
An OS communication endpoint exposed to applications through a socket API.
A reliable, ordered byte-stream transport protocol.
A distributed naming system used to look up records such as IP addresses.
An application protocol for requests, responses, and related semantics.
Software that accepts connections and handles HTTP protocol traffic.
A server that receives requests and forwards them to upstream services.
A scheduler that coordinates asynchronous tasks and I/O readiness.
An asynchronous interface between Python servers and applications.
An ASGI server implementation.
A Python web framework built on Starlette and Pydantic.
Read the specifications and project documentation
- Python socket documentation — socket API, bind, listen, accept, send, and receive.
- RFC 9293: Transmission Control Protocol — TCP protocol specification.
- RFC 9110: HTTP Semantics — methods, status codes, fields, and semantics.
- RFC 9112: HTTP/1.1 — HTTP/1.1 message syntax and connection handling.
- ASGI documentation — application interface and protocol specifications.
- Uvicorn documentation — server configuration and deployment.
- FastAPI documentation — routing, dependencies, middleware, and deployment.
- Starlette documentation — ASGI toolkit used by FastAPI.
- Pydantic documentation — parsing, validation, and serialization.
- PEP 3333: WSGI — Python Web Server Gateway Interface.