Every request runs the same pipeline inside one worker process (server, middleware, router, dependencies, validation, handler, data layer, response), and building a backend well means keeping each stage bounded: never block the event loop, never hold a database connection across a slow call, and never let a request die half done when the process is told to stop.
Fig. 1 is that pipeline. The running example is the chat API built for this page (src/service/app.py); each part of the figure is a section below.
async def handler, a pool of 40 threads for plain def handlers (section 6), and settings read once at startup (section 7). One request that blocks the loop stalls all the others./livez, /readyz), SIGTERM (stop accepting, drain what is in flight) and exit (the lifespan closes the pool): section 9.You need: what an HTTP request and response contain (HTTP, sections 1 and 2). The contract the service exposes (error shapes, pagination, idempotency keys, rate limits, versioning, OpenAPI) is designed on Service APIs; this page builds the service behind it.
New terms
async def handler of a process, switching at each await.This page used to teach the whole API surface from zero. Each part now has an owner that teaches it with its own measurements; here is the one thing to carry from each, and the link.
| Subject | The one thing to carry | Owner |
|---|---|---|
| HTTP methods and status codes | GET is safe, PUT and DELETE are idempotent, POST is neither; 4xx is the caller's fault, 5xx yours (RFC 9110). | HTTP, section 2 |
| Resources and URLs | Nouns in plural collections, verbs in methods, custom methods for actions that are not CRUD (Fielding's REST as practised). | Service APIs, section 2 |
| Error format | One machine-readable shape, RFC 9457 application/problem+json, with a stable type clients switch on and a request ID. | Service APIs, section 2 |
| Pagination and filtering | Cursors, not offsets: on 1M Postgres rows a deep offset page took 98.1 ms against 0.032 ms with a cursor; filters change between pages give INVALID_ARGUMENT (AIP-158). | Service APIs, section 2 |
| Idempotency keys | A client-chosen key makes a POST safe to retry: replay the stored result with Idempotent-Replayed, 409 while the first is running, 422 for the same key with a different body (draft-07); Stripe keeps keys 24 hours. | Service APIs, section 4 |
| Authentication | API keys stored as a hash, sessions against JWTs, OAuth with PKCE, and pinning the JWT algorithm (RFC 8725) so "alg: none" fails. | Auth |
| Rate limits | 429 with Retry-After; RateLimit-Policy is still a draft; rate limiters run before the idempotency layer. | Service APIs, section 5 |
| Webhooks | Sign the raw bytes, reject old timestamps (Stripe: 52 minutes), retry for days (three days at Stripe), dedupe on webhook-id. | Service APIs, section 6; Streaming and real-time, section 9 |
| Streaming output | SSE is one long text/event-stream response; turn proxy buffering off (X-Accel-Buffering: no) and send : ping through idle timeouts. | Streaming and real-time, sections 2 to 5 |
| Versioning and OpenAPI | Additive changes only within a version for tolerant readers (AIP-180); Stripe pins each account to a dated Stripe-Version; diff the spec in CI with oasdiff. | Service APIs, sections 2 and 3 |
| gRPC against REST | REST at the public edge, gRPC with protobuf inside; field numbers are never reused. | Service APIs, sections 8 to 14 |
Also elsewhere: queues and delivery guarantees on Queues, streams and async work; timeouts, retries and probes' failure modes on Reliability engineering; request IDs, logs and traces on Observability; Postgres itself on Topic: databases; how to structure the code behind the endpoints on Code design.
The service built and run for this page is a chat API like any LLM provider's, small enough to read in one sitting: an API key per user, chats, messages that cost 10 credits each (standing in for a model call, which costs real money), and a streamed reply. It is about 200 lines of FastAPI in src/service/app.py, with SQLite standing in for Postgres so it runs anywhere. Every response quoted on this page was captured from it on 2026-10-04 (FastAPI 0.142.2, pydantic 2.13.5, uvicorn 0.54.0, Python 3.12.11); the measurements of sections 2, 6, 7, 8 and 9 come from a second tiny app, src/service/exp_app.py, run on 2026-10-24 (FastAPI 0.162.0, Starlette 1.10.0, AnyIO 4.15.1, pydantic-settings 2.16.1).
| Endpoint | What it does | Shows (section) |
|---|---|---|
GET /v1/health | Is the process up? | Liveness (9) |
POST /v1/chats | Create a chat | Validation (3) |
GET /v1/chats/{chat_id} | Read one chat | Authorise the object in the query (4) |
GET /v1/chats?limit=&cursor= | List chats, a page at a time | One query per page, not N+1 (5) |
POST /v1/chats/{chat_id}/messages | Send a message, get the reply (10 credits) | The LLM endpoint end to end (10) |
To run it: uv run --no-project --with fastapi --with uvicorn uvicorn app:app --port 8765 from src/service/, then curl localhost:8765/v1/health.
GET /v1/health p50 0.341 ms, p99 0.451 ms; GET /v1/chats/{id} with a database read p50 0.383 ms, p99 0.597 ms. An LLM reply takes seconds (the root's Step 5), so what decides the service's behaviour is how it waits: on the model, on the database, on other requests. That is what the rest of the page is about.Fig. 2 · one recorded request, stage by stage
A Python web service has two programs in one process. The server, uvicorn, owns the socket: it accepts connections and parses the HTTP bytes. The application, FastAPI (built on Starlette), receives each parsed request through ASGI (asgi.readthedocs.io): a dictionary called the scope, plus two functions, receive for the body and send for the response. Fig. 2 follows one real request to exp_app.py, GET /trace with an API key; the order of the stages was logged by the app itself recorded, and under the figure is what each stage saw or ran.
receive() only if a route needs it.GET /trace matches this one. No match gives 404; a path that exists with another method gives 405.Depends(current_user), so FastAPI ran it first and passed its result in. This is where authentication, a per-request database session and permission checks live; raising here answers 401 or 403 before the handler runs./trace has no body, so only the header was read. Neither the router nor validation writes to the log, so these two stages carry no number.Recorded 2026-10-24 by src/service/run_experiments.py. Two middlewares were registered, "added first" then "added second"; the log shows the one added second ran outermost (it entered first and left last). The scope is printed as the app received it (client port elided).
Order is a design decision. The middleware registered last wraps everything else, so register the request-ID and timing middleware last (outermost): then they see every request, including the ones an inner stage rejects (no route: 404 or 405; a dependency: 401; validation: 422), and they time the whole trip back out.
Real bytes, captured on 2026-10-04 by src/service/capture.py, which starts app.py and talks to it over a raw socket so nothing is reformatted. Pick an exchange, then click any line for what it means. The Connection: close header was added by the capture client so each exchange is one connection; real clients keep connections open. What each header means in HTTP is HTTP's subject; what each error and idempotency response means as a contract is Service APIs's.
Every byte from a client is untrusted: malformed, malicious, or from an app version two years old. The rule is to turn it into typed objects at the edge, once, and reject what does not fit, so code inside never sees a missing field or a string where a number should be. Alexis King calls it "parse, don't validate": the result of checking should be a value whose type proves the check happened (lexi-lambda.github.io, 2019). A pydantic model is exactly that, and FastAPI builds it before the handler runs:
Field(min_length=1, max_length=200), max_tokens between 1 and 4096): an unbounded content field is how someone sends you 2 GB, or a prompt that costs a fortune.extra="forbid" rejects unknown fields, catching client typos (max_token) that would otherwise be silently ignored; the cost is that clients cannot send fields from a newer version. Anthropic's API rejects an unknown field with "Extra inputs are not permitted" (Claude API errors), which is pydantic's own wording.Literal["small", "large"] is an enum: any other model name fails with a message listing the allowed values.Before and after, on the same bad body {"title": "", "colour": "blue"} (both captured): FastAPI's default answer (on the right, top), and the same failure after the demo's twelve-line exception handler rewrites it into the problem-details shape that Service APIs specifies (below it).
application/json)Both report every failing field at once, so a form can highlight two mistakes in one round trip. The default exposes pydantic's internals (loc, ctx, and the echoed input, which can leak a secret a user pasted into the wrong field); the rewritten one points at each field with a JSON Pointer (RFC 6901), names a query parameter instead ("parameter": "limit" for ?limit=500), and for a body that is not JSON says where it broke ("Invalid JSON at character ...").
Three places can hold code that runs for a request, and choosing the wrong one is a common source of bugs. The test is scope: does it apply to every request, to some routes, or to one?
Drawn from the recorded order in section 2: the outer ring (registered last) enters first and leaves last. A dependency runs only for routes that declare it, after routing and before the handler; FastAPI resolves it together with the parsed body, so both are ready when the handler starts.
| Place | Runs for | Put here | Do not put here |
|---|---|---|---|
Middleware (@app.middleware("http") or a pure ASGI class) | Every request, even a 404 | Request ID, access log and timing (Observability), CORS (HTTP, section 4), compression, a body-size limit | Anything that needs the route or the user: middleware runs before routing |
Dependency (Depends(current_user)) | Routes that declare it | Who is calling, a database session per request (a dependency with yield closes it after the response), permission checks, pagination parameters | Work that must happen for every request |
| Handler | One method and path | Business rules, queries, the model call | Cross-cutting concerns copied into every route |
A dependency is cached once per request: two dependencies that both ask for current_user get one call (FastAPI, dependencies; dependencies with yield).
Knowing who is calling (authentication, Auth) is not the same as checking they may touch this chat. The first entry of OWASP's API Security Top 10 (2023) is Broken Object Level Authorization (API1:2023): an endpoint takes an ID from the URL and returns or changes that object without checking the caller owns it; change chat_ae81... to someone else's ID and you read their chats. The fix belongs in the data layer of the handler: scope every query by the caller, so a lookup by ID alone does not exist in the code base. The demo's:
It answers 404, not 403, for someone else's chat, so the API does not confirm the chat exists. Add a test per endpoint that tries another user's ID (Testing and quality); roles and scopes (chats:read) come later, as a policy layer in a dependency.
Almost every handler reads or writes the database, and three habits decide whether that scales: borrow connections from a pool, make one unit of work one transaction, and count round trips. The demo uses SQLite in memory; a real service uses Postgres with the same tables (Topic: databases).
A Postgres connection is a whole operating-system process on the server, and opening one costs a process start plus authentication; Running Postgres in production measures both (section 7). So each service process keeps a pool: a handful of open connections lent to a request and taken back. Steps 1 to 3 of Fig. 3 do the arithmetic nobody does.
An LLM handler reads the chat, waits seconds for the model, then saves the reply. If it borrows one connection at the start and returns it at the end, the connection sits idle through the whole model call, and the pool needs one connection per request in flight (steps 4 and 5).
max_connections defaults to 100 (the dashed line).max_connections (sizing with Little's law is on Capacity planning and performance).Little's law (in-flight = arrival rate x time held) makes the cost exact. Predict: at the root's busy hour of 231.5 model calls a second (only the message request calls the model) and a 10 s model call, how many connections does holding need, and how many does borrowing twice for 1 ms each need? Then move the slider.
The same rule covers transactions: a transaction left open across the model call holds its locks and its snapshot for seconds. Read what you need, commit or release, call the model, then open a short transaction to save the result.
Derived: connections busy = 231.5 model calls/s x seconds held. Before holds for the model call (10 s at the default: 2,315, the root's figure for streams open at once and Capacity planning and performance's corrected one, "correction (2026-10-24)": its earlier 11,570 counted all five requests per message as model calls); after holds two 1 ms borrows (read the history, save the reply): 0.5. The rate is the root's busy-hour estimate; the 1 ms per borrow is Capacity planning's assumption, not a measurement.
A transaction makes several writes commit together or not at all. In the demo's message handler the reply, the credit charge and the stored response (for idempotent retries) must agree, so they are one transaction:
If they were separate statements, a crash between them would leave credits taken and no reply, or a reply nobody paid for. Isolation levels and the anomalies they allow are Transactions and concurrency's subject; the handler's job is to draw the boundary in the right place.
INSERT before the transaction above. If anything fails between the claim and the commit (the model call times out, the process is killed, any unexpected exception), the row stays at started, nothing releases it, and every retry with that key gets 409 "still in progress" forever. The demo releases the claim only on the two paths it thought of (unknown chat, streaming). Code design found and measured this while refactoring the same handler. The fix is general handler hygiene: release on every exit that did not save a response (Code design's step 10 wraps the claim in one context manager, idempotency_claim), and give each claim an expiry so a claim left by a process that died without cleanup is taken over after a few minutes. The captures on this page come from the demo as it was and were not rerun.The list page of chats with each chat's last message, written the obvious way with an ORM's lazy loading, is one query for 20 chats and then one per chat: 21 round trips. One query with a join returns the same rows. Query planning and performance measured it on one laptop (psycopg 3.3.6, 0.056 ms for SELECT 1): 1.42 ms against 0.22 ms per page, 6.5 times. Across a network each extra trip costs its full latency. Move the round-trip time:
Every query passes values as parameters (the demo's ? placeholders), so the database never interprets user text as SQL: that is the whole fix for SQL injection. The fix for N+1 is eager loading (selectinload or joinedload in SQLAlchemy, select_related and prefetch_related in Django) or writing the join; the way to notice is a trace that shows how many queries each request made (Observability). Paging itself is one query per page with a cursor (the demo's where (created_at,id) > (?,?); the design is Service APIs's).
async def but calls sqlite3, a blocking driver. With an in-memory SQLite that blocks for microseconds; with a network database it blocks the whole event loop for every query (section 6 measures what that does). Use an async driver (asyncpg, psycopg 3's async connection, SQLAlchemy's asyncio extension) in async def handlers, or keep the handler a plain def.Derived: time on the wire = round trips x round-trip time; query execution is left out. Four presets: the measured local trip (0.056 ms, Query planning), and from the root's Numbers to know tab the same data centre (0.5 ms, Dean 2009), zone to zone in one region (2 ms, Microsoft's target) and two nearby regions (8 ms, Azure East US to East US 2, P50). At 2 ms the 21 trips cost 42 ms against 2 ms for the single query; the root adds 21 x 0.067 ms of lookup time for 43.41 ms.
Time until all 50 were answered, the four styles on one scale measured. Recorded 2026-10-24 by src/service/run_experiments.py on an Apple M1 Pro laptop over loopback (uvicorn 0.54.0, one worker unless stated; httpx client with 50 open connections; the client takes about 45 ms to send all 50).
A handler spends most of its time waiting: on the database, on the model, on another service. What decides throughput is what the process does with the other requests while one waits. FastAPI gives two ways to write a handler, and uvicorn a third lever:
async def runs on the process's single event loop. At each await the loop switches to another request; a call that blocks without await (time.sleep, a synchronous HTTP client, a blocking database driver) stops every request on that worker until it returns (FastAPI, async).def runs in a worker thread from AnyIO's pool, so blocking is fine; the pool has 40 threads by default (CapacityLimiter(40) in AnyIO 4.15.1, printed by the run below).--workers N starts N processes sharing the port, each with its own loop and pool.Predict: 50 requests arrive at once, each waiting 500 ms. Written as async def with time.sleep(0.5), how long until the first one is answered? Then pick a style. Fig. 4 replays each recorded run: every ball is one request, at the place it waited, on the run's own clock.
time.sleep(0.5) never hands the loop back, so the 50 sleeps run one after another, and for 25 seconds not a single answer goes out, not even to the first request.await asyncio.sleep(0.5) hands the loop back, so the loop keeps switching and the 50 waits overlap.def handlers run in AnyIO's thread pool, not on the loop.CapacityLimiter(40) lets 40 handlers sleep in threads at once; the other 10 wait for a free thread.| Work the handler waits on | Write it as | Why |
|---|---|---|
Network I/O with an async client (model API via httpx.AsyncClient or the provider's async SDK, asyncpg) | async def, await everything | Thousands of waits share one thread; best for long model calls and streams |
| A library that only blocks (a synchronous SDK or driver) | Plain def, or await anyio.to_thread.run_sync(f) inside async | Threads absorb the blocking, up to the pool size |
| CPU work in Python (tokenising, parsing large JSON, resizing images) | More worker processes, a process pool, or a queue | Threads do not help under the GIL; processes do |
How many processes: on a single machine, uvicorn --workers N with roughly one per core; under Kubernetes, FastAPI's deployment guide says you "will probably not want to use workers and instead run a single Uvicorn process per container" (FastAPI, server workers), letting the cluster add replicas and the load balancer spread connections. Gunicorn as a process manager now takes the separate uvicorn-worker package (uvicorn 0.54.0's uvicorn.workers module prints a deprecation warning pointing to it). The GIL, threads against processes for CPU work (measured, with the free-threaded build) and how many replicas a load needs are Capacity planning and performance's; asyncio itself is Python: concurrency, asyncio and the GIL, section 2's.
Configuration is, in the Twelve-Factor App's words, "everything that is likely to vary between deploys (staging, production, developer environments, etc)": the database URL, the model name, the provider key, timeouts. Its rule: "The twelve-factor app stores config in environment variables", and its test is "whether the codebase could be made open source at any moment, without compromising any credentials" (12factor.net/config). In Python the usual tool is pydantic-settings: a class whose fields are read from the environment, typed and validated like a request body, once, when the process starts.
1 validation error for Required / database_url / Field required [type=missing, ...]. A crash loop at deploy time is visible; a service that starts and fails one request in a hundred is not.SecretStr field prints as SecretStr('**********'), so the whole settings object can be logged at startup without leaking the key; the value comes out only through provider_key.get_secret_value() at the point of use.secrets_dir reads (a Kubernetes Secret volume, Docker's /run/secrets). Never in the repository, the image, a URL or a log line. Rotating a secret then means a restart or a reload hook, so design for both keys being valid for a while.os.environ in the middle of a handler cannot be tested or audited.Feature flags and gradual config rollouts are configuration that changes while the process runs; rolling them out like code is on Reliability engineering. The code-design view of settings objects is on Code design.
Top row: highest priority; each row is the source added at that step, numbered in the order added, and the value then read. Recorded with pydantic-settings 2.16.1: a Settings class with env_prefix="CHAT_", a .env file and a secrets_dir, each source added in turn for model_name. The value read went small, from-secrets-dir, from-dotenv, from-environment, from-init: an argument in code beats an environment variable, which beats the .env file, which beats a file in the secrets directory, which beats the class default.
Some work does not need to finish before the user gets an answer: send a notification, meter the tokens, generate a chat title, index the message for search. Doing it inline makes every user wait for it. There are three places to put it, and the difference is what happens when the process dies.
FastAPI's own guidance draws the same line: background tasks run "after returning a response", and for "heavy background computation" that does not need the same process "you might benefit from using other bigger tools like Celery", which need "a message/job queue manager, like RabbitMQ or Redis" but run "in multiple processes, and especially, in multiple servers" (FastAPI, background tasks). Section 9 shows the in-process kind being waited for on a graceful shutdown and cancelled on a forced one. For long work the client must see, answer 202 Accepted with a job resource to poll; queues, at-least-once delivery and the outbox pattern (write the job row in the same transaction as the business change) are Queues, streams and async work's.
Medians of seven requests to exp_app.py (2026-10-24): inline, the client waited 506.3 ms; with BackgroundTasks the response came in 4.2 ms and the work finished 501.8 ms after it, in the same process. The queue row is drawn, not measured: the handler only enqueues, and a separate worker process does the work.
| Inline | BackgroundTasks | A queue and a worker | |
|---|---|---|---|
| User waits for it | Yes | No | No |
| Runs in | The request | The same process, after the response is sent | Another process, maybe another machine |
| If the process is killed | The request fails; the client knows | Lost silently; the client already got 200 | Survives: the job is in the broker until a worker acknowledges it |
| Retries | The client's | None unless you write them | The queue's, so the job must be idempotent |
| Use for | Work the answer depends on | Small, losable work: FastAPI's example is a log line or "sending an email notification" | Anything that must happen, is heavy, or takes longer than a deploy's grace period |
A service is started, checked and stopped by something else: a load balancer, Kubernetes, a deploy script. Each of those asks a question the service must answer honestly.
GET /livez (the demo's /v1/health) answers 200 from the process itself, touching nothing else. Failing it gets the container restarted, so it must not check the database: when the database has a slow minute, every pod would fail liveness and restart at once.
GET /readyz checks what a request needs (a pooled SELECT 1 with a short timeout, the model client configured) and answers 503 while starting, while a dependency is down, and once shutdown begins. Failing it takes the pod out of the load balancer, without a restart.
Kubernetes' three probes (liveness, readiness, startup), their defaults and the outages caused by probes that check too much are on Reliability engineering.
Open the pool, read the settings, warm the model client once, in the app's lifespan: code before its yield runs before the first request, code after it once the server has drained. A pool opened lazily inside the first request makes the first users slow; one closed nowhere leaves connections for Postgres to time out.
Kubernetes stops a pod by sending SIGTERM to the container's main process; "The default terminationGracePeriodSeconds setting is 30 seconds", after which "The container runtime sends SIGKILL to any processes still running" (Kubernetes, pod lifecycle). Removal from the load balancer happens "At the same time as the kubelet is starting graceful shutdown", not before it. Here is what uvicorn does with that SIGTERM, recorded with a slow request, an idle keep-alive connection and a background job in flight. Predict: does the slow request get its answer? Fig. 5 replays the recording recorded on the run's own clock: exp_app.py under uvicorn 0.54.0, a 3 s request sent at about 0.2 s, a 3 s background job at about 0.3 s, SIGTERM at about 1.0 s, then a new connection and a request on the idle keep-alive connection (times in ms from the start of the run, the same clock for server and clients).
yield (close the pool) runs at 3,416 ms, and the process exits at 3,426 ms, 2,423 ms after SIGTERM, well inside the 30 s grace period.Both runs follow uvicorn's Server.shutdown in uvicorn/server.py (0.54.0): close the listeners, ask each connection to shut down, wait for connections and then tasks up to the timeout, cancel what is left, run the lifespan shutdown. The process then re-raises the signal it caught, so its exit status is "killed by SIGTERM" (143 in a shell) even after a clean drain.
preStop hook that sleeps a few seconds before the signal, so the pod leaves the balancer first; the sleep counts against the 30 s.--timeout-graceful-shutdown (or your server's equivalent) a few seconds under terminationGracePeriodSeconds, so cancellation and the lifespan shutdown run before SIGKILL, which runs nothing.Code from src/service/app.py with its real line numbers. The demo "calls the model" with a sleep and an echo; the captured responses of each branch (401, 429, 400, 201, the replay, 409, 422, the stream) are in the exchanges block of section 2.
POST /v1/chats/{chat_id}/messages is where every section meets: it costs money, takes seconds, may stream, and is the request users retry. The steps below walk the demo's real handler; on the right is the code that ran for the captures real code, and each step says what it does and what a production version adds.
MessageIn (content up to 32,000 characters, model small or large, max_tokens 1 to 4096, stream) and two headers. FastAPI validates all of it before line one of the body runs; a bad request is a 422 that cost nothing. The handler is async def because it awaits the model.Depends(current_user)) shared by every route.INSERT that the primary key lets only one attempt win; a retry gets the stored answer, a concurrent one 409, a different body with the same key 422. This claim sits outside the transaction of step 8, which is the stuck-key bug of section 5.StreamingResponse of server-sent events; the status line is sent now, so any later failure must be an event. The demo frees the key and stores nothing here; production stores the finished message so a retry can fetch it, and stops when the client disconnects.await client.messages.create(...) with an async client and a timeout, so the event loop serves other requests during the seconds it takes (section 6).The order is the design. Cheap rejections come first (credentials; the rate limit, a bucket of 5 requests refilling at 1 per second; a missing key), so a flood of bad requests costs almost nothing; the rate limit runs before the idempotency claim, so a 429 is not stored against the key; the expensive call happens only after the request is known to be valid, owned and not a duplicate; and everything that must agree afterwards commits in one transaction.
httpx.AsyncClient(timeout=...) or asyncio.timeout), shorter than the client's, with the provider's own retries counted in; the demo has none, which is how the stuck-key bug of section 5 is triggered. Timeout budgets are Reliability engineering's.await (section 6).await request.is_disconnected() between chunks (Starlette also raises on a failed send) and cancel the model call, or you pay for tokens nobody reads.usage (input and output tokens) in the same transaction as the stored reply, not a flat 10 credits.The SSE format and chunked encoding are taught byte by byte on Streaming and real-time; here it is only this endpoint's real output.
What the user sees from the streaming branch, one arrival per step, with the arrival times of the capture: a start event, five deltas about 50 ms apart, a stop event.
"stream": true.message_start, 0.8 ms. The status line and text/event-stream go out before any text exists, in the same packet as the first chunk.message_stop at 261.7 ms, with finish_reason "stop".Sections 3 to 10 cover the service itself. The rest of the list a Python API normally gains before launch, each with the page that owns it:
| Add | Because | Owner |
|---|---|---|
| Postgres with migrations (Alembic) instead of SQLite in memory | SQLite in memory loses everything on restart and serves one machine | Topic: databases |
| A timeout on every outgoing call and on the request itself | One slow dependency otherwise holds every worker | Reliability engineering |
| A request ID per request, structured logs, metrics per endpoint and status, traces | "It failed" must become one search | Observability |
| A body size limit at the proxy and in the app | A 2 GB body is a denial of service | Section 3 (field limits); the proxy's on HTTP |
| TLS termination, CORS rules for browser clients, security headers | Browsers enforce who may call you from which site | HTTP, TLS and certificates |
| Tests per endpoint: happy path, each error, another user's ID, a retried key, a diff of the OpenAPI spec | The contract is only as good as its tests | Testing and quality |
| A gateway in front (auth, rate limits, routing to model providers) once there are several services | Cross-cutting rules in one place | Gateways and routing |
| Load tests at the expected peak | The worker and pool numbers of sections 5 and 6 are guesses until measured | Capacity planning and performance |
GET /unsubscribe?id=... gets triggered by an email scanner.{"error": ...}. Every proxy, monitor, retry policy and SDK reads the status code: dashboards stay green while users fail.primary key(owner, key)) make the second insert fail.JSON has no date type, no integer against decimal distinction and no comments (RFC 8259), hence three rules:
"chat_ae8136d1b896" and Stripe's cus_....created_at) or RFC 3339 with a time zone ("2026-10-04T19:06:35Z").amount: 2000 for $20.00.The contract details this page used to keep (PUT against PATCH, about:blank and Stripe-Should-Retry, the empty end token, allow-listed filters bound into the cursor, descending keysets, Hyrum's law, Brandur Leach's atomic phases, OpenAPI 3.2.0 and the LLM call as an ordinary resource) are on Service APIs (sections 2 to 4), and why a 422's reason phrase says "Entity" is on HTTP (section 2). The demo's own cursor is hex-encoded JSON, which a curious client can decode: fine for a demo, a mistake in production.
This page replaced the API half of the old "API and Code Design" page (fetched 2026-09-22, saved in src/live.md, every claim mapped in src/coverage.json); its code-design half went to Code design. On 2026-10-24 the API-contract sections moved to the protocol pages (top of this page) and this page became the owner of the service behind the contract. Corrections it made to the old page, still standing:
Stripe-Version header overrides it per request.Times for pages in this knowledge base are their measured core reading times (closed details not counted) as of October 2026; outside resources are estimates for a careful first read. Links checked 2026-10-24.
The root: one request to an LLM chat product followed from 1 user to 10 million. Step 1 (the front door) and Step 4 (the double charge) lead into this page; its Numbers to know tab holds the round-trip times used in section 5. About 21 min.
REST done properly, error formats, pagination (the Postgres measurement), idempotency keys, rate limits, webhooks, versioning, OpenAPI, gRPC and GraphQL. About 46 min.
The message, methods and status codes, caching, CORS and cookies, HTTP/1.1 to 3, proxies and timeouts. About 45 min.
API keys, sessions against tokens, OAuth 2.1 with PKCE, OIDC, JWT verification, mTLS. About 42 min.
SSE byte by byte, LLM token streams, cutting and resuming streams, WebSockets, webhooks from the receiver's side. About 38 min.
Little's law, pool sizing, the GIL and threads against processes measured, load testing. About 39 min.
Timeouts, retries with backoff and jitter, circuit breakers, health probes, SLOs. About 40 min.
202 Accepted and job resources, at-least-once delivery, deduplication, the outbox pattern. About 40 min.
Request IDs, logs, metrics and traces for a service like this one. About 39 min.
The demo's message handler refactored step by step, including the stuck-key fix. About 42 min.
Testing endpoints and contracts in CI. About 46 min.
The N+1 measurement of section 5, EXPLAIN, indexes and batching. About 45 min.
What a connection costs, max_connections, PgBouncer, backups and failover. About 43 min.
ACID, MVCC, isolation anomalies and locks behind the handler's transaction. About 43 min.
asyncio from the event loop up, threads and the GIL. 19 min, plus 10
The 2026 toolchain: uv, ruff, type checkers, packaging. 22 min, plus 15
The LLM gateway, routing and caching in front of APIs like this one.
What happens behind POST /messages when a model answers.
Abuse and prompt-injection checks around an LLM endpoint.
Build the demo's pieces yourself: parameters, bodies, validation, errors, dependencies, background tasks. About 3 h with typing along.
When to write async def and when plain def, from the framework's author. About 25 min.
Workers, containers, HTTPS, running behind a proxy. About 1 h.
Models, fields, validators and pydantic-settings: the contract layer of Python services. About 1 h 30 min for the core pages.
Config, backing services, processes and disposability (fast startup, graceful shutdown) in twelve short pages. About 30 min.
SIGTERM, the grace period, preStop and how endpoints change during a stop. About 30 min for the termination part.
The ten ways APIs get broken into; API1, object-level authorisation, is the one a handler fixes. About 45 min.
Why validation should produce types. Examples in Haskell; the idea is language-free. About 25 min.
A whole handler designed around transactions, atomic phases and recovery points; the contract side is on Service APIs. About 40 min.
API-contract resources (RFC 9457, Stripe's idempotency and versioning posts, Zalando's guidelines, Google's AIPs, RFC 9110, Standard Webhooks) are listed on Service APIs and HTTP; Ousterhout's book and Google's code review guide on Code design.