Building a backend API: request lifecycle, data layer, async and workers, shutdown

Reading: 32 min, plus 5 in closed details. Data as of October 2026; the chat API's exchanges captured on 4 October 2026 and the service experiments (handler styles, shutdown, background work, settings) recorded on 24 October 2026, all on a laptop over loopback. Child page of Topic: swe-and-system-design; sources are linked inline.

The idea in one screen

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.

  1. Six stages before your code. A request from the client passes uvicorn (the server: the socket and the HTTP bytes, section 2), the middleware (section 4), the router, the dependencies (section 4) and validation (section 3), and only then reaches the handler, all inside one worker process (the dashed outline). Any of them can answer early.
  2. What the handler borrows. A pooled database connection (SQLAlchemy's default pool: 5 open plus up to 10 overflow per process, section 5), the model client (async, with a timeout: sections 6 and 10) and somewhere to hand off work the answer does not depend on (BackgroundTasks or a queue, section 8).
  3. What every request shares. One event loop that runs every 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.
  4. The answer goes back out through the same middleware in reverse, which is how middleware times a request and adds headers to every response (section 2).
  5. The process's own life. Startup (the lifespan opens the pool), serving (/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

ASGI: the Python interface between the server that owns the socket (uvicorn) and the application (FastAPI).
Middleware: code wrapped around every request, on the way in and on the way out.
Dependency: a function FastAPI runs before one route (current user, a database session) and passes in.
Event loop: the one thread that runs every async def handler of a process, switching at each await.
Worker: one server process; several share a port to use several cores.
Connection pool: a few open database connections lent to requests and taken back.
N+1 queries: one query for a list, then one more per item, instead of one query in all.
Lifespan: the app's startup and shutdown hook (open the pool, close it).
Liveness, readiness: "is the process alive" against "should traffic come here now".
Graceful shutdown: stop accepting, finish what is in flight, release resources, exit.
Designing the contract, the protocol and the credentials: where each now lives (one line each)

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.

SubjectThe one thing to carryOwner
HTTP methods and status codesGET 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 URLsNouns in plural collections, verbs in methods, custom methods for actions that are not CRUD (Fielding's REST as practised).Service APIs, section 2
Error formatOne 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 filteringCursors, 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 keysA 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
AuthenticationAPI keys stored as a hash, sessions against JWTs, OAuth with PKCE, and pinning the JWT algorithm (RFC 8725) so "alg: none" fails.Auth
Rate limits429 with Retry-After; RateLimit-Policy is still a draft; rate limiters run before the idempotency layer.Service APIs, section 5
WebhooksSign 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 outputSSE 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 OpenAPIAdditive 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 RESTREST 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.

1. The running example: a chat API in one file

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

EndpointWhat it doesShows (section)
GET /v1/healthIs the process up?Liveness (9)
POST /v1/chatsCreate a chatValidation (3)
GET /v1/chats/{chat_id}Read one chatAuthorise the object in the query (4)
GET /v1/chats?limit=&cursor=List chats, a page at a timeOne query per page, not N+1 (5)
POST /v1/chats/{chat_id}/messagesSend 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.

The framework is not the bottleneck of an LLM product
Measured on an Apple M1 Pro, one uvicorn worker, loopback, keep-alive, 2,000 requests after 200 warm-up: 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

2. One request through the service, 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.

  1. uvicorn turns bytes into a scope. The server read the request line and headers off the socket and built the ASGI scope shown under the figure: method, path, query string, headers as byte pairs (lower-cased names), and who is on each end. The body is not in it; the app pulls it with receive() only if a route needs it.
  2. Middleware runs, outermost first. The two middlewares log their entry. The one registered second entered first: Starlette builds the stack so that the last middleware added wraps the others. Middleware sees every request, before any routing.
  3. The router picks the function. Starlette matches the method and path against the routes in order; GET /trace matches this one. No match gives 404; a path that exists with another method gives 405.
  4. Dependencies run, for this route only, 3rd. The handler asked for 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.
  5. Inputs are parsed and validated. Path and query parameters, headers and the JSON body are converted to the declared types; a failure answers 422 without running the handler (section 3). /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.
  6. The handler runs, 4th. Only now does your code run, with typed arguments and a known user. It returned a dict; FastAPI serialises it to JSON.
  7. The response goes back out, innermost first. The middlewares leave in reverse order (added first leaves 5th, added second 6th), so the outermost one can time the whole request and add headers to every response. Then uvicorn writes the bytes.

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.

Every exchange the chat API produced (20 captured requests and responses, every line explained)

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.

Request
Response
Click a line.
The same request with curl:

3. Validation: parse at the edge, once

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:

  • Limits on every string and number (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).

Where validation stops
Pydantic v2's validation core is written in Rust (pydantic docs), so it costs little next to network and database time. It checks shape: types, lengths, ranges, allowed values. It cannot check meaning that needs the database: whether the chat exists and belongs to the caller, whether the user has credits. Those are business rules in the handler, and they answer 404, 403 or 409 rather than 422. Keep pydantic models at the boundary rather than deep in the program (Code design).
Before and after: FastAPI's default 422 against problem details, same bad body
Before: FastAPI default (application/json)
After: problem details with a JSON Pointer per field

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 ...").

4. Middleware, dependencies and the handler: what goes where

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?

Middleware wraps everything; a dependency wraps one route; the handler is the route

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.

PlaceRuns forPut hereDo not put here
Middleware (@app.middleware("http") or a pure ASGI class)Every request, even a 404Request ID, access log and timing (Observability), CORS (HTTP, section 4), compression, a body-size limitAnything that needs the route or the user: middleware runs before routing
Dependency (Depends(current_user))Routes that declare itWho is calling, a database session per request (a dependency with yield closes it after the response), permission checks, pagination parametersWork that must happen for every request
HandlerOne method and pathBusiness rules, queries, the model callCross-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).

Authorise the object in the query, every time

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.

5. The data layer: pools, transactions and round trips

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

Connection pools, and the arithmetic that runs them out

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.

Never hold a connection across the model call

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

  1. One process, one pool. SQLAlchemy's default pool is 5 connections plus up to 10 overflow, opened on demand: up to 15 Postgres processes for one service process.
  2. Twenty processes. Twenty pods open up to 20 x 15 = 300 connections, and Postgres's max_connections defaults to 100 (the dashed line).
  3. A deploy doubles it. A deploy briefly runs old and new pods together (600). The usual answer is small per-process pools behind a pooler such as PgBouncer in transaction mode, not a bigger max_connections (sizing with Little's law is on Capacity planning and performance).
  4. Holding across the model call (a schematic, not a run). Each request borrows a connection first and returns it only after the model answers: five slow model calls hold all five connections, idle, and every other request queues for one, even one that needs the database for a millisecond.
  5. Borrowing twice. Read the history, give the connection back, call the model, borrow again to save the reply. Each borrow is brief, so the connections are free while the model works; the slider below puts numbers on the difference.

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.

Before and after: the same request holding one connection, or borrowing twice derived

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.

One unit of work, one transaction

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.

A bug in this demo, found later: work outside the transaction left a key claimed forever
The handler claims its idempotency key with an 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.

Count round trips: N+1 queries

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

An async handler needs an async driver
The demo's message handler is 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.
Before and after: 21 round trips or one, as the network gets further away derived

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

6. Async, threads and worker processes: how many requests can wait at once

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).
  • Plain 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.

  1. 50 requests arrive within about 45 ms. The client opens 50 connections at once; every request lands on the worker's one event loop.
  2. The loop runs one sleep at a time. 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.
  3. All 50 answers leave at the end, between 25,412 and 25,460 ms: 25,460 ms in all, and the median request waited 25,421 ms, not about 12.75 s, the median a fair one-at-a-time queue would give (answers at 0.5, 1.0, ... 25 s). Each handler's response is written only after the loop gets back to it, by which time every other request's sleep had run. One blocking call in an async handler hurts every request on the worker, not only the slow one.

So which shape?

Work the handler waits onWrite it asWhy
Network I/O with an async client (model API via httpx.AsyncClient or the provider's async SDK, asyncpg)async def, await everythingThousands 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 asyncThreads 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 queueThreads 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.

The three handlers, exactly as measured

7. Configuration and secrets: read once, typed, at startup

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.

  • Fail fast. A required setting that is missing stops the process at startup, not on the first request that needs it. The recorded error: 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.
  • Secrets are typed as secrets. A 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.
  • Where secrets come from in production: a secret manager (Vault, AWS Secrets Manager, GCP Secret Manager) injected as environment variables or mounted as files; mounted files are what 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.
  • Read once, pass down. Build the settings object in the lifespan hook (section 9) or a cached dependency, and pass it to what needs it; code that reads 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.

Measured: when the same setting comes from five places, the one nearest the code wins

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.

8. Background work: answer first, then do the rest

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.

Measured: the same 500 ms of follow-up work, inline against BackgroundTasks; and where a queue would put it

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.

InlineBackgroundTasksA queue and a worker
User waits for itYesNoNo
Runs inThe requestThe same process, after the response is sentAnother process, maybe another machine
If the process is killedThe request fails; the client knowsLost silently; the client already got 200Survives: the job is in the broker until a worker acknowledges it
RetriesThe client'sNone unless you write themThe queue's, so the job must be idempotent
Use forWork the answer depends onSmall, 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

9. Health checks, startup and graceful shutdown

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.

Two health endpoints, two questions

Liveness: "is this process alive?"

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.

Readiness: "should traffic come here now?"

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.

Startup and shutdown belong to the lifespan hook

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.

What a stop actually looks like

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

  1. Three things in flight. A request on a keep-alive connection was answered (200 at 133 ms) and the connection stays open, idle; a 3 s request was sent at 208 ms (its handler started at 213 ms); a request that left a 3 s background job running got its answer at 316 ms, and the job runs on in the same process.
  2. SIGTERM at 1,003 ms, and uvicorn starts shutting down. The signal handler only sets a flag; the main loop checks it every 0.1 s and logs "Shutting down" at 1,063 ms. It closes the listening socket and asks every connection to close after its current response, so the idle keep-alive connection closes now; "Waiting for connections to close" follows at 1,165 ms.
  3. New work bounces. A new connection at 1,310 ms is refused (ConnectionRefusedError), and a request on the old keep-alive connection at 1,410 ms fails with RemoteDisconnected. A load balancer that still routes here gets errors, which is why a preStop sleep exists; clients must retry such requests on a new connection, elsewhere.
  4. The slow request finishes normally: 200 OK at 3,218 ms. Graceful shutdown waited for it.
  5. The background job is awaited. uvicorn logs "Waiting for background tasks to complete" at 3,315 ms and the job is done at 3,317 ms: it waits for tasks after connections.
  6. Lifespan shutdown, then exit. The code after the lifespan 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.

The shutdown checklist for a service behind a load balancer
  • Keep serving briefly after SIGTERM. uvicorn refuses new connections immediately, but the balancer may still route to the pod for a moment while endpoints update. The common fix is a preStop hook that sleeps a few seconds before the signal, so the pod leaves the balancer first; the sleep counts against the 30 s.
  • Bound the drain below the grace period. Set --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.
  • Long streams outlive any grace period. A model reply can stream for minutes; decide whether to raise the grace period for that deployment, or cut streams and let clients retry with their idempotency key.
  • Background work in the process dies with it once the timeout passes (section 8): what must happen goes on a queue.
The message handler, top to bottom real code

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.

10. Worked example: the LLM-backed endpoint, end to end

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.

  1. The signature is the contract. The path parameter, the body as a 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.
  2. Who is calling. The API key becomes a user or a 401. The demo calls a helper; a production version makes it a dependency (Depends(current_user)) shared by every route.
  3. Rate limit before anything expensive. A token bucket per key (5 requests, refilling at 1 per second); over the limit is a 429 with Retry-After. It runs before the idempotency claim, so a limited request is not stored against the key (the contract is Service APIs's; a shared limiter in Redis or the gateway replaces this in-process dict once there are several workers).
  4. Claim the idempotency key. An 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.
  5. Authorise the object. The chat must exist and belong to the caller, in one query (section 4). Production: this is where the history is read, in one query, and the connection released before the model call.
  6. Or stream the reply. The streaming branch returns a 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.
  7. Call the model. The demo sleeps and echoes. A real call is 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).
  8. One transaction for everything that must agree. The reply, the charge and the stored response commit together (section 5). Production charges by the provider's reported token usage rather than a flat 10 credits.
  9. Answer. 201 with the message and the rate limit headers. What does not change the answer (titles, metering, indexing) goes to a queue after this point (section 8).

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.

What the production version of this handler adds
  • A timeout on the model call (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.
  • One query for the history, then release the connection before the model call (section 5), and an async client so the wait is an await (section 6).
  • Stop when the client goes away. When the user closes the tab mid-stream, check 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.
  • Charge by what was used: the provider's usage (input and output tokens) in the same transaction as the stored reply, not a flat 10 credits.
  • Stream after the checks, store at the end. The demo frees the idempotency key on the streaming path and stores nothing; a real one stores the finished message so a retry can fetch it. The status code is gone once streaming starts, so failures become an error event (Streaming and real-time, sections 4 and 5).
  • Hand off the rest (title generation, metering, search indexing) to a queue (section 8), and pin the model version you call, since a model change is a contract change (Production eval engineering).
Replay of the captured stream, one arrival per step captured
Bytes on the wire
What the user sees

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.

  1. Request sent (0 ms), with "stream": true.
  2. Headers and 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.
  3. The first delta, "Here", also at 0.8 ms.
  4. " is" at 53.0 ms.
  5. " a" at 105.1 ms.
  6. " short" at 157.3 ms.
  7. " reply." at 209.5 ms: five deltas about 52 ms apart, the demo's stand-in for tokens.
  8. message_stop at 261.7 ms, with finish_reason "stop".
  9. The zero-length chunk ends the body, in the same arrival as the stop event.

11. Before real users: what the demo still lacks

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:

AddBecauseOwner
Postgres with migrations (Alembic) instead of SQLite in memorySQLite in memory loses everything on restart and serves one machineTopic: databases
A timeout on every outgoing call and on the request itselfOne slow dependency otherwise holds every workerReliability engineering
A request ID per request, structured logs, metrics per endpoint and status, traces"It failed" must become one searchObservability
A body size limit at the proxy and in the appA 2 GB body is a denial of serviceSection 3 (field limits); the proxy's on HTTP
TLS termination, CORS rules for browser clients, security headersBrowsers enforce who may call you from which siteHTTP, TLS and certificates
Tests per endpoint: happy path, each error, another user's ID, a retried key, a diff of the OpenAPI specThe contract is only as good as its testsTesting and quality
A gateway in front (auth, rate limits, routing to model providers) once there are several servicesCross-cutting rules in one placeGateways and routing
Load tests at the expected peakThe worker and pool numbers of sections 5 and 6 are guesses until measuredCapacity planning and performance

Depth: mistakes, JSON rules and provenance

Common mistakes that the sections above do not already show
  • A GET that changes something. Link previews, crawlers and retrying proxies send GETs freely because RFC 9110 says GET is safe; GET /unsubscribe?id=... gets triggered by an email scanner.
  • Returning 200 with {"error": ...}. Every proxy, monitor, retry policy and SDK reads the status code: dashboards stay green while users fail.
  • Leaking internals in a 500. Stack traces and SQL tell an attacker your stack and schema; log them under the request ID and return a generic problem.
  • Checking "is the key already there?" with a SELECT, then inserting. Two concurrent retries both see "absent"; let a unique constraint (the demo's primary key(owner, key)) make the second insert fail.
  • A streaming endpoint behind a buffering proxy works on a laptop and arrives as one lump in production; test through the real proxy.
  • Renaming a field "because the old name was ugly" breaks every client that reads it: add the new field, keep the old one, deprecate it with a date, remove it only in a new version.
  • No limits on strings, lists, page sizes or bodies: one request can then exhaust memory, database time or model tokens.
JSON rules every handler's output must respect

JSON has no date type, no integer against decimal distinction and no comments (RFC 8259), hence three rules:

  • Big integers break in browsers. JavaScript numbers are 64-bit floats, exact only up to 253 − 1 = 9,007,199,254,740,991 (RFC 8259 §6 warns about this range). Send IDs as strings with a type prefix, like the demo's "chat_ae8136d1b896" and Stripe's cus_....
  • Dates are strings by convention: one format everywhere, Unix seconds (the demo's created_at) or RFC 3339 with a time zone ("2026-10-04T19:06:35Z").
  • Money is never a float: 0.1 + 0.2 is not 0.3 in binary floating point; send integer minor units (cents, credits), as Stripe does with 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.

What changed from the old pages, and the corrections they carried

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:

  • "Cursor ... O(1) on the DB": a keyset page is an index seek plus the page, logarithmic in table size, measured as flat (0.02 to 0.05 ms) from page 1 to a million rows deep; offset is the one that grows linearly.
  • "Return a conflict if the same key arrives with a different payload": the IETF draft says 422 for that case and 409 for a retry while the first is still running; Brandur Leach's 2017 reference code used 409 for both.
  • Idempotency-Key as a standard: it is an expired IETF draft (draft-07, 2025-10-15), though widely implemented.
  • RFC 9457 obsoleted RFC 7807 in July 2023; the major LLM providers still use their own error shapes.
  • "Stripe ... pins each consumer to the version they onboarded with": confirmed; the pin happens on the account's first API request and a Stripe-Version header overrides it per request.