Every FastAPI developer has met Starlette without being introduced. The HTTPException you raise, the Request object you annotate, the BackgroundTasks you inject, the 405 that appears when you POST to a GET-only route β all of that surfaces from Starlette, the ~30-file ASGI microframework that FastAPI bolts its dependency-injection layer onto. When something breaks at 2 a.m. and the traceback passes through starlette/routing.py or starlette/middleware/base.py, most engineers discover they have no mental model of what those files actually do.
That gap is expensive. First, Starlette is the layer that decides how your bytes move: which coroutine matches which URL path, where the request body is buffered, when a gzip compressor spins up a worker thread. Second, Starlette is deliberately tiny β the whole library is a flat starlette/ package with just 37 Python files, no nested subpackages beyond middleware/ β so it is one of the few web frameworks where an afternoon of source reading buys full comprehension. Compare that with larger stacks like Django, where the request path crosses dozens of modules first.
This post walks the real tree of encode/starlette on main: the routing engine, the applicationβs middleware stack, the request/response models, the websocket state machine, and the background-task module. Every line number cited below was checked against the actual source.
Overview of Starlette's runtime shape: the application builds a middleware stack around a Router, which dispatches to Route, Mount, and Host matchers producing Request and Response objects.
Reading the overview from left to right:
- Router.app, L697 β the match loop scans
self.routeslinearly; the first full match dispatches, and the first partial match is parked so a wrong method can become 405 instead of 404. - compile_path, L116 β turns a path string like
/users/{id:int}into a named-group regex, a format string for reverse URL generation, and a convertor map. - CONVERTOR_TYPES, L79 β the registry of five built-in path convertors (
str,path,int,float,uuid), each carrying its own regex plusconvert/to_stringpairs. - build_middleware_stack, L63 β folds
ServerErrorMiddleware, your user middleware, andExceptionMiddlewarearound the Router by iterating the list in reverse. - call_next, L112 β the bridge that lets request/response-style middleware run over raw ASGI, pumping messages through an anyio memory object stream created at L200.
- FileResponse, L303 β a stat-cached file sender that reads in 64 KiB chunks, computes an md5 etag from mtime and size, and parses Range headers capped at 100 ranges (L305).
- WebSocket.receive, L41 β one half of a dual state machine that validates every ASGI websocket message sequence before your handler ever sees it.
The detailed view: path compilation, the middleware chain from ServerErrorMiddleware down to ExceptionMiddleware, and Request/Response machinery including Range parsing and background tasks.
The application is a middleware list folded in reverse
Starlette.__init__ (applications.py, L23) stores almost nothing but configuration: a Router, your user_middleware list, and exception handlers. The interesting part happens in build_middleware_stack (L63). It first splits exception_handlers into two buckets β a handler keyed on 500 or Exception becomes the ServerErrorMiddleware handler, everything else goes to ExceptionMiddleware (L68-72). Then it assembles the ordered list: ServerErrorMiddleware first, an optional RequestBodyLimitMiddleware if max_body_size was set, your middleware, and ExceptionMiddleware last (L74-78). The fold is for cls, args, kwargs in reversed(middleware): app = cls(app, ...) β the classic onion, built from the inside out (L80-83).
Two consequences deserve attention. add_middleware (L104) inserts at position zero of the user list and raises RuntimeError if the stack was already built β middleware is frozen after the first request (L105-106). And the stack itself is built lazily inside __call__ (L92-96), which also stamps scope["app"] = self so handlers and url_for can find the application from any depth.
The two bookend middlewares have opposite jobs. ServerErrorMiddleware (middleware/errors.py, L127) catches what nothing else caught: production returns a plain PlainTextResponse("Internal Server Error", status_code=500) (L259), while debug_response (L249) renders an HTML traceback with highlighted frames. ExceptionMiddleware (middleware/exceptions.py, L18) is the polite half: it registers defaults mapping HTTPException to a PlainTextResponse carrying the exceptionβs detail (L65-69), and publishes its handler tables through scope["starlette.exception_handlers"] (L52) so any wrapped endpoint can participate in the same resolution logic via wrap_app_handling_exceptions.
The routing engine: compiled paths and a three-state Match
Everything in starlette/routing.py orbits one function: compile_path (L116). It walks PARAM_REGEX (L111) β the pattern {name} or {name:convertor} β and emits three things: a regex with named groups, a {name}-style format string for url_path_for, and a dict of convertors. The syntax is strict: an unknown convertor name asserts immediately (L139), and duplicated parameter names raise a ValueError listing the offenders (L158). Host patterns get special treatment β the port is stripped before escaping (L160-164) and the whole regex compiles with re.IGNORECASE, per RFC 9110βs case-insensitive host names (L171-172).
Matching itself returns a Match enum β NONE, PARTIAL, FULL (L41). Route.matches (L251) only matches http scopes; it computes the route path via get_route_path (starlette/_utils.py, L137), which strips the ASGI root_path prefix, then converts every matched parameter through its convertor. The methods logic has a subtle convenience: declaring GET automatically adds HEAD (L246-247), and a path match with a disallowed method yields Match.PARTIAL rather than NONE (L263-264). That distinction is what lets the Router return a proper 405 with an Allow header (L281-287) instead of a bare 404.
Router.app (L685) is the dispatcher: it iterates routes (L697), dispatches the first FULL match immediately (L701-705), parks the first PARTIAL (L706-708), and only after the whole list fails tries a trailing-slash redirect probe β flipping a missing or extra / and re-scanning, returning a 307 if any route matches the corrected path (L720-733). Nothing is cached: the scan is a plain linear pass, which is why route order matters.
Two composite matchers extend the model. Mount (L372) compiles its path with a synthetic trailing parameter β compile_path(self.path + "/{path:path}") (L397) β then pops the path group and rewrites root_path with the matched prefix (L413-431), so a mounted sub-application sees a clean route path. Host (L475) matches the Host header instead of the URL, using parse_host_header to validate IPv6 and strip ports. Both delegate to a child ASGI app, usually another Router, which makes nesting β app.mount("/static", StaticFiles(...)) β just recursion in the same match loop.
Requests, responses, and the price of streaming
Request (starlette/requests.py, L215) extends HTTPConnection (L81), an immutable Mapping over the scope with lazily cached url, headers, query_params, and cookies. Body access is where laziness pays off. stream() (L235) yields chunks straight from http.request messages and flips guards so each body is read exactly once; body() (L255) consumes the stream and caches the bytes in self._body; json() (L264) caches its parsed result. Form parsing (_get_form, L270) asserts the optional python-multipart dependency is installed, then routes to the urlencoded FormParser or the multipart parser. MultiPartParser (starlette/formparsers.py, L134) spools file parts into a SpooledTemporaryFile with a 1 MB in-memory limit (L135) and enforces default caps of 1000 files and 1000 fields (L145-146) β a quiet DoS guard most users never notice.
The response side (starlette/responses.py) is a small class hierarchy. The base Response (L30) renders content to bytes (L49), sets latin-1-encoded content-length/content-type headers (L58-84), and β critically β awaits its background task after sending the body (L174-175). JSONResponse renders with ensure_ascii=False, allow_nan=False, and compact separators (L199-206). StreamingResponse (L227) wraps any iterable or async iterable; on servers advertising ASGI spec_version below 2.4 it races stream_response against listen_for_disconnect inside a collapsing task group so a disconnecting client cancels the send (L272-287), while on ASGI 2.4+ the protocol itself raises ClientDisconnect from an OSError (L274-278).
FileResponse (L303) is the most engineering-dense file in the repo. It sends files in 64 KiB chunks (L304), computes an etag as the md5 of "mtime-size" (L342), and implements full HTTP Range support: _parse_range_header (L505) validates the header, bails to an empty list when the client requests more than 100 ranges (L517-518), and merges overlapping ranges after sorting (L534-544). Multiple ranges produce a multipart/byteranges response with a 13-byte token_hex boundary (L469) and an arithmetically computed content-length (L575) before any bytes are read. StaticFiles (starlette/staticfiles.py, L40) builds on it, adding If-None-Match/If-Modified-Since handling and 404-page lookup in HTML mode.
Background work is deliberately minimal. BackgroundTask (starlette/background.py, L12) stores a function plus args and detects sync versus async via is_async_callable; sync callables run through run_in_threadpool (L23) so they never block the event loop. BackgroundTasks (L26) is just an ordered list whose add_task (L30) appends. Everything runs after the response is fully sent β FIFO order, late errors by design.
From path strings to compressed bytes: build facts in numbers
The codebase rewards readers who like constants. Path conversion supports exactly five convertors out of the box (convertors.py, L79-85); StringConvertor refuses slashes with regex [^/]+ (L21), IntegerConvertor is [0-9]+ (L44), and UUIDConvertor tolerates both dashed and undashed UUIDs via [0-9a-fA-F]{8}-?... (L70). The Match enum has three states (L41-44). Route matching is case-sensitive for paths but case-insensitive for hosts (L172).
Compression and limits form another set of numbers. GZipMiddleware (middleware/gzip.py, L45) ignores bodies under 500 bytes (minimum_size, L49) and defaults to compresslevel 9 (L50); chunks of 128 KiB or more (thread_minimum_size, L51) are compressed in worker threads behind a dedicated anyio.CapacityLimiter(40) (L40) so large payloads cannot starve the event loopβs default thread pool. Fourteen content types are excluded by default (L13-28) β images, video, fonts, and already-compressed formats β and 206 partial responses are never re-compressed (L121). CORSMiddleware (middleware/cors.py, L15) hardcodes its eight-method ALL_METHODS tuple including the newer QUERY method (L11), defaults allow_methods to ("GET",) (L20), sets preflight max_age to 600 seconds (L26), and mirrors the exact origin back when credentials are enabled instead of emitting * (L163-164). SessionMiddleware (middleware/sessions.py, L16) signs cookies with itsdangerous.TimestampSigner (L30), defaults max_age to 14 days (L22), and tracks mutation via a Session dict subclass that flips modified on every write (L95-139). The test tooling: TestClient supports both ASGI2 and ASGI3 apps, detecting the difference in _is_asgi3 (starlette/testclient.py, L56) β a friendlier pattern than the sync WSGI in-process clients Flask popularized, because it drives the async app through anyio portals.
Honest Limits
Starletteβs minimalism has edges worth knowing. Enjoyed this post? Never miss out on future posts by following us BaseHTTPMiddleware (middleware/base.py, L96) wraps every request in a collapsing task group plus a memory object stream β that bridging overhead is real on hot paths, which is why performance-sensitive sites implement native ASGI middleware. Route matching is a linear scan with no compiled dispatch table, so an application with thousands of flat routes pays O(n) per request unless it subdivides with Mount. The middleware stack is immutable once the first request lands (applications.py, L105-106). Sessions are client-side signed cookies β nothing is stored server-side, so large session payloads bloat every request and response. Form parsing caps are defaults, not guarantees; pass explicit max_files/max_fields to change them. Websockets demand discipline: the state machine raises RuntimeError on out-of-order sends (websockets.py, L63-104) rather than papering over protocol mistakes. None of these are bugs β they are the documented cost of a framework whose entire request path fits in 37 files.