Python API Development — FastAPI + 150-Question Drill
"FastAPI makes the first endpoint take five minutes. This chapter is about the next five hundred."
01 · Why this primer existsYour First Endpoint Takes Five Minutes; the Incidents Start at Five Hundred
FastAPI hides a lot of machinery behind a few decorators, and two of its defaults can hurt you: a blocking call inside an async def endpoint freezes the whole process, and returning a database object without a response model leaks every column. This chapter opens the machinery so you can predict both before they happen.
Here is a launch week that happens to a lot of teams. QuickBite, a food-delivery start-up, builds its orders API in FastAPI. The first endpoint works in five minutes, the tutorial is friendly, and the team ships a first version in three weeks.
On the second day of launch, at lunch time, about 50 customers open the app at the same moment. The app calls GET /v1/restaurants/3/menu. Normally that returns in about 0.1 seconds.
Today it takes five seconds. The server is not out of memory. The CPU graph is flat at a few percent. The database is bored. Yet the slowest customers wait a full five seconds while the fastest wait 0.1.
The endpoint was written like this: async def menu(...), and inside it, a call to a library that waits for the database and does not know about await. The word async on the first line made the function look modern. The blocking call on the third line made it a single-lane road.
You can reproduce the whole incident in a few lines. The next program has three endpoints that each "wait" 0.1 seconds. They differ only in how they wait. A test client sends 50 requests at the same moment to each one and measures how long the batch takes.
The setup: three endpoints, one sleep each. time.sleep stands in for any blocking library call (a synchronous database driver, the requests library, reading a big file). asyncio.sleep stands in for a well-behaved non-blocking wait.
import asyncio, time
import httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/blocking")
async def blocking():
time.sleep(0.1) # blocks the event loop
return {"ok": True}
@app.get("/async-ok")
async def async_ok():
await asyncio.sleep(0.1) # hands the loop back while waiting
return {"ok": True}
@app.get("/threadpool")
def threadpool():
time.sleep(0.1) # plain def: runs in a worker thread
return {"ok": True}
async def hit(client, path, latencies, t0):
await client.get(path)
latencies.append(time.perf_counter() - t0) # every client "arrived" at t0
async def run(path, n=50):
lat = []
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
t0 = time.perf_counter()
await asyncio.gather(*(hit(c, path, lat, t0) for _ in range(n)))
total = time.perf_counter() - t0
lat.sort()
return total, lat[len(lat)//2], lat[-1]
async def main():
print(f"{'endpoint':<12}{'total':>9}{'median':>9}{'slowest':>9}")
for p in ("/blocking", "/async-ok", "/threadpool"):
total, med, worst = await run(p)
print(f"{p:<12}{total:>8.2f}s{med:>8.2f}s{worst:>8.2f}s")
asyncio.run(main())Make the invisible visible: the real numbers from that program, run on the course machine.
endpoint total median slowest
/blocking 5.06s 2.63s 5.06s
/async-ok 0.11s 0.11s 0.11s
/threadpool 0.27s 0.16s 0.26sRead the table as a story. The 50 customers all "arrive" at time zero. With /async-ok the server starts all 50 waits together, so everyone is done after about 0.11 seconds. That is the best case.
With /threadpool (a plain def), FastAPI hands each call to a pool of 40 worker threads. The first 40 finish after 0.1 seconds and the last 10 after about 0.2. The batch takes 0.26 seconds. That is the second best case.
With /blocking, the server does 50 sleeps one after another: 50 × 0.1 = 5 seconds. The median customer waits 2.6 seconds and the last one waits 5.06. Nothing else in the process can run during that time, not even a health check.
Why: an async def endpoint runs on the event loop, the single thread that serves every request in that process. A blocking call inside it stops the loop, and every other request waits. A plain def endpoint runs in a worker thread, so blocking there only blocks that thread.
That is incident one. Section 02 explains the event loop and the thread pool in full, with the rule that prevents it (Idiom: def versus async def).
Incident two arrives on day four. A security researcher emails the team. They called GET /v1/customers/7 for their own account and got back more than they expected:
What you see: two endpoints that return the same database row. The first returns the object directly. The second declares a response model.
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
class CustomerRow: # stands in for the SQLAlchemy object
def __init__(self):
self.id = 7
self.name = "Asha"
self.email = "asha@example.com"
self.password_hash = "$2b$12$Zk9...hash"
class CustomerOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
app = FastAPI()
@app.get("/naive/customers/{cid}")
def naive(cid: int):
return vars(CustomerRow()) # dict of every attribute
@app.get("/v1/customers/{cid}", response_model=CustomerOut)
def safe(cid: int):
return CustomerRow() # the model filters it
c = TestClient(app)
print("naive:", c.get("/naive/customers/7").json())
print("safe: ", c.get("/v1/customers/7").json())naive: {'id': 7, 'name': 'Asha', 'email': 'asha@example.com', 'password_hash': '$2b$12$Zk9...hash'}
safe: {'id': 7, 'name': 'Asha'}The naive endpoint returns every attribute of the row, including password_hash and the email. The endpoint with response_model=CustomerOut returns only the two fields the model lists. Nothing in the first endpoint is "wrong" as far as Python is concerned. FastAPI did exactly what it was told.
In the real incident the leak was a SQLAlchemy object (a Python object that represents one row), and the team returned it straight from the endpoint because the tutorial did the same. A response model is the filter that makes a leak structurally impossible. Section 03 builds it (Idiom: three models, never one).
The fix: both fixes are tiny. Neither one is hard to write. What is hard is knowing, before launch, that the defaults are unsafe. That is what this chapter is for.
The journey of one request
Before the two incidents make sense you need a picture of what happens between a customer's phone and your function. FastAPI feels like one thing, but a request passes through eight stages, and each stage has its own failure modes.
Figure 20.1 shows the path. Each box says where in this chapter it is explained. Keep the picture in your head. Almost every question in the drill is "which box is this failing in?".
async.Notice that box 7, your code, is only one of eight. A big share of production incidents never touch your business logic. They happen in box 2 (too few processes), box 4 (a middleware that reads the body), box 6 (a dependency that opens a connection per request) or box 8 (a model that forgot to filter).
If you know Spring Boot, you already know the shape
Most readers of this chapter have built REST services in Spring Boot (Chapter E4). Almost every idea in FastAPI has a Spring twin. The twin is often a better teacher than the FastAPI documentation, because you already know what it is for.
The table below pairs them. Each row links to the idiom block in this chapter that teaches the Python side. The "catch" in each row is where the translation stops being exact.
| Spring Boot | FastAPI and friends | Where the translation breaks |
|---|---|---|
@RestController, @GetMapping | APIRouter, @router.get (layered structure) | Routes are plain functions registered at import time. Order of registration matters for overlapping paths. |
| DTO + Bean Validation | Pydantic models (annotated constraints) | Pydantic also converts types ("2" becomes 2), which Bean Validation never does. |
@Autowired, IoC container | Depends (yield dependency) | No container and no singletons by default. A dependency is a function run per request. |
application.yml, @ConfigurationProperties | pydantic-settings (settings object) | Environment variables first. There are no profiles unless you build them. |
| JPA / Hibernate | SQLAlchemy 2.0 (session per request) | You write the session lifecycle yourself. There is no @Transactional annotation. |
| Flyway / Liquibase | Alembic (expand and contract) | Autogenerate suggests migrations, but you must review them. |
| Spring Security filter chain | Security dependencies (auth dependency) | Nothing is secure by default. Each route opts in with a dependency. |
@ControllerAdvice | Exception handlers + Problem Details (Problem Details) | Handlers are registered per exception class on the app. |
| Actuator | Health routes + OpenTelemetry (request id) | You write the health routes and wire the metrics yourself. |
MockMvc, @SpringBootTest | TestClient / ASGI transport + dependency overrides (test client) | Overrides replace one function, not a bean in a context. |
| Tomcat thread per request (or virtual threads) | Event loop + thread pool (def vs async def) | One wrong call on the loop stalls everyone. Threads do not stall each other. |
| springdoc OpenAPI | Built-in OpenAPI (section 02) | The schema comes for free from the type hints. Keep it honest with response_model. |
The row that matters most is the second to last: Tomcat gives every request its own thread, so one slow request only slows itself. FastAPI gives all async def requests one thread. That is the root of incident one, and the reason the first half of this chapter is about the event loop.
Here is the smallest possible example of the translation. It is the same endpoint, "get one order by id", in both frameworks.
Spring Boot
A controller class, an annotation for the route and one for the path variable. Spring converts the id to a long for you.
// illustrative
@GetMapping("/v1/orders/{id}")
public OrderOut get(
@PathVariable long id) {
return service.find(id)
.orElseThrow(() ->
new ResponseStatusException(
HttpStatus.NOT_FOUND));
}FastAPI
A function with a decorator. The type hint int does the conversion and the return type is the response filter.
@router.get("/{order_id}",
response_model=OrderOut)
def get(order_id: int,
svc: OrderSvc = Depends()):
order = svc.find(order_id)
if order is None:
raise HTTPException(404)
return orderThe shift: in Spring the framework reads annotations and a container builds the objects. In FastAPI the framework reads your function signature, and the signature is the contract.
How to read this chapter
The chapter has two halves. The first half is a primer in six sections, each starting with an incident and then opening the mechanism one level down. The second half is a drill of 150 interview questions with collapsed answers.
- Primer, sections 02 to 07: ASGI and the event loop, Pydantic, dependency injection, SQLAlchemy and migrations, security and API behaviour, then testing and deployment. Each primer section ends with named idioms, 26 in total, so you leave with a vocabulary.
- Drill, sections 08 to 11: 150 questions marked K (knowledge), S (scenario) or D (design). Read the question, answer it aloud, then open the answer.
- The running example: QuickBite's orders API. Names such as
OrderCreate,OrderOut,OrderServiceand the route/v1/ordersare the same everywhere, and they match the complete working app in section 07.
Every code block that shows output was run. The tested stack is FastAPI 0.141.1, Starlette 1.6.0, Pydantic 2.13.5, SQLAlchemy 2.0.54 and Python 3.12. FastAPI is still a 0.x library and changes often, so pin the version in your own projects. Where a behaviour changed between versions, the text says "as of 0.141".
If you want to refresh Python itself first, Chapter E19 covers the language (the event loop, threads, context variables), and the Python primer from the AI course covers the basics. This chapter assumes you can read Python and focuses on what changes when the program becomes a service.
02 · ASGI, servers and the event loopFrom Socket to Handler: ASGI, Servers and the Event Loop
A Python web server hands each request to your app through a small standard interface called ASGI. Each server process has one event loop that runs all async def endpoints on one thread, and a pool of 40 threads for plain def endpoints. Knowing that split tells you how many processes to run and which kind of function to write.
Back to QuickBite. After the lunch-time incident the team fixes the blocking call. A week later the dinner rush arrives, and a different graph looks wrong. The VM has 8 CPU cores. During the rush, CPU usage sits at 12% and the requests queue up anyway.
Everyone assumes the server is under-used and has spare room. It is the opposite. The app was started with the command from the tutorial: uvicorn main:app. That starts exactly one process.
One Python process, running async def endpoints, does its Python work on one thread. One thread can use one core at a time. So one core is 100% busy and seven are idle. A graph that averages all eight cores shows 1 / 8 = 12.5%, which is the "12%" the team saw.
Make the invisible visible: how many cores the machine has, and what uvicorn offers to use them.
import os
print("os.cpu_count():", os.cpu_count())
print("one uvicorn process = one event loop = one core of Python work")os.cpu_count(): 12
one uvicorn process = one event loop = one core of Python work --workers INTEGER Number of worker processes. Defaults to the
$WEB_CONCURRENCY environment variable if
--
--loop [auto|asyncio|uvloop|zuvloop]
Event loop factory implementation.
--
--http [auto|h11|httptools|zttp]
HTTP protocol implementation. [default:
--
--http2 Enable HTTP/2 support. Requires --http zttp.
--ws [auto|websockets|websockets-sansio|wsproto]
--
--proxy-headers / --no-proxy-headers
Enable/Disable X-Forwarded-Proto,
--
--limit-concurrency INTEGER Maximum number of concurrent connections or
tasks to allow, before issuing HTTP 503
--
--timeout-graceful-shutdown INTEGER
Maximum number of seconds to wait for
--
--factory Treat APP as an application factory, i.e. a
() -> <ASGI app> callable.The course machine has 12 cores, the team's VM had 8. The fix is one flag. uvicorn main:app --workers 8 starts eight separate processes, each with its own event loop, and the operating system spreads incoming connections across them. The flag reads its default from the WEB_CONCURRENCY environment variable, which many platforms set for you.
Why can't one process just use all the cores? Python's memory management is protected by a lock (the "global interpreter lock", covered in Chapter E19), so two threads cannot run Python code at the same instant. The standard answer is more processes, not more threads.
Before the details of workers, you need to see what the server actually hands to your app. That is the job of ASGI.
Bridge: WSGI to ASGI, one level down
FastAPI is not a web server. A separate program (uvicorn, for example) listens on the port, reads bytes from sockets, parses HTTP, and then calls your application. The rule for that call is a standard, so any server can run any framework. Python has had two such standards.
The older one is WSGI (Web Server Gateway Interface, from 2003). A WSGI application is a plain function: app(environ, start_response). The server passes a dictionary describing the request (environ) and a callback to begin the response. The function returns the body as bytes. When it returns, the request is over.
That shape forces one request per thread. While your function waits for the database, its thread is stuck. Flask and classic Django work this way, and servers such as Gunicorn run many threads or processes to cope.
The newer one is ASGI (Asynchronous Server Gateway Interface). An ASGI application is an async function with three arguments: app(scope, receive, send). It does not return the response. It sends events.
scope: a dictionary describing the connection. Itstypeis"http","websocket"or"lifespan", and it carries the path, method and headers.receive: anasyncfunction. Eachawait receive()returns the next incoming event, such as a chunk of the request body or "client disconnected".send: anasyncfunction. You callawait send(...)once for the response status and headers, and then one or more times for body chunks.
Because the function is a coroutine (a function that can pause at await and let others run), one thread can hold thousands of unfinished requests. Because it exchanges events, the same shape also handles WebSockets and streaming responses, which WSGI cannot do.
What you see: a complete ASGI app with no framework, twelve lines, run through the same test transport FastAPI's tests use. It prints what it receives and what it sends.
import asyncio
import httpx
async def app(scope, receive, send):
print("scope type:", scope["type"], "| path:", scope["path"], "| method:", scope["method"])
event = await receive()
print("received:", event)
await send({"type": "http.response.start", "status": 200,
"headers": [(b"content-type", b"text/plain")]})
await send({"type": "http.response.body", "body": b"hello from raw ASGI"})
print("sent: http.response.start, http.response.body")
async def main():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
r = await c.get("/orders/42")
print("client got:", r.status_code, r.text)
asyncio.run(main())scope type: http | path: /orders/42 | method: GET
received: {'type': 'http.request', 'body': b'', 'more_body': True}
sent: http.response.start, http.response.body
client got: 200 hello from raw ASGIEverything FastAPI does sits on top of this one function. The scope carried type http, the path and the method. The app received one event with the request body (empty here) and sent two events back: a start message with the status and headers, then a body message.
One detail to be honest about: the event shows more_body: True even though the body is empty. That is a habit of httpx's test transport, which sends the body in pieces and ends with a closing event. A real server such as uvicorn sends a single event for a small body with more_body false. The shape (scope, receive, send, two response events) is the same.
Starlette is the library that wraps this raw function into something pleasant: routing, request and response objects, middleware, WebSocket support and a test client. FastAPI is Starlette plus type-hint-driven parameters, Pydantic validation and automatic OpenAPI docs. When you read a stack trace, the lower frames are Starlette (version 1.6.0 on the course machine) and the top frames are yours.
Java · Servlet API
Tomcat calls service() on a thread. The method blocks until the response is written, and then the thread is free.
// illustrative
void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException {
String path = req.getRequestURI();
res.setStatus(200);
res.getWriter().write("hello");
} // thread returns to the pool herePython · ASGI
The server awaits your function. It sends events and can pause at any await without holding a thread.
async def app(scope, receive, send):
path = scope["path"]
await send({
"type": "http.response.start",
"status": 200,
"headers": []})
await send({
"type": "http.response.body",
"body": b"hello"})The shift: a servlet owns a thread until it returns. An ASGI app owns nothing while it waits, so thousands of waiting requests cost almost nothing, but one call that refuses to wait stops all of them.
Servers: who runs the ASGI call
Something has to listen on the port and call your app. You have several choices, and the choice is a deployment decision rather than a coding one, because your FastAPI code does not change.
| Option | Pick it when | Cost or catch |
|---|---|---|
uvicorn (alone, --workers N) | You want the simplest correct setup, especially in containers where Kubernetes restarts pods. | Its built-in worker supervision is basic. It uses uvloop and httptools automatically when they are installed (they are in the course venv). |
| Gunicorn + uvicorn worker class | You run on plain VMs and want a mature process manager: worker recycling after N requests, graceful restarts, timeouts. | Two layers to configure. In recent uvicorn the old uvicorn.workers module warns that it is deprecated and points to the separate uvicorn-worker package, so check what your version expects. |
| Granian | You want a Rust-based server and are willing to benchmark it on your own workload. | Younger ecosystem and fewer production war stories. Not installed in the course venv, so it is described here, not run. |
| Hypercorn | You need HTTP/2 or HTTP/3 support straight from the Python server. | Slower in most benchmarks than uvicorn with uvloop. Most teams terminate HTTP/2 at the load balancer instead. |
| Any of them behind nginx, an ingress or a cloud load balancer | Always, in production. | The proxy handles TLS, slow clients and buffering. Tell the app about it with --proxy-headers so redirects and client IPs are right. |
Switch when: start with uvicorn --workers. Move to Gunicorn when you need its worker recycling or you already run it for other Python services. Try Granian only after you have a load test that shows the server, not your code, is the limit.
Whatever you pick, the process layout is the same, and Figure 20.2 shows it. There is a parent ("master") process that starts the workers and restarts any that die. Each worker is a full copy of your app. Inside each worker there is one event loop and one pool of 40 threads. Workers share nothing, so each one also has its own database connection pool. That last fact matters in the sizing idiom below.
async def endpoints), a pool of 40 threads (all plain def endpoints) and its own database connection pool.Notice two things in the picture. First, the green box, the event loop, is the single lane for all async def work in that process. Second, the pool and the database pool are separate resources: 40 threads can all ask for a database connection at once even though the pool may hold only five. We come back to that mismatch in section 05.
Bridge: the event loop, one level down
To use the rule in the next idiom, you need a plain picture of what the event loop does. Think of one waiter serving a restaurant. The waiter takes an order to the kitchen, and while the kitchen cooks, the waiter does not stand and stare. They go and serve other tables, and come back when the kitchen rings the bell.
The event loop is that waiter. At each await your function says "I have to wait for something (a database reply, a network answer, a timer). Wake me when it is ready." The loop then runs another request's code. One thread, thousands of requests in progress.
Now picture a customer who grabs the waiter's sleeve and says "stay here until my food is ready." That is a blocking call: time.sleep, requests.get, a synchronous database driver, a big CPU computation. The waiter cannot leave. Every other table waits.
You can measure this directly. The program below starts a "heartbeat" task that should wake every 10 milliseconds, then sends 20 requests. It records the longest gap between two heartbeats. If the loop is healthy the gap stays near 10 ms.
import asyncio, time
import httpx
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
app = FastAPI()
def slow_driver_call(): # stands in for requests.get / a sync DB driver
time.sleep(0.1)
@app.get("/bad")
async def bad():
slow_driver_call() # ❌ TRAP: blocks the loop
return {"ok": True}
@app.get("/good")
async def good():
await run_in_threadpool(slow_driver_call) # ✅ one blocking call, off the loop
return {"ok": True}
async def heartbeat(stop, gaps):
last = time.perf_counter()
while not stop.is_set():
await asyncio.sleep(0.01) # should wake up every ~10 ms
now = time.perf_counter()
gaps.append(now - last)
last = now
async def probe(path):
stop, gaps = asyncio.Event(), []
hb = asyncio.create_task(heartbeat(stop, gaps))
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
t0 = time.perf_counter()
await asyncio.gather(*(c.get(path) for _ in range(20)))
total = time.perf_counter() - t0
stop.set(); await hb
print(f"{path:<6} 20 requests in {total:.2f} s | longest gap between heartbeats {max(gaps)*1000:6.0f} ms")
async def main():
await probe("/bad")
await probe("/good")
asyncio.run(main())/bad 20 requests in 2.02 s | longest gap between heartbeats 2023 ms
/good 20 requests in 0.14 s | longest gap between heartbeats 40 msWith the blocking call inside async def, the loop did not wake up for 2,023 milliseconds. Every heartbeat, and every other request or health check, was frozen for two seconds. With run_in_threadpool the longest gap was 40 ms and the 20 requests finished in 0.14 seconds.
Idiom: def versus async def
The problem: an endpoint is declared async def because that looks modern, but it calls a library that blocks. The whole process stalls under load, while CPU and database look idle.
How it works: FastAPI inspects each endpoint. If it is async def, FastAPI awaits it on the event loop. If it is a plain def, FastAPI runs it in a worker thread from AnyIO's thread pool, and the loop stays free. Dependencies follow the same rule. The default pool has 40 threads (we measure it below).
- Ask what you call: does everything you
awaitin this function come from an async library (httpx, asyncpg, an async SQLAlchemy session)? - If yes: use
async def. Waiting is free. - If you call any blocking library: use a plain
def. The threadpool absorbs the wait. - If you must mix: stay in
async defand wrap the one blocking call withawait run_in_threadpool(fn, arg)(oranyio.to_thread.run_sync).
Make the invisible visible: the limit of 40, and what it does to a burst. A plain def endpoint sleeps 0.5 seconds. We send 40, then 41, then 100 requests at once.
import asyncio, time
import anyio.to_thread
import httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/slow")
def slow():
time.sleep(0.5) # plain def: runs in the AnyIO thread pool
return {"ok": True}
async def main():
limiter = anyio.to_thread.current_default_thread_limiter()
print("default thread limiter tokens:", limiter.total_tokens)
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
for n in (40, 41, 100):
t0 = time.perf_counter()
await asyncio.gather(*(c.get("/slow") for _ in range(n)))
print(f"{n:>3} concurrent requests x 0.5 s sleep -> {time.perf_counter()-t0:.2f} s")
asyncio.run(main())default thread limiter tokens: 40
40 concurrent requests x 0.5 s sleep -> 0.54 s
41 concurrent requests x 0.5 s sleep -> 1.02 s
100 concurrent requests x 0.5 s sleep -> 1.57 sThe numbers tell the whole story. 40 requests fit in the pool at once, so the batch takes one wait, 0.54 seconds. One more request (41) needs a second wave, so the time doubles to 1.02 seconds. 100 requests need three waves (40, 40, 20): about 1.5 seconds, and we measured 1.57.
That is the arithmetic you can do in an interview: time ≈ ceil(requests / 40) × work time. If each request really waits 0.5 seconds and 400 arrive per second, you need 400 × 0.5 = 200 threads busy at once, and one worker only has 40. Either more workers, or an async library that does not need a thread per wait.
Here is the fix from the first incident, in code. The wrong version blocks the loop. The two right versions differ only in who does the waiting.
# illustrative: not run, the output is the earlier measurements
import requests # blocking HTTP library
import httpx # has an async client
from fastapi.concurrency import run_in_threadpool
@router.get("/bad")
async def bad():
r = requests.get(URL) # ❌ TRAP: blocks the loop
return r.json()
@router.get("/fix-1")
def fix_1(): # ✅ plain def: threadpool
return requests.get(URL).json()
@router.get("/fix-2")
async def fix_2(client: httpx.AsyncClient = Depends(get_client)):
r = await client.get(URL) # ✅ truly async
return r.json()
@router.get("/fix-3")
async def fix_3(): # ✅ one blocking call, wrapped
r = await run_in_threadpool(requests.get, URL)
return r.json()- Works:
deffor code that uses synchronous SQLAlchemy,requests, file I/O or any library without async support.async deffor calls through httpx, async database drivers and message clients. - Fails:
async defplus a blocking call (stalls everyone). A huge CPU job in either kind (async defblocks the loop,defhogs the interpreter lock, so use a process pool or a worker queue). Also: assumingdefis infinite, because the pool stops at 40 threads. - Interview takeaway: "
async defonly if everything I await is non-blocking; otherwise a plaindef, which FastAPI runs in a 40-thread pool. I never block insideasync def, and for one stray blocking call I wrap it inrun_in_threadpool."
Java · Tomcat
Each request gets a platform thread (up to 200 by default). A blocking call costs one thread, nobody else is blocked.
// illustrative
@GetMapping("/slow")
public String slow() throws Exception {
Thread.sleep(100); // only this thread waits
return "ok";
}
// server.tomcat.threads.max=200 (default)
// or virtual threads: one per request, cheapPython · uvicorn
All async def requests share one thread. Plain def requests share 40 pool threads.
@app.get("/slow-bad")
async def slow_bad():
time.sleep(0.1) # ❌ everyone waits
return "ok"
@app.get("/slow-ok")
def slow_ok():
time.sleep(0.1) # ✅ only this thread
return "ok"The shift: in Tomcat a blocking call is always safe, because every request has its own thread. In FastAPI the first line of the function, def or async def, decides whether a blocking call is safe.
Java 21 virtual threads narrow the gap: a virtual thread that blocks on I/O is parked cheaply, so Spring Boot can also serve many waiting requests. The difference that remains is the failure mode. A blocking call on a Java virtual thread costs little. A blocking call on the Python event loop stops everything.
Bridge: routing, one level down
The router is box 5 in Figure 20.1. It holds a list of routes and, for each request, walks the list from the top and picks the first route whose path and method match. That one sentence explains a very common bug.
QuickBite wants a "latest order" shortcut. A developer adds GET /orders/latest below the existing GET /orders/{order_id}. In testing, /orders/latest does not work. Here is the real behaviour.
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/orders/{order_id}") # registered FIRST
def get_order(order_id: int):
return {"route": "get_order", "order_id": order_id}
@app.get("/orders/latest") # ❌ TRAP: never reached
def latest():
return {"route": "latest"}
c = TestClient(app)
r = c.get("/orders/latest")
print(r.status_code, r.json())422 {'detail': [{'type': 'int_parsing', 'loc': ['path', 'order_id'], 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'latest'}]}The request for /orders/latest matched the first route, because {order_id} accepts any text. FastAPI then tried to convert "latest" to an int and answered 422. The "latest" route is never reached. If order_id had been declared str, the request would have succeeded silently with the wrong handler, which is worse.
The fix: register the specific route first. Put fixed paths (/orders/latest) above paths with variables (/orders/{order_id}).
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/orders/latest") # ✅ specific route first
def latest():
return {"route": "latest"}
@app.get("/orders/{order_id}")
def get_order(order_id: int):
return {"route": "get_order", "order_id": order_id}
c = TestClient(app)
print(c.get("/orders/latest").json())
print(c.get("/orders/42").json()){'route': 'latest'}
{'route': 'get_order', 'order_id': 42}Now the rules for where each parameter comes from. FastAPI reads your function signature and decides by simple rules:
- Path: the name appears inside
{braces}in the route path. - Body: the type is a Pydantic model (or you use
Body()). Several body parameters are nested under their names. - Query: anything else with a simple type (
int,str,bool) and not in the path. - Header and cookie: only when you say so with
Header()orCookie(). Underscores in a header parameter turn into hyphens (x_client_versionreadsX-Client-Version).
from typing import Annotated
from fastapi import FastAPI, Header, Cookie, Query, Path
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Note(BaseModel):
text: str
app = FastAPI()
@app.post("/orders/{order_id}/notes")
def add_note(
order_id: Annotated[int, Path(gt=0)], # in the path template -> path
note: Note, # a Pydantic model -> JSON body
notify: bool = False, # simple type, not in path -> query
x_client_version: Annotated[str | None, Header()] = None, # explicit -> header (x_client_version -> X-Client-Version)
session: Annotated[str | None, Cookie()] = None, # explicit -> cookie
):
return {"order_id": order_id, "note": note.text, "notify": notify,
"version": x_client_version, "session": session}
c = TestClient(app)
r = c.post("/orders/9/notes?notify=true", json={"text": "no onions"},
headers={"X-Client-Version": "3.2"}, cookies={"session": "abc"})
print(r.json()){'order_id': 9, 'note': 'no onions', 'notify': True, 'version': '3.2', 'session': 'abc'}All five sources arrive in one function call. Each failure is a 422 that names the place (loc starts with path, query, header, cookie or body), which makes client bugs easy to find.
Three more routing details to know. Status codes are set on the decorator (status_code=201), not in the body. response_model filters and documents the output (section 03). responses={404: {...}} adds extra documented outcomes to the OpenAPI page without changing behaviour. Larger apps split routes into files with APIRouter(prefix="/v1/orders", tags=["orders"]) and attach them with app.include_router(...); section 04 shows the layout.
Bridge: middleware, the onion
Middleware is code that wraps every request: it runs before your endpoint, calls the next layer, and runs again on the way back. Typical jobs are timing, request ids, compression and CORS headers. If you know servlet filters, this is the same idea.
The picture is an onion. The request enters through the outer layer and moves inward until it reaches the endpoint. The response then travels back out through the same layers in reverse. The question that trips people up is the order, so here is a run with two middlewares that print when they start and finish.
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
app = FastAPI()
@app.middleware("http")
async def first(request: Request, call_next): # registered first
print(" first : before")
response = await call_next(request)
print(" first : after")
return response
@app.middleware("http")
async def second(request: Request, call_next): # registered second
print(" second : before")
response = await call_next(request)
print(" second : after")
return response
@app.get("/ping")
def ping():
print(" endpoint runs")
return {"ok": True}
TestClient(app).get("/ping") second : before
first : before
endpoint runs
first : after
second : afterThe middleware registered last (second) ran first on the way in. Each new @app.middleware or add_middleware call wraps the existing stack, so the newest layer becomes the outermost one. On the way out the order reverses: first finished before second.
Idiom: Middleware as an onion
The problem: cross-cutting code (timing, request ids, CORS, compression) is copied into endpoints, or added as middleware in the wrong order. A logging layer that sits inside the error layer never sees errors, and a layer that reads the body breaks the endpoint.
How it works: each layer receives the request and a handle to "the rest of the app". It does something, calls the rest, and may do something with the response. The newest registered layer is outermost.
- Decide what must be outermost: request id and timing go outermost so they cover everything. Error-to-response conversion goes just outside the endpoint.
- Register in reverse: the one you want outermost is added last.
- Prefer pure ASGI for hot paths: a class with
__call__(scope, receive, send)adds almost no cost. The decorator@app.middleware("http")uses Starlette'sBaseHTTPMiddleware, which is easier to write but heavier.
Make the invisible visible: the cost of each style. The program sends 3,000 requests to a trivial endpoint with no middleware, a do-nothing pure ASGI middleware, and a do-nothing decorator middleware.
import asyncio, time
import httpx
from fastapi import FastAPI, Request
def make(kind):
app = FastAPI()
if kind == "http-decorator":
@app.middleware("http")
async def mw(request: Request, call_next): # BaseHTTPMiddleware under the hood
return await call_next(request)
elif kind == "pure-asgi":
class Pass:
def __init__(self, app): self.app = app
async def __call__(self, scope, receive, send):
await self.app(scope, receive, send)
app.add_middleware(Pass)
@app.get("/ping")
async def ping():
return {"ok": True}
return app
async def bench(kind, n=3000):
transport = httpx.ASGITransport(app=make(kind))
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
for _ in range(200): await c.get("/ping")
t = time.perf_counter()
for _ in range(n): await c.get("/ping")
return (time.perf_counter() - t) / n * 1e6
async def main():
for kind in ("none", "pure-asgi", "http-decorator"):
print(f"{kind:<15}{await bench(kind):7.0f} microseconds per request")
print("# measured on the course machine (12 cores); your numbers will differ")
asyncio.run(main())none 194 microseconds per request
pure-asgi 190 microseconds per request
http-decorator 359 microseconds per request
# measured on the course machine (12 cores); your numbers will differThe pure ASGI layer cost nothing measurable (190 against 194 microseconds is noise). The decorator style added about 165 microseconds per request, because BaseHTTPMiddleware runs your endpoint in a separate task and wraps the response in a stream. At 1,000 requests per second that is about 16% of one core. Worth knowing, rarely a deal breaker. The bigger concern is behaviour, not speed: BaseHTTPMiddleware has had edge cases with streaming responses and with background tasks in some versions, so test them if you rely on either.
The trap: reading the body in middleware
A request body is a stream. It arrives in chunks through receive(), and once a chunk is taken, it is gone unless somebody puts it back. A middleware that "just logs the body" can steal it from the endpoint.
The demo below uses a pure ASGI middleware that takes the first message from receive() and passes the app on without replaying it.
import asyncio
import httpx
from fastapi import FastAPI, Request
from pydantic import BaseModel
class Item(BaseModel):
qty: int
app = FastAPI()
class PeekBody: # pure ASGI middleware, naive version
def __init__(self, app): self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] == "http":
msg = await receive() # ❌ TRAP: takes the body message, never hands it on
print("middleware peeked:", msg["body"])
await self.app(scope, receive, send)
app.add_middleware(PeekBody)
@app.post("/items")
async def create(item: Item):
return item
async def main():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
try:
r = await asyncio.wait_for(c.post("/items", json={"qty": 2}), timeout=2)
print("status:", r.status_code, r.text)
except asyncio.TimeoutError:
print("endpoint still waiting for a body after 2 s: the request hangs")
asyncio.run(main())middleware peeked: b'{"qty":2}'
status: 422 {"detail":[{"type":"missing","loc":["body"],"msg":"Field required","input":null}]}The middleware printed the body, and the endpoint then saw nothing: a 422 "Field required" for the body. This test transport delivers the body in two messages: the data chunk (marked more_body=True) and then an empty closing message. This middleware read only the first one, so the endpoint received just the empty closing message, saw no JSON and answered 422.
Q9 shows the other outcome: a middleware that drains both messages leaves the endpoint waiting for a message that never comes, so the request hangs. Same mistake, different symptom, depending on how much the middleware consumed. A real server behaves like the hang case when the whole body is gone.
Starlette's own Request.body() caches what it reads, so the decorator style often "works", which hides the problem until you write a pure ASGI layer. The safer habits are: do not read bodies in middleware; log the parsed model inside the endpoint or in a dependency; and if you truly must, wrap receive so that you replay the same message afterwards.
- Works: middleware for things that need no body: request ids, timing, security headers, CORS, GZip, access logs with path and status.
- Fails: reading or validating bodies in middleware, doing slow work (a database call) in a layer that runs on every request, and registering layers in the wrong order so the outer one never sees what the inner one did.
- Interview takeaway: "Middleware is an onion where the last one added runs first on the way in. I keep it for body-free cross-cutting work, write hot ones as pure ASGI, and I never consume the request body there, because the endpoint's stream would be empty."
Bridge: OpenAPI, generated from your code
FastAPI builds an OpenAPI document (a standard JSON description of every route, parameter and model) from the same things it uses at runtime: your routes and your type hints. The pages /docs (Swagger UI) and /redoc are viewers for that document, and /openapi.json serves it.
You can see it without a browser by calling app.openapi(). This is the output for a one-route app with an OrderCreate model, plus a debug route that is hidden with include_in_schema=False.
import json
from fastapi import FastAPI
from pydantic import BaseModel, Field
class OrderCreate(BaseModel):
restaurant_id: int
qty: int = Field(gt=0, le=50)
app = FastAPI(title="QuickBite", version="1.0.0")
@app.post("/v1/orders", status_code=201, tags=["orders"])
def create(body: OrderCreate): ...
@app.get("/internal/debug", include_in_schema=False)
def debug(): ...
spec = app.openapi()
print("openapi:", spec["openapi"])
print("paths:", list(spec["paths"]))
print(json.dumps(spec["components"]["schemas"]["OrderCreate"], indent=2))openapi: 3.1.0
paths: ['/v1/orders']
{
"properties": {
"restaurant_id": {
"type": "integer",
"title": "Restaurant Id"
},
"qty": {
"type": "integer",
"maximum": 50.0,
"exclusiveMinimum": 0.0,
"title": "Qty"
}
},
"type": "object",
"required": [
"restaurant_id",
"qty"
],
"title": "OrderCreate"
}Three things to notice. The hidden debug route is absent from paths, though it still works if called. The Field(gt=0, le=50) constraints on qty became exclusiveMinimum and maximum in the schema, so a generated client knows the limits. And the schema is only as accurate as your models: an endpoint without a response_model documents nothing about its output.
Because the document is generated, it cannot drift from the code, which is the main reason teams pick FastAPI. In production many teams turn /docs off or protect it (FastAPI(docs_url=None)), since it lists every route, including internal ones.
Idiom: Sizing workers and their pools
The problem: either too few processes (CPU idle, queues build up, as in the dinner rush) or too many, so that workers multiplied by pods multiplied by pool size exceeds what the database allows and new connections are refused.
How it works: each worker is a separate process with its own event loop, thread pool and database pool. So the numbers multiply. Count connections from the database's side, not from one process's side.
- Start with workers ≈ cores for an I/O-bound API that does little CPU work per request. In containers, give each pod 1 or 2 workers and add pods to scale, so Kubernetes (not the process manager) does the scaling and restarting. See Chapter E10.
- Count connections: total = workers × pods × (pool_size + max_overflow).
- Compare with the database limit: PostgreSQL's default
max_connectionsis 100, and a few are reserved for admin use. Stay well under it, or put a pooler such as PgBouncer in front (see pool sizing in section 05). - Count memory: every worker holds its own copy of the code, models and caches. Many FastAPI services use roughly 80 to 150 MB per worker, but measure yours.
| Layout | Workers × pods | Pool per worker | Max connections | Against Postgres default of 100 |
|---|---|---|---|---|
| Laptop | 1 × 1 | 10 | 10 | fine |
| One VM, 8 cores | 8 × 1 | 10 | 80 | close to the limit |
| Small cluster | 2 × 3 | 10 | 60 | fine |
| Bigger layout | 3 × 4 | 10 | 120 | over the limit: new connections fail |
| After scaling to 20 pods | 2 × 20 | 10 | 400 | far over: needs a pooler or smaller pools |
| Fixed with smaller pools | 2 × 20 | 3 + 2 = 5 | 200 | still over: PgBouncer or a bigger database |
Notice the trap in the last rows: scaling the app out is a database event too. Adding pods multiplies the connections, even though no code changed. The usual answer is a pooler that multiplexes many app connections onto a few real ones, plus smaller per-worker pools.
- Works: workers near the core count, pods for scale, a connection budget written down and checked against the database limit before each scale-out.
- Fails: one process on a big machine; the same worker count copied from a laptop to 20 pods; CPU-heavy endpoints that need processes of their own (move them to a job queue).
- Interview takeaway: "One worker is one event loop and one core, so I run about one worker per core, and I budget database connections as workers times pods times pool size against the database's max, because scaling out multiplies them."
The other scope types: lifespan, streaming and WebSockets
So far every call had scope["type"] == "http". ASGI defines two more, and FastAPI uses both. One is "websocket", for long-lived two-way connections. The other is "lifespan", a special call that the server makes once when the process starts and once when it stops. It carries no request at all. It exists so your app can open resources at start-up and close them at shutdown. Section 04 builds on it.
The program below puts a do-nothing, printing middleware at the front of an app with a streaming route and a WebSocket route. Entering the test client's with block triggers start-up, and leaving it triggers shutdown.
from fastapi import FastAPI, WebSocket
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
from starlette.types import ASGIApp, Receive, Scope, Send
class ShowScopes: # pure ASGI middleware that only prints
def __init__(self, app: ASGIApp): self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send):
print("scope type:", scope["type"])
await self.app(scope, receive, send)
app = FastAPI()
app.add_middleware(ShowScopes)
@app.get("/stream")
def stream():
return StreamingResponse((f"chunk {i}\n" for i in range(3)), media_type="text/plain")
@app.websocket("/ws")
async def ws(sock: WebSocket):
await sock.accept()
await sock.send_text("hi")
await sock.close()
with TestClient(app) as c: # entering the block runs startup
print(c.get("/stream").text.split())
with c.websocket_connect("/ws") as s:
print("websocket says:", s.receive_text())
# leaving the block runs shutdownscope type: lifespan
scope type: http
['chunk', '0', 'chunk', '1', 'chunk', '2']
scope type: websocket
websocket says: hiRead the output top to bottom. The first call was lifespan, before any request. The streaming route was an ordinary http call whose body arrived in three pieces, because a streaming response sends several http.response.body events instead of one. The WebSocket connection was a separate websocket scope, and it could send messages without a new request.
This is also where the event loop idea pays off. A server-sent-events stream or a WebSocket can stay open for minutes. If each open connection held a thread, 5,000 live customers would need 5,000 threads. On the event loop an idle connection is just a paused coroutine and costs a few kilobytes. The price is the same rule as before: while the loop is serving those connections, nothing on it may block.
Two practical consequences follow. A middleware written as pure ASGI sees all three scope types and should check scope["type"] before using HTTP-only keys such as method. And a long-lived stream is a good reason to prefer async def with an async library: you pay almost nothing per idle connection, and you can still send each client a heartbeat so that proxies do not close the connection for being quiet.
03 · Pydantic v2Validation and Serialisation with Pydantic v2
Pydantic turns untrusted input into typed Python objects, and turns your objects back into safe JSON. It both checks and converts, which is the part that surprises Java developers. Use three separate models (request, response, database) and each of the traps below disappears.
Two weeks after launch, QuickBite's mobile team reports that some orders arrive with strange quantities. The order line model was declared like this: qty: int. A customer's older app version sent "qty": "2", a string. The server accepted it and ordered two biryanis.
The backend team was relieved but also confused. Another client sent "qty": 2.7 and got an error. One string was accepted, one float was refused. What are the rules?
Nobody on the team could say, and that is the problem. A validation library that converts silently is a library whose rules you must know by heart. The first demo below stops guessing and runs the three inputs.
from pydantic import BaseModel, ValidationError
class OrderLineIn(BaseModel):
menu_item_id: int
qty: int
for raw in ({"menu_item_id": 1, "qty": 2},
{"menu_item_id": 1, "qty": "2"},
{"menu_item_id": 1, "qty": 2.7}):
try:
print(repr(raw["qty"]).ljust(5), "->", OrderLineIn.model_validate(raw))
except ValidationError as e:
err = e.errors()[0]
print(repr(raw["qty"]).ljust(5), "-> ValidationError:", err["type"], "|", err["msg"])2 -> menu_item_id=1 qty=2
'2' -> menu_item_id=1 qty=2
2.7 -> ValidationError: int_from_float | Input should be a valid integer, got a number with a fractional partThe string "2" was converted to the integer 2. The float 2.7 was rejected, because it has a fractional part and converting would lose information. The default mode is called lax: accept anything that can be converted without loss.
The second incident arrives in the same week. The order-status endpoint (PATCH) had a model with two optional fields, status and delivery_note. A client sent only {"status": "PREPARING"}. The server then wrote null into delivery_note and the customer's note, "ring twice", vanished. Both incidents have the same root: the team did not know what Pydantic does on the way in.
Bridge: what Pydantic does, one level down
Pydantic reads your type hints and builds a validator. Handed a dictionary or a JSON string, it parses (finds each field), validates (checks types and constraints) and converts (turns "2" into 2 and an ISO date string into a datetime). The result is an object whose fields have the right Python types, or a ValidationError listing every problem, not just the first.
Version 2 (2023) moved the checking into pydantic-core, a library written in Rust. The model class you write is still plain Python, but the work of walking the data happens in compiled code. Version 1 did all of it in Python. The result is typically many times faster, and the API changed in places: .dict() became .model_dump(), @validator became @field_validator, Config became model_config. Old tutorials still show v1 code, so check the version of any snippet you copy.
FastAPI uses Pydantic at the door. Whatever you declare as a parameter or body is validated before your function runs. If validation fails, your function never runs and the client gets a 422. Here is the exact body, produced by a test client for an order with two mistakes.
import json
from typing import Annotated
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
Qty = Annotated[int, Field(gt=0, le=50)]
class OrderLineIn(BaseModel):
menu_item_id: int
qty: Qty
class OrderCreate(BaseModel):
restaurant_id: int
lines: list[OrderLineIn] = Field(min_length=1)
app = FastAPI()
@app.post("/v1/orders", status_code=201)
def create_order(body: OrderCreate):
return {"accepted": len(body.lines)}
c = TestClient(app)
r = c.post("/v1/orders", json={"restaurant_id": "x", "lines": [{"menu_item_id": 1, "qty": 2.7}]})
print(r.status_code)
print(json.dumps(r.json(), indent=2))422
{
"detail": [
{
"type": "int_parsing",
"loc": [
"body",
"restaurant_id"
],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "x"
},
{
"type": "int_from_float",
"loc": [
"body",
"lines",
0,
"qty"
],
"msg": "Input should be a valid integer, got a number with a fractional part",
"input": 2.7
}
]
}Two mistakes, two entries. Each has a type (a stable code you can branch on), a loc (where: body, then the path inside it, with list positions as numbers), a human-readable msg and the offending input. Clients should rely on type and loc, not on the English message.
Lax and strict: what becomes what
Lax mode is friendly for JSON, because JSON has no way to say "this is an integer" for a form field or a query string. But it can be too friendly for money and quantities. The table in Figure 20.4 comes from running the same int field in both modes.
from pydantic import BaseModel, ConfigDict, ValidationError
class Lax(BaseModel):
n: int
class Strict(BaseModel):
model_config = ConfigDict(strict=True)
n: int
def probe(model, value):
try:
return repr(model(n=value).n)
except ValidationError as e:
return "error: " + e.errors()[0]["type"]
print(f"{'input':<9}{'lax':<28}{'strict=True'}")
for v in ("42", 42.0, 42.5, True, " 42 ", "4e1", None):
print(f"{v!r:<9}{probe(Lax, v):<28}{probe(Strict, v)}")input lax strict=True
'42' 42 error: int_type
42.0 42 error: int_type
42.5 error: int_from_float error: int_type
True 1 error: int_type
' 42 ' 42 error: int_type
'4e1' error: int_parsing error: int_type
None error: int_type error: int_typeint field, taken from the program above. The one lax result worth remembering is that True becomes 1.When do you pick which? For a public JSON API with many client versions, lax is usually fine and friendlier, as long as you constrain the range (next idiom). For internal service-to-service calls where both sides are your code, strict catches mistakes earlier. You can set it per model (ConfigDict(strict=True)), per field, or for one call (model_validate(data, strict=True)).
One gotcha: strict mode applies to what arrives from JSON in Python terms. For JSON input, Pydantic's strict mode is a bit more forgiving about dates and UUIDs (which JSON can only express as strings), so test the type you care about, don't assume.
Idiom: Annotated constraints as reusable types
The problem: the rule "a quantity is 1 to 50" is written as Field(gt=0, le=50) in four models. Someone changes one to 100, the others drift, and the API accepts different limits on different endpoints.
How it works: Annotated[int, Field(...)] attaches rules to a type. Give the result a name and reuse it. Pydantic checks the rules after the type conversion, and FastAPI copies them into the OpenAPI schema.
- Name the business concept:
Qty,Cents,Phone, not "a number between 1 and 50". - Define it once: in one module (
app/schemas.pyin the QuickBite app). - Use it everywhere:
qty: Qty. Tighten the rule in one place and every model follows.
# illustrative: the same rule, copied
class OrderLineIn(BaseModel):
qty: int = Field(gt=0, le=50)
class CartLine(BaseModel):
qty: int = Field(gt=0, le=100) # ❌ TRAP: drifted to 100from typing import Annotated
from pydantic import BaseModel, Field, ValidationError
Qty = Annotated[int, Field(gt=0, le=50)]
Cents = Annotated[int, Field(ge=0)]
Phone = Annotated[str, Field(pattern=r"^\+91[0-9]{10}$")]
class OrderLineIn(BaseModel):
menu_item_id: int
qty: Qty
price_cents: Cents
class Contact(BaseModel):
phone: Phone
for model, data in ((OrderLineIn, {"menu_item_id": 1, "qty": 0, "price_cents": 24900}),
(OrderLineIn, {"menu_item_id": 1, "qty": 51, "price_cents": -5}),
(Contact, {"phone": "98450 12345"})):
try:
model.model_validate(data)
except ValidationError as e:
for err in e.errors():
print(err["loc"], err["type"], "|", err["msg"])('qty',) greater_than | Input should be greater than 0
('qty',) less_than_equal | Input should be less than or equal to 50
('price_cents',) greater_than_equal | Input should be greater than or equal to 0
('phone',) string_pattern_mismatch | String should match pattern '^\+91[0-9]{10}$'- Works: numeric ranges, string lengths, regex patterns, list sizes (
Field(min_length=1)), and money as integer cents (Cents). Errors name the exact rule:greater_than,less_than_equal,string_pattern_mismatch. - Fails: rules that depend on two fields (use a model validator, below), or on the database ("is this restaurant open?"), which belongs in the service, not in the model. Also, a regex is not a full phone-number check; it only shapes the input.
- Interview takeaway: "I name every constrained value once with
Annotated[int, Field(...)], such asQtyorCents, so limits live in one place and show up in the OpenAPI schema."
Validators: when a constraint is not enough
Sometimes a rule cannot be written as a range. For those, Pydantic gives you two decorators. @field_validator checks or cleans one field. @model_validator sees the whole object, so it can compare fields.
Each can run at a different time, called its mode:
- before: runs on the raw input, before type conversion. Use it to clean data (trim spaces, accept
""as missing). - after: runs on the already-typed value. Use it for checks that need the real type. This is the default and the safest.
- wrap: receives the raw value and a
handlerthat runs the normal validation. You decide what to do before, after, or when it fails.
The QuickBite order model uses both kinds: it cleans a coupon code before checking, and it refuses an order with no lines after all fields are valid.
from typing import Annotated, Self
from pydantic import (BaseModel, Field, ValidationError, field_validator,
model_validator)
Qty = Annotated[int, Field(gt=0, le=50)]
class OrderLineIn(BaseModel):
menu_item_id: int
qty: Qty
class OrderCreate(BaseModel):
restaurant_id: int
lines: list[OrderLineIn]
coupon: str | None = None
@field_validator("coupon", mode="before") # runs BEFORE type checking
@classmethod
def clean_coupon(cls, v):
return v.strip().upper() if isinstance(v, str) and v.strip() else None
@model_validator(mode="after") # runs after all fields are valid
def at_least_one_line(self) -> Self:
if not self.lines:
raise ValueError("an order needs at least one line")
return self
print(OrderCreate(restaurant_id=3, lines=[{"menu_item_id": 1, "qty": 2}], coupon=" diwali10 "))
print(OrderCreate(restaurant_id=3, lines=[{"menu_item_id": 1, "qty": 2}], coupon=" ").coupon)
try:
OrderCreate(restaurant_id=3, lines=[])
except ValidationError as e:
err = e.errors()[0]
print(err["loc"], err["type"], "|", err["msg"])restaurant_id=3 lines=[OrderLineIn(menu_item_id=1, qty=2)] coupon='DIWALI10'
None
() value_error | Value error, an order needs at least one lineThe coupon " diwali10 " arrived with spaces and lower case and left as 'DIWALI10'. An all-spaces coupon became None. The empty lines list failed with a value error whose loc is empty, because the problem belongs to the whole model, not to one field.
A wrap validator is rarer. This one lets the normal integer check run and, if it fails, substitutes 1. It is shown only to make the mechanism visible, since silently fixing bad input is usually a bad idea for orders.
from typing import Annotated
from pydantic import BaseModel, ValidationError, WrapValidator
def clamp_or_fail(value, handler):
try:
return handler(value) # run the normal int check
except ValidationError:
print(" wrap saw a failure for", repr(value), "-> using 1")
return 1
SafeQty = Annotated[int, WrapValidator(clamp_or_fail)]
class Line(BaseModel):
qty: SafeQty
print(Line(qty="3"))
print(Line(qty="three"))qty=3
wrap saw a failure for 'three' -> using 1
qty=1Remember where the line is. Pydantic validators should be pure: no database calls, no network. "The restaurant must be open" needs data from outside the request, so it belongs in the service layer (section 04), where it can raise a proper domain error with a 409.
Bridge: one entity, three models
Go back to the leak in section 01. The customer row has a password_hash column. The endpoint returned the whole row. The fix was a second class, CustomerOut, that lists only the fields a client may see. That is the whole idea, and QuickBite applies it to every entity.
An order exists in three shapes, and each shape has a different job:
- Request model (
OrderCreate): what the client may send. It has noid, nostatus, nototal_cents. A client must not be able to choose its own price or id. - ORM model (
Order): the database row, with every column, including internal ones. It never leaves the server. - Response model (
OrderOut): what the client may read. It lists fields explicitly, so a new column added to the table does not appear in the API by accident.
OrderCreate, the service works with the ORM row, and OrderOut is the only shape that reaches the client. The shortcut from the row straight to the response is the leak path from section 01.Pydantic can read attributes from an object (instead of dictionary keys) when you set from_attributes=True. That is the bridge from the ORM row to the response model. In the program below, the "ORM" classes are plain stand-ins, so the demo has no database. The row has an extra internal_note attribute that must never leave.
Idiom: Separate input and output models
The problem: one class is used for the request, the database and the response. Adding a column leaks it. A client can send id or status and overwrite them. Renaming a database column breaks every client.
How it works: three classes per entity with different fields. The endpoint accepts OrderCreate, the service builds an ORM Order, and response_model=OrderOut filters the result on the way out.
- Write the request model: only fields the client controls.
- Write the response model: every field you are happy to publish, with
from_attributes=True. - Declare it on the route:
response_model=OrderOut. FastAPI validates the returned value against it and drops everything else.
Make the invisible visible: the "with" side. Here the response model is built from the object, and the internal note is not in the output.
from datetime import datetime, timezone
from pydantic import BaseModel, ConfigDict
# --- stand-ins for the SQLAlchemy ORM objects (app/models.py) ---
class OrderLine:
def __init__(self, menu_item_id, qty, price_cents):
self.menu_item_id, self.qty, self.price_cents = menu_item_id, qty, price_cents
class Order:
def __init__(self):
self.id = 1001
self.customer_id = 7
self.restaurant_id = 3
self.status = "PLACED"
self.total_cents = 49800
self.created_at = datetime(2026, 11, 24, 12, 30, tzinfo=timezone.utc)
self.lines = [OrderLine(1, 2, 24900)]
self.internal_note = "customer is a VIP, comp a dessert" # must never leave
# --- response models (app/schemas.py) ---
class OrderLineOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
menu_item_id: int
qty: int
price_cents: int
class OrderOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
customer_id: int
restaurant_id: int
status: str
total_cents: int
created_at: datetime
lines: list[OrderLineOut]
out = OrderOut.model_validate(Order())
print(out.model_dump_json(indent=2))
print("internal_note in output?", "internal_note" in out.model_dump()){
"id": 1001,
"customer_id": 7,
"restaurant_id": 3,
"status": "PLACED",
"total_cents": 49800,
"created_at": "2026-11-24T12:30:00Z",
"lines": [
{
"menu_item_id": 1,
"qty": 2,
"price_cents": 24900
}
]
}
internal_note in output? FalseThe "without" side is the naive endpoint from section 01, which returned password_hash. Note two more benefits visible above. The created_at datetime was written as ISO 8601 text with a timezone (2026-11-24T12:30:00Z). And money stayed an integer in cents, never a float.
- Works: every public endpoint. Renaming a database column or adding an internal column changes nothing for clients. Different views of one entity (
OrderOutfor customers,OrderAdminOutfor support) are just more response models. - Fails: skipping the response model "because it is internal". Internal endpoints become external. Also,
response_modelwithfrom_attributesreads lazy-loaded relationships, which can trigger extra queries (section 05 shows the cost). - Interview takeaway: "I never return an ORM object without a response model. Request model, ORM model and response model are three classes, so a new column can't leak and a client can't set fields it doesn't own."
Bridge: serialisation, one level down
Going out, model_dump() turns a model into a dictionary and model_dump_json() into a JSON string. Four options cover almost every need:
mode="json": convert everything to JSON-safe types (datetime to text, Decimal to text). The defaultmode="python"keeps Python types.exclude_unset=True: keep only the fields that were explicitly provided when the model was created. This fixes the PATCH incident below.exclude_none=True: drop fields whose value isNone.by_alias=True: use the alias names (such as camelCase) instead of the Python field names.
The PATCH incident, solved
Remember the customer note that vanished. The endpoint copied every field of the update model into the database, and omitted fields were None. The two endpoints below differ by one argument.
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class OrderStatusUpdate(BaseModel):
status: str | None = None
delivery_note: str | None = None
DB = {"status": "PLACED", "delivery_note": "ring twice"}
app = FastAPI()
@app.patch("/naive")
def naive(body: OrderStatusUpdate):
DB.update(body.model_dump()) # ❌ TRAP: includes omitted fields as None
return DB
@app.patch("/fixed")
def fixed(body: OrderStatusUpdate):
DB.update(body.model_dump(exclude_unset=True)) # ✅ only what the client sent
return DB
c = TestClient(app)
print("client sends: {'status': 'PREPARING'}")
print("naive result: ", c.patch("/naive", json={"status": "PREPARING"}).json())
DB.update(status="PLACED", delivery_note="ring twice")
print("fixed result: ", c.patch("/fixed", json={"status": "PREPARING"}).json())
print("explicit null: ", c.patch("/fixed", json={"delivery_note": None}).json())client sends: {'status': 'PREPARING'}
naive result: {'status': 'PREPARING', 'delivery_note': None}
fixed result: {'status': 'PREPARING', 'delivery_note': 'ring twice'}
explicit null: {'status': 'PREPARING', 'delivery_note': None}With exclude_unset=True, only status was updated and the note survived. The last line shows the useful side effect: when a client explicitly sends null for the note, "unset" and "set to null" are different things, so the note is cleared on purpose. (Section 06 uses this in the full partial-update idiom.)
CamelCase on the wire, snake_case in the code
JavaScript clients prefer deliveryNote. Python style is delivery_note. You do not need two sets of models. An alias generator creates the camelCase names, and populate_by_name=True keeps the Python names usable inside your code.
from datetime import datetime, timezone, timedelta
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, computed_field, field_serializer
from pydantic.alias_generators import to_camel
class OrderLineOut(BaseModel):
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
menu_item_id: int
qty: int
price_cents: int
@computed_field
@property
def line_total_cents(self) -> int:
return self.qty * self.price_cents
class OrderOut(BaseModel):
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
id: int
total_cents: int
delivery_note: str | None = None
created_at: datetime
lines: list[OrderLineOut]
@field_serializer("created_at")
def as_utc(self, v: datetime) -> str: # one timezone on the wire
return v.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
# camelCase in
o = OrderOut.model_validate({
"id": 1, "totalCents": 49800,
"createdAt": "2026-11-24T18:00:00+05:30",
"lines": [{"menuItemId": 1, "qty": 2, "priceCents": 24900}],
})
print("python side: ", o.total_cents, o.created_at.isoformat(), o.lines[0].menu_item_id)
print("by_alias=True:", o.model_dump_json(by_alias=True))
print("no alias: ", o.model_dump_json())
print("exclude_none: ", o.model_dump(mode="json", exclude_none=True, by_alias=True).keys())
class Stamp(BaseModel):
at: datetime
price: Decimal
st = Stamp(at=datetime(2026, 11, 24, 12, 30, tzinfo=timezone.utc), price=Decimal("249.00"))
print("mode=python:", st.model_dump())
print("mode=json: ", st.model_dump(mode="json"))python side: 49800 2026-11-24T18:00:00+05:30 1
by_alias=True: {"id":1,"totalCents":49800,"deliveryNote":null,"createdAt":"2026-11-24T12:30:00Z","lines":[{"menuItemId":1,"qty":2,"priceCents":24900,"lineTotalCents":49800}]}
no alias: {"id":1,"total_cents":49800,"delivery_note":null,"created_at":"2026-11-24T12:30:00Z","lines":[{"menu_item_id":1,"qty":2,"price_cents":24900,"line_total_cents":49800}]}
exclude_none: dict_keys(['id', 'totalCents', 'createdAt', 'lines'])
mode=python: {'at': datetime.datetime(2026, 11, 24, 12, 30, tzinfo=datetime.timezone.utc), 'price': Decimal('249.00')}
mode=json: {'at': '2026-11-24T12:30:00Z', 'price': '249.00'}The input used camelCase (totalCents, createdAt) and the Python side used snake_case. by_alias=True wrote camelCase out, and leaving it off wrote snake_case. The @computed_field property line_total_cents appears in the output even though nobody sets it. The datetime was sent as +05:30 and written back as UTC with a Z by a custom serializer, so clients see one timezone. A Decimal is written as the string "249.00", which keeps its exact value; QuickBite avoids the question by storing integer cents.
In FastAPI the response model's aliases are used by default on the way out. This is the same behaviour through a route:
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel
class OrderIn(BaseModel):
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
restaurant_id: int
delivery_note: str | None = None
app = FastAPI()
@app.post("/v1/orders", response_model=OrderIn)
def create(body: OrderIn):
return body
c = TestClient(app)
print(c.post("/v1/orders", json={"restaurantId": 3, "deliveryNote": "gate 2"}).json())
print(c.post("/v1/orders", json={"restaurant_id": 3}).json()){'restaurantId': 3, 'deliveryNote': 'gate 2'}
{'restaurantId': 3, 'deliveryNote': None}Both camelCase and snake_case input were accepted (thanks to populate_by_name), and the response was camelCase both times.
Idiom: Discriminated unions
The problem: a field can be one of several shapes. QuickBite's payment method is card, upi or cash, and each has different fields. A plain union (Card | Upi | Cash) tries each model in turn and, on failure, reports an error from every one, which is unreadable.
How it works: every model carries a field with a fixed literal value (the "tag", here type). Field(discriminator="type") tells Pydantic to read the tag first and validate with only the matching model.
- Add a literal tag to each model:
type: Literal["card"]. - Declare the union with the discriminator:
Annotated[Card | Upi | Cash, Field(discriminator="type")]. - Use it as a field type in
OrderCreate, or directly through aTypeAdapter.
from typing import Annotated, Literal
from pydantic import BaseModel, Field, TypeAdapter, ValidationError
class Card(BaseModel):
type: Literal["card"]
token: str
class Upi(BaseModel):
type: Literal["upi"]
vpa: str
class Cash(BaseModel):
type: Literal["cash"]
PaymentMethod = Annotated[Card | Upi | Cash, Field(discriminator="type")]
adapter = TypeAdapter(PaymentMethod)
print(adapter.validate_python({"type": "upi", "vpa": "asha@okbank"}))
for bad in ({"type": "bitcoin"}, {"type": "card"}):
try:
adapter.validate_python(bad)
except ValidationError as e:
err = e.errors()[0]
print(bad, "->", err["type"], err["loc"], "|", err["msg"])
# without discriminator: plain union, noisy errors
class Plain(BaseModel):
pay: Card | Upi | Cash
try:
Plain.model_validate({"pay": {"type": "card"}})
except ValidationError as e:
print("plain union reports", e.error_count(), "errors for one mistake")type='upi' vpa='asha@okbank'
{'type': 'bitcoin'} -> union_tag_invalid () | Input tag 'bitcoin' found using 'type' does not match any of the expected tags: 'card', 'upi', 'cash'
{'type': 'card'} -> missing ('card', 'token') | Field required
plain union reports 4 errors for one mistakeThe upi payload was routed to the Upi model. An unknown tag produced one clear error that lists the allowed tags. A card payload without a token produced one error, ('card', 'token'), pointing to the field. Without the discriminator, the same mistake produced four errors. The discriminator also makes the OpenAPI schema typically a proper oneOf with a mapping, so generated clients get real types.
- Works: payment methods, event payloads, notification types, anything with a "kind" field.
- Fails: when the shape has no explicit tag. Then you need a custom "before" validator that decides the model, or change the API to add a tag.
- Interview takeaway: "For a field with several shapes I give each a literal tag and use
Field(discriminator=...), so validation is fast, errors point at the right model, and the OpenAPI schema is a cleanoneOf."
Idiom: A typed settings object
The problem: configuration read with os.environ["DB_POOL_SIZE"] in twenty places. Values are strings, typos fail at 2 a.m., and secrets get printed in logs.
How it works: pydantic-settings gives you a BaseSettings class. Each attribute is read from an environment variable (optionally a .env file), converted to its type and validated at start-up. A SecretStr hides its value in repr and logs.
- Declare the settings class: with types and safe defaults for development only.
- Create one cached instance:
@lru_cache def get_settings(), so the environment is read once. - Inject it with
Depends(get_settings): tests then replace it withdependency_overrides.
Make the invisible visible: three environment variables set inline, one of them wrong on purpose.
import os
from functools import lru_cache
from pydantic import SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_prefix="QB_", extra="ignore")
database_url: str = "sqlite:///./quickbite.db"
jwt_issuer: str = "https://id.quickbite.example"
jwt_audience: str = "quickbite-api"
jwt_secret: SecretStr = SecretStr("dev-only")
db_pool_size: int = 5
@lru_cache
def get_settings() -> Settings:
return Settings()
os.environ["QB_DATABASE_URL"] = "postgresql+psycopg://qb:pw@db:5432/quickbite"
os.environ["QB_DB_POOL_SIZE"] = "10"
os.environ["QB_JWT_SECRET"] = "s3cr3t-value"
s = get_settings()
print(s.database_url)
print("pool size:", s.db_pool_size, type(s.db_pool_size).__name__)
print("repr shows:", repr(s.jwt_secret))
print("real value:", s.jwt_secret.get_secret_value())
print("same object each call:", get_settings() is s)
os.environ["QB_DB_POOL_SIZE"] = "ten"
get_settings.cache_clear()
try:
get_settings()
except Exception as e:
err = e.errors()[0]
print(type(e).__name__, "->", err["loc"], err["type"])postgresql+psycopg://qb:pw@db:5432/quickbite
pool size: 10 int
repr shows: SecretStr('**********')
real value: s3cr3t-value
same object each call: True
ValidationError -> ('db_pool_size',) int_parsingThe pool size arrived as the text "10" and came out as an int. The secret printed as SecretStr('**********') and is only readable by calling get_secret_value(). The cache returned the same object on the second call. And a bad value ("ten") failed immediately with a clear error naming the setting, instead of failing later inside the first request that used it.
Why the cache? Building Settings() reads the environment and any .env file each time, and different parts of the program should never disagree about configuration. The cache also gives tests a single function to override:
from typing import Annotated
from functools import lru_cache
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
jwt_audience: str = "quickbite-api"
@lru_cache
def get_settings() -> Settings:
return Settings()
app = FastAPI()
@app.get("/whoami")
def whoami(s: Annotated[Settings, Depends(get_settings)]):
return {"audience": s.jwt_audience}
c = TestClient(app)
print("real: ", c.get("/whoami").json())
app.dependency_overrides[get_settings] = lambda: Settings(jwt_audience="test-audience")
print("override:", c.get("/whoami").json())real: {'audience': 'quickbite-api'}
override: {'audience': 'test-audience'}- Works: twelve-factor style configuration: the same image everywhere, with the environment supplying the database URL, issuer and secrets (see Chapter E9).
- Fails: secrets committed in
.envfiles, and a cached settings object that tests mutate (override the dependency instead; if you must change the environment, callget_settings.cache_clear()). - Interview takeaway: "Configuration is a typed pydantic-settings object read once from the environment, cached, injected with Depends and overridden in tests. Secrets are
SecretStrand come from the platform, never from the repository."
What validation costs
Validation is not free, but it is small next to the database call it protects. The program below builds a 1,000-line order as JSON (32 KB) and validates it two ways: parse with json.loads and then validate the dictionary, or hand the raw text to model_validate_json, which parses and validates in one pass inside the Rust core.
import json, timeit
from datetime import datetime
from typing import Annotated
from pydantic import BaseModel, Field
Qty = Annotated[int, Field(gt=0, le=50)]
class OrderLineIn(BaseModel):
menu_item_id: int
qty: Qty
note: str | None = None
class OrderCreate(BaseModel):
restaurant_id: int
lines: list[OrderLineIn]
payload = {"restaurant_id": 3,
"lines": [{"menu_item_id": i, "qty": 1 + i % 5} for i in range(1000)]}
raw = json.dumps(payload)
n = 200
t_dict = timeit.timeit(lambda: OrderCreate.model_validate(json.loads(raw)), number=n) / n
t_json = timeit.timeit(lambda: OrderCreate.model_validate_json(raw), number=n) / n
t_loads = timeit.timeit(lambda: json.loads(raw), number=n) / n
print(f"1,000-line order, {len(raw)/1024:.0f} KB of JSON, average of {n} runs")
print(f"json.loads only {t_loads*1000:6.2f} ms")
print(f"json.loads + model_validate {t_dict*1000:6.2f} ms")
print(f"model_validate_json (one step) {t_json*1000:6.2f} ms")
print("# measured on the course machine (12 cores); your numbers will differ")1,000-line order, 32 KB of JSON, average of 200 runs
json.loads only 0.34 ms
json.loads + model_validate 1.01 ms
model_validate_json (one step) 0.93 ms
# measured on the course machine (12 cores); your numbers will differAbout one millisecond for a very large order. A normal order with five lines takes microseconds. The one-step method is slightly faster and uses less memory, because it never builds the intermediate dictionary. Which path FastAPI takes internally for a JSON body has changed between versions, so measure before you rely on it. Use the one-step method yourself when you parse JSON from a queue or a file.
Java · Bean Validation
Annotations on a DTO and @Valid on the parameter. Types must already match; nothing converts.
// illustrative
public record OrderLineIn(
@NotNull Long menuItemId,
@Min(1) @Max(50) int qty) {}
@PostMapping("/v1/orders")
Order create(@Valid @RequestBody
OrderCreate body) { ... }Python · Pydantic
The type hint and the constraint are one declaration. The same model validates, converts and documents.
Qty = Annotated[int, Field(ge=1, le=50)]
class OrderLineIn(BaseModel):
menu_item_id: int
qty: Qty
@router.post("/v1/orders")
def create(body: OrderCreate): ...The shift: Bean Validation checks an object that is already built. Pydantic builds the object from raw input, checking and converting as it goes, so the typed object is proof that the input was valid.
Stack: Pydantic or something else?
FastAPI is built around Pydantic, so inside FastAPI the choice is made for you. The table is for the other cases: libraries, workers and non-FastAPI services.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Pydantic v2 | API boundaries, settings, anything FastAPI touches. Best ecosystem and error messages. | Heavier than plain classes. Converts types in lax mode, which you must know. |
| dataclasses + manual checks | Internal objects that are already trusted. Zero dependencies. | You write all validation and parsing by hand, and nothing generates documentation. |
| msgspec | Very high throughput JSON or MessagePack where speed matters more than features (installed in the course venv, not run here). | Smaller ecosystem. FastAPI does not use it natively, so you validate yourself. |
| attrs + cattrs | You already use attrs and want structuring and unstructuring of data with explicit converters. | More wiring than Pydantic and no built-in OpenAPI link. |
| marshmallow | An older Flask-style codebase that already has schemas. | Schemas are separate from the classes they describe, so there is more duplication. |
Switch when: keep Pydantic at every network boundary. Switch to dataclasses or msgspec only inside a measured hot path (profile first), for example decoding millions of queue messages per minute.
Putting sections 02 and 03 together
So far each idea ran alone. A real endpoint uses all of them at once, so here is the QuickBite order-creation route in its smallest honest form. It accepts OrderCreate, hands it to a stand-in "service" that builds a row (the real OrderService comes in sections 04 and 05), and returns OrderOut.
Read the program in four chunks before looking at the output. First the constrained types and request models. Second the response models with from_attributes. Third the stand-in row, which has an internal_note that must not leave. Fourth the route itself, which is only two lines of logic.
from datetime import datetime, timezone
from typing import Annotated
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field
Qty = Annotated[int, Field(gt=0, le=50)]
class OrderLineIn(BaseModel):
menu_item_id: int
qty: Qty
class OrderCreate(BaseModel):
restaurant_id: int
lines: list[OrderLineIn] = Field(min_length=1)
class OrderLineOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
menu_item_id: int
qty: int
price_cents: int
class OrderOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
status: str
total_cents: int
created_at: datetime
lines: list[OrderLineOut]
class OrderRow: # stand-in for app.models.Order
def __init__(self, body: OrderCreate):
self.id, self.status = 1001, "PLACED"
self.created_at = datetime(2026, 11, 24, 12, 30, tzinfo=timezone.utc)
self.lines = [type("L", (), dict(menu_item_id=l.menu_item_id, qty=l.qty,
price_cents=24900))() for l in body.lines]
self.total_cents = sum(l.qty * l.price_cents for l in self.lines)
self.internal_note = "never leaves"
app = FastAPI()
@app.post("/v1/orders", status_code=201, response_model=OrderOut)
def create_order(body: OrderCreate): # 1. validated into OrderCreate
return OrderRow(body) # 2. the "service" builds the row
c = TestClient(app)
r = c.post("/v1/orders", json={"restaurant_id": 3, "lines": [{"menu_item_id": 1, "qty": "2"}]})
print(r.status_code, r.json())
r = c.post("/v1/orders", json={"restaurant_id": 3, "lines": []})
print(r.status_code, r.json()["detail"][0]["type"], r.json()["detail"][0]["loc"])201 {'id': 1001, 'status': 'PLACED', 'total_cents': 49800, 'created_at': '2026-11-24T12:30:00Z', 'lines': [{'menu_item_id': 1, 'qty': 2, 'price_cents': 24900}]}
422 too_short ['body', 'lines']Trace one request through Figure 20.1. The JSON text arrived at the server. The router matched POST /v1/orders. FastAPI built an OrderCreate from the body, and in doing so converted the string "2" to the integer 2 (lax mode, bounded by Qty). The function ran and returned an object with an internal_note. The response model picked the six fields it declares, wrote the datetime as ISO 8601 and produced JSON. internal_note is nowhere in the output.
The second request sent an empty lines list. The function never ran. FastAPI answered 422 with type too_short at ['body', 'lines']. In section 06 this error will be reshaped into an RFC 9457 Problem Details body, but the mechanism is the one you just saw.
Symptom to box: a first-response table
Most of the drill questions in this chapter start from a symptom. A good habit is to map the symptom to a box of Figure 20.1 before touching code. The table lists the symptoms from sections 01 to 03, the box they live in, and the first thing to check.
| Symptom | Box in Fig. 20.1 | First thing to check |
|---|---|---|
| Latency jumps under load, CPU and database look idle | 7 · endpoint on the loop | A blocking call inside async def. Measure the loop lag, as in the heartbeat demo. |
| CPU graph shows 12% on 8 cores and requests queue | 2 · uvicorn | Number of worker processes (--workers, WEB_CONCURRENCY). |
| Every request hangs after a logging change | 4 · middleware | A layer that reads the body without replaying it. |
/orders/latest returns 422 or the wrong handler | 5 · router | Order of route registration: fixed paths first. |
| Client gets a column it should not see | 8 · response model | The route has no response_model, or returns a model that includes the column. |
"2" accepted, 2.7 refused | 3 to 5 · validation at the door | Lax mode. Decide whether to tighten with strict and a range. |
| PATCH wipes fields | 7 · endpoint | Missing exclude_unset=True when applying the update. |
| Slow burst of exactly 41 or 81 simultaneous requests | 7 · thread pool | The 40-thread limit. Count waves: ceil(requests / 40). |
What to carry into the next sections
Three sentences hold the whole of this half. A request is a function call from a server into your app, and everything else is layers around that call. Every process has one event loop for async def and 40 threads for def, so you choose the kind of function by what it calls. Every boundary is a Pydantic model, and the three-model rule keeps the inside of your system from leaking out.
Section 04 picks up from the endpoint and opens box 6: how Depends builds the objects an endpoint needs, how one database session per request is created and cleaned up, and how the project is laid out so that these routes stay thin. Section 05 then replaces the stand-in row with a real SQLAlchemy model.
If you want to rehearse before reading on, close the page and say the answer to these aloud: What happens to a blocking call in an async def endpoint, and how would you prove it? Why does uvicorn main:app on an 8-core VM show 12% CPU? In what order do two middlewares run? What are the three models of one entity, and which one is allowed to leave the server?
Five mistakes to recognise on sight
When you read someone else's FastAPI code in a review or an interview exercise, these five patterns account for most of the damage. Each one maps to something you ran in this chapter.
async defwith a synchronous driver inside: look forrequests.,time.sleep, a plain SQLAlchemySessionoropen(...).read()in an async function. The fix is a plaindef, an async library, orrun_in_threadpool.- No
response_model: look for routes that return a dictionary built from a database object, or an ORM object itself. Ask which columns exist today that the client should never see. --workersmissing, or copied blindly: look at the start command in the Dockerfile and at the pool settings. Ask how many processes run, and multiply by the pool size.- Model reused for input and output, or applied to PATCH without
exclude_unset: look for one class used in three places, and formodel_dump()without arguments in an update path. - Constraints missing on numbers and lists: look for bare
intandlist[...]in request models. An order with 10 million lines is valid unless a rule says otherwise.
None of these needs a clever tool to find. They show up by reading the function signatures, and that is exactly why interviewers like them: a candidate who spots all five in two minutes has understood where FastAPI's defaults end and the engineer's job begins.
04 · DependenciesDependency Injection with Depends, Lifespan and Project Structure
In FastAPI, "dependency injection" means plain functions that the framework calls for you, once per request, before your endpoint runs. Things that must live for the whole process (a connection pool, an HTTP client) belong in the lifespan, not in a dependency. This section shows how Depends resolves, how yield cleans up, how tests swap pieces out, and how to split the code into layers.
Here is an incident from QuickBite's second week. A developer needs to call the payment provider from the order endpoint. The quickest way, copied from a tutorial, is a dependency that returns an HTTP client.
The dependency builds a fresh httpx.AsyncClient() and hands it to the endpoint. A teammate does the same for the database: a dependency that calls create_engine(...) and returns a session from it. Both work perfectly on a laptop.
At 300 requests per second in production, the service starts to fail with OSError: [Errno 24] Too many open files within about a minute. Each request opened its own client with its own pool of sockets, and nothing closed them. Each fresh engine also opened its own brand-new connection to PostgreSQL, so the database saw 300 new connections every second.
Nothing in the code looks wrong. The functions are short and the tests pass. The bug is about lifetime: an object that should be created once per process was being created once per request.
Make the invisible visible: count how many clients get built when 300 requests arrive, once with the "client in a dependency" version and once with a client created at start-up. (This demo counts objects; it cannot show you the file-descriptor limit, but every client counted here owns its own connection pool, which is where the descriptors go.)
class CountingClient(httpx.AsyncClient):
kind = "naive"
def __init__(self, *a, **kw):
super().__init__(*a, **kw)
created[self.kind] += 1
class SharedClient(CountingClient):
kind = "shared"
# --- naive: a dependency that builds a client every time ---
async def naive_client():
client = CountingClient() # ❌ TRAP: new connection pool per request
return client # never closed
# --- fixed: build once at startup, close once at shutdown ---
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = SharedClient() # ✅ one client, one pool
yield
await app.state.http.aclose()@app.get("/naive")
async def naive(c: httpx.AsyncClient = Depends(naive_client)):
return {"client_id": id(c) % 10_000}requests sent to each endpoint: 300
clients created by /naive : 300
clients created by /shared: 1Why: a dependency function runs for every request that uses it. Whatever you create inside it is created again each time. The fix is not a cleverer dependency. It is to move the creation to a place that runs once, which is the lifespan, and let the dependency only hand out the shared object.
Bridge: Depends, one level down
Most tutorials show Depends as magic: you write a parameter, and a value appears. It is not magic, and knowing the mechanism removes most of the surprises. Here is what FastAPI does.
- At start-up, read the signature: when you write
@router.post(...), FastAPI looks at the endpoint function's parameters once. For each parameter it decides: path value, query value, header, body, or "dependency" (because the default isDepends(...)). - Recurse: each dependency is itself a function with parameters. FastAPI reads those too, and so on. The result is a tree, called the dependency graph, stored with the route.
- At request time, resolve from the leaves up: FastAPI calls the deepest dependencies first, passes their results into the ones above, and finally calls your endpoint with everything filled in.
- Remember within the request: if the same dependency appears twice in the graph, FastAPI runs it once and reuses the result. The memory lives only for this request.
Two details matter in practice. A dependency declared with async def is awaited on the event loop. A dependency declared with plain def is run in the thread pool (the same pool of 40 threads that plain def endpoints use, see the def versus async def idiom). So a slow, blocking dependency written with def costs a thread, and the same code inside async def would block the whole loop.
The second detail is that "once per request" is a promise about one request. Two different requests never share a dependency result. That is why Depends is the right tool for per-request things (a database session, the current user) and the wrong tool for per-process things (the pool itself).
Make the invisible visible: a recording of which dependencies run for three requests. get_settings is used twice in the first request (directly, and through get_session), and the counter shows how often it really ran.
calls = []
def get_settings():
calls.append("get_settings")
return {"pool": 5}
def get_session(settings: dict = Depends(get_settings)):
calls.append("get_session")
return f"session(pool={settings['pool']})"
def get_service(session: str = Depends(get_session), settings: dict = Depends(get_settings)):
calls.append("get_service")
return f"service({session})"
class Pager: # class dependency: __init__ params come from the query string
def __init__(self, limit: int = 20, offset: int = 0):
calls.append("Pager")
self.limit, self.offset = limit, offset
def require_scope(name: str): # factory: returns the real dependency
def checker():
calls.append(f"require_scope({name})")
return name
return checkerapp = FastAPI()
@app.get("/cached")
def cached(a=Depends(get_session), b=Depends(get_service)):
return {"a": a, "b": b}
@app.get("/uncached")
def uncached(a=Depends(get_settings), b=Depends(get_settings, use_cache=False)):
return {"ok": True}
@app.get("/list")
def listing(p: Pager = Depends(), scope: str = Depends(require_scope("orders:read"))):
return {"limit": p.limit, "offset": p.offset, "scope": scope}
c = TestClient(app)
for path in ["/cached", "/uncached", "/list?limit=5"]:
calls.clear()
r = c.get(path)
print(f"GET {path} -> {r.json()}")
print(" ran:", calls)GET /cached -> {'a': 'session(pool=5)', 'b': 'service(session(pool=5))'}
ran: ['get_settings', 'get_session', 'get_service']
GET /uncached -> {'ok': True}
ran: ['get_settings', 'get_settings']
GET /list?limit=5 -> {'limit': 5, 'offset': 0, 'scope': 'orders:read'}
ran: ['Pager', 'require_scope(orders:read)']What you see: in /cached, get_settings ran once even though it is needed by get_session, by get_service, and by the endpoint itself. In /uncached, the second parameter says use_cache=False, so it ran twice. In /list, a class and a factory both worked as dependencies.
The three shapes of a dependency
Any callable (anything you can put () after) can be a dependency. In real projects you meet three shapes.
| Shape | Looks like | Use it when |
|---|---|---|
| Plain function | def get_session(): ... | Most things: a session, the current user, settings. Simple, and easy to override in tests. |
| Class | class Pager: def __init__(self, limit: int = 20, offset: int = 0) | A bundle of query parameters you want as one object, with defaults and validation in one place. FastAPI calls the class, so __init__ parameters are read from the request like any other. |
| Factory (parameterised) | def require_scope(name): def checker(): ...; return checker | The same check with different settings per route: Depends(require_scope("orders:write")). The outer call runs at import time, the inner function at request time. |
The factory shape is the one Part C uses for authorisation. The important bit is the timing: require_scope("orders:write") executes once, when the module is imported, and returns the inner function. FastAPI then calls that inner function on every request. Forgetting the difference leads to a classic bug where someone writes Depends(require_scope) (no call) and FastAPI tries to treat name as a query parameter.
POST /v1/orders. Settings feed the session, the session feeds the service, and the authentication chain runs beside it. Two branches meet at the endpoint.Read the picture from the left. get_settings has no dependencies, so it is a leaf and runs first. get_session needs the settings (for the database URL, in the real app), so it runs next. In parallel, conceptually, get_current_user reads the bearer token, and require_scope checks that the user may write orders. Only when both branches have finished does FastAPI call the endpoint.
Notice what is not in the graph: the engine and the connection pool. They exist before any request, created by the lifespan, which is the next idiom after yield.
Idiom: Yield dependency for per-request resources
The problem: a database session must be opened before the endpoint, closed after it, and rolled back if something went wrong. Writing that try/finally in every endpoint is repetitive, and the one endpoint where someone forgets it leaks a connection.
How it works: a dependency written as a generator. Code before yield is setup, the yielded value is what the endpoint receives, and code after yield is teardown. FastAPI drives the generator for you, the way a with block would.
- Setup: FastAPI calls the generator and runs it up to
yield. The yielded object (the session) is passed to the endpoint. - Endpoint runs: it uses the session and returns a value, or raises.
- Teardown: if the endpoint returned, FastAPI resumes the generator after
yield. If the endpoint raised, FastAPI throws that exception into the generator at theyieldline, so yourexceptandfinallyblocks run.
Make the invisible visible: the exact order of events for a successful request, a business error (HTTP 409), and a crash, recorded with a small spy that notes when the first and last bytes of the response leave the app. Tested with FastAPI 0.141.1.
class FakeSession:
def commit(self): stamp("session.commit()")
def rollback(self): stamp("session.rollback()")
def close(self): stamp("session.close()")POST /ok -> 200 {'saved': True}
25.2 ms get_session: open
26.0 ms endpoint: running
26.3 ms ASGI send: http.response.start (status 200)
26.3 ms ASGI send: http.response.body (last chunk)
26.5 ms session.commit()
26.5 ms session.close()
POST /boom -> 409 {'detail': 'out of stock'}
29.0 ms get_session: open
29.4 ms endpoint: raising
29.8 ms session.rollback()
29.8 ms session.close()
29.9 ms ASGI send: http.response.start (status 409)
29.9 ms ASGI send: http.response.body (last chunk)
POST /crash -> 500 Internal Server Error
31.8 ms get_session: open
32.2 ms endpoint: raising ZeroDivisionError
32.5 ms session.rollback()
32.5 ms session.close()
32.7 ms ASGI send: http.response.start (status 500)
32.7 ms ASGI send: http.response.body (last chunk)What you see: two different orders.
- Success path (/ok): the endpoint returns, then FastAPI sends the whole response, and only after that does the code after
yieldrun. Socommit()happens after the client already has its 200. - Error path (/boom, /crash): the exception is thrown into the generator first,
rollback()andclose()run, and then the error response (409 or 500) is sent.
The first line is the one to remember: as of FastAPI 0.141, teardown after a successful endpoint runs after the response has been sent. This behaviour has changed between FastAPI versions, so treat it as something to re-check when you upgrade, not as a law of nature.
The trap: if you put session.commit() after the yield, a failed commit (a deadlock, a constraint violation, a lost connection) can no longer change the answer. The client was already told "201 Created". Here is the same idea with a commit that fails.
dependency commits -> 200 {'order_id': 42, 'status': 'CREATED'}
service commits -> 500 Internal Server Errordef get_session():
s = FailingSession()
try:
yield s
s.commit() # ❌ TRAP: runs after the 200 was already sent
except Exception:
s.rollback()
raise
app = FastAPI()
@app.post("/orders")
def create(session=Depends(get_session)):
return {"order_id": 42, "status": "CREATED"}The first call returned 200 with an order id even though the commit failed. The customer thinks the order exists, and it does not. The second version moves the commit into the service method, inside the call, so the failure becomes a 500 the client can see and retry.
That is why QuickBite's rule is: the dependency owns opening and closing the session; the service owns the commit. The dependency still does rollback and close in its teardown as a safety net.
- Works: any per-request resource with a setup and a cleanup: sessions, temporary files, locks, a per-request HTTP span.
- Fails: relying on teardown to produce part of the response, or committing in teardown. Teardown cannot change a response that has been sent, and an exception raised there is not seen by the client.
- Interview takeaway: "A yield dependency gives me setup and teardown per request. I open and close the session there, but the service commits inside the call, because teardown can run after the response is already sent."
Bridge: Spring's @Transactional, one level down
In Spring, a @Transactional method is wrapped by a proxy. The proxy begins a transaction before the method, commits when it returns, and rolls back when it throws a runtime exception. The commit happens inside the call, so a failed commit surfaces as an exception to the caller.
FastAPI has no proxy and no annotation. You get two ordinary tools: the yield dependency (resource lifetime) and an explicit with session.begin(): block in the service (transaction boundary). They do the two jobs that @Transactional does in one.
Idiom: Lifespan for process-wide resources
The problem: the incident at the start of this section. An engine, a connection pool, an HTTP client, a loaded machine-learning model: these are expensive to build and meant to be shared. Building them in a dependency rebuilds them for every request.
How it works: a lifespan is an async context manager you give to FastAPI(lifespan=...). Code before its yield runs once when the server starts. Code after runs once when the server stops. Resources are stored on app.state, and a small dependency hands them to endpoints.
- Start-up: create the engine and the HTTP client, put them on
app.state. - Serving: the dependency
shared_client(request)readsrequest.app.state.http. It creates nothing. - Shutdown: after
yield, close the client and dispose the engine so connections end cleanly.
Make the invisible visible: start-up and shutdown messages, and what happens if a test forgets to run the lifespan.
class FakePool:
def __init__(self): print(" [startup] pool created")
def close(self): print(" [shutdown] pool closed")
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = FakePool() # before the first request
yield # the app serves requests here
app.state.pool.close() # after the last request
app = FastAPI(lifespan=lifespan)
@app.get("/ping")
def ping(request: Request):
return {"pool_id": id(request.app.state.pool) % 1000}
print("1) TestClient WITHOUT 'with': lifespan never runs")
c = TestClient(app)
try:
print(" ", c.get("/ping").status_code)
except Exception as e:
print(" ", type(e).__name__, e)
print("2) TestClient AS a context manager: lifespan runs")
with TestClient(app) as c:
print(" inside with-block, three requests")
ids = {c.get("/ping").json()["pool_id"] for _ in range(3)}
print(" distinct pools seen:", len(ids))
print(" after with-block")1) TestClient WITHOUT 'with': lifespan never runs
AttributeError 'State' object has no attribute 'pool'
2) TestClient AS a context manager: lifespan runs
[startup] pool created
inside with-block, three requests
distinct pools seen: 1
[shutdown] pool closed
after with-blockWhat you see: one pool for three requests, start-up before the first one, shutdown after the last. And the first test shows the common surprise: a TestClient used without with never runs the lifespan, so app.state.pool does not exist and the endpoint fails.
The lifespan replaced the older @app.on_event("startup") hooks. Those are deprecated, so write new code with lifespan. In the real QuickBite app (Part C) the lifespan builds the engine from Settings, and the shutdown half calls engine.dispose().
| Question | Lifespan | Dependency |
|---|---|---|
| How often does it run? | Once per process (per worker). | Once per request. |
| Typical contents | Engine, pool, HTTP client, model weights, cache connection. | A session, the current user, a request-scoped helper. |
| Can it depend on the request? | No: there is no request yet. | Yes: it can read headers, the path, the body. |
| Where is it stored? | app.state | Passed to the endpoint as an argument. |
Remember that each worker process runs its own lifespan. With four workers, four engines exist, each with its own pool. That multiplication returns in the data section when we size the pool.
- Works: anything expensive and shareable, with a clear "close it" moment.
- Fails: sharing something that is not safe to share. A Session is not thread-safe, so it never goes in
app.state. The engine is safe to share, and so is anhttpx.AsyncClientinside the event loop.
- Interview takeaway: "Process-wide, expensive resources are created once in the lifespan and closed on shutdown. Dependencies only hand them out or build cheap per-request objects on top."
Idiom: Dependency override for tests
The problem: a test must not talk to the production database, a real payment provider or a real identity server. Patching imports with unittest.mock.patch works, but it is tied to where a name is imported, and it breaks when someone moves a function.
How it works: the app keeps a dictionary, app.dependency_overrides. Its keys are the original dependency functions, its values are replacements. When FastAPI resolves the graph, it looks each function up in the dictionary first.
- Key by the function object:
app.dependency_overrides[get_session] = fake_session. The key is the very function the endpoint declared withDepends. - The replacement can have its own dependencies: it is resolved like any other dependency, so a fake can still take a
Requestor a header. - Clean up: call
app.dependency_overrides.clear()after the test, or the next test inherits the fake.
Make the invisible visible: the same endpoint without an override, with one, and after clearing. The router also has a router-level dependency, an API-key check, which the override of the session does not affect.
def get_session():
raise RuntimeError("real database not available in tests") # stands in for Postgres
yield
def verify_api_key(x_api_key: str = Header(default="")):
if x_api_key != "secret":
raise HTTPException(status_code=401, detail="bad api key")
class FakeSession:
def count_orders(self): return 3
router = APIRouter(prefix="/v1/internal", dependencies=[Depends(verify_api_key)]) # whole router
@router.get("/orders/count")
def count(session=Depends(get_session)):
return {"count": session.count_orders()}
app = FastAPI()
app.include_router(router)
@app.get("/healthz")
def healthz():
return {"status": "ok"}
c = TestClient(app, raise_server_exceptions=False)
print("no override :", c.get("/v1/internal/orders/count", headers={"x-api-key": "secret"}).status_code)
app.dependency_overrides[get_session] = lambda: FakeSession()
print("with override :", c.get("/v1/internal/orders/count", headers={"x-api-key": "secret"}).json())
print("router-level dep :", c.get("/v1/internal/orders/count").status_code, c.get("/v1/internal/orders/count").json())
print("healthz (no router):", c.get("/healthz").status_code)
app.dependency_overrides.clear()
print("after clear() :", c.get("/v1/internal/orders/count", headers={"x-api-key": "secret"}).status_code)no override : 500
with override : {'count': 3}
router-level dep : 401 {'detail': 'bad api key'}
healthz (no router): 200
after clear() : 500What you see: the real get_session raised, so the endpoint gave a 500. With the override, it returned count: 3. The API-key dependency still ran (a request without the header got 401), because it was not overridden. After clear() the real dependency is back.
- Works: replacing a session, the current user, the clock, an outbound client. It tests the real routing, validation and serialisation, which mocks of the whole endpoint would skip.
- Fails: forgetting to clear overrides (tests leak into each other), or overriding with a function that has a different return type. Nothing checks that the fake matches the real one, so a drifted fake gives green tests and a red production.
- Interview takeaway: "Because dependencies are plain functions, tests replace them through app.dependency_overrides. I swap the session and the user, keep the real routing and validation, and clear the overrides after each test."
Router-level and app-level dependencies
Sometimes a check should run for every route in a group, and the endpoints do not need the result. The example above does this: APIRouter(dependencies=[Depends(verify_api_key)]). The function runs before every endpoint of that router, and its return value is thrown away. If it raises HTTPException, the endpoint never runs.
The same list exists on FastAPI(dependencies=[...]) for the whole application, and on a single route decorator. Use it for guards: API-key checks, "this whole router is internal", rate-limit counters. Do not use it when the endpoint needs the value (for example the current user). Then put the dependency in the signature so you receive the result.
Note the router-level dependency in the demo did not apply to /healthz, which lives outside that router. That is exactly the point: health checks stay public while the internal routes are guarded.
Idiom: Layered structure, routers then services then repositories
The problem: a QuickBite endpoint grows to 120 lines. It parses the request, checks stock, writes SQL, calls the payment provider, builds the JSON. To test the stock rule you have to start an HTTP client. To reuse it from a Kafka consumer, you copy and paste.
How it works: give each concern one home, and allow calls to go in only one direction.
- Router (
routers/orders.py): HTTP only. Read the request, call a service, choose the status code, return a response model. No business rules, no SQL. - Service (
services.py): business rules and transaction boundaries. "Is the item in stock", "is this a replay of an idempotency key", "commit now". It knows nothing about HTTP. - Repository (
repositories.py): queries. "Orders for this customer, newest first". It knows SQL and models, not rules. - Models and schemas:
models.pyholds the ORM classes.schemas.pyholds the Pydantic request and response shapes, the boundary types from the Pydantic section.
The setup: the folder tree of the canonical QuickBite app (Part C builds it).
# illustrative
quickbite_api/
├── pyproject.toml
├── Dockerfile
├── app/
│ ├── main.py create_app(), lifespan
│ ├── db.py engine, SessionLocal, get_session()
│ ├── models.py Customer, MenuItem, Order, OrderLine ...
│ ├── schemas.py OrderCreate, OrderOut, Problem ...
│ ├── repositories.py OrderRepository (queries)
│ ├── services.py OrderService (rules, commit)
│ ├── security.py get_current_user(), require_scope()
│ ├── errors.py problem-details handlers
│ ├── core/
│ │ ├── config.py Settings(BaseSettings)
│ │ └── logging.py
│ └── routers/
│ ├── orders.py APIRouter(prefix="/v1/orders")
│ └── health.py /healthz, /readyz
└── tests/
└── conftest.py app + in-memory DB + overridesThe dependency graph is how the layers get wired. The router declares service: OrderService = Depends(get_order_service). That function builds OrderService(session) from get_session, and the service builds its repository from the same session. One session, shared by all three layers, for one request.
class OrderService:
def __init__(self, session: Session):
self.session = sessiondef get_order_service(session: Session = Depends(get_session)) -> OrderService:
return OrderService(session) # one session per request, shared down the layers
@router.post("", status_code=201, response_model=OrderOut)
def create_order(body: OrderCreate,
idempotency_key: str = Header(min_length=8),
user: User = Depends(require_scope("orders:write")),
service: OrderService = Depends(get_order_service)):
return service.create_order(user.id, idempotency_key, body) # HTTP in, HTTP outThe trap: business logic in the endpoint. It starts innocently ("just one if for stock") and ends with the same rule written three times in three endpoints, each slightly different. A sign you have crossed the line: your endpoint imports select or checks a business rule.
The other trap is the opposite: a repository for every table with one method each, wrapped by a service that only forwards calls. If a layer adds nothing, skip it. A 5-endpoint internal tool does not need three layers. A 40-endpoint service with several callers (HTTP, a consumer, a scheduled job) does.
- Works: services with real rules, several entry points, and tests that run without HTTP.
- Fails: ceremony without content, such as pass-through layers, or repositories that commit (that decision belongs to the service).
- Interview takeaway: "Routers do HTTP, services own rules and the transaction, repositories own queries, and calls only go downward. The session is created once per request and shared through Depends."
Spring Boot · IoC container
The container creates singleton beans at start-up. Constructors receive their collaborators, and a proxy handles transactions.
// illustrative
@Service
class OrderService {
private final OrderRepository repo;
OrderService(OrderRepository repo) {
this.repo = repo;
}
@Transactional
Order create(OrderCreate c) { ... }
}FastAPI · Depends
No container. Plain functions build objects per request, and the service opens its own transaction.
class OrderService:
def __init__(self, session):
self.session = session
def create(self, c):
with self.session.begin():
...
def get_service(s=Depends(get_session)):
return OrderService(s)The shift: Spring builds a long-lived object graph once and wraps methods in proxies; FastAPI builds a short-lived graph per request from plain functions, and the transaction is a visible with block.
Spring beans are singletons by default, so they must be stateless and thread-safe. A FastAPI service object lives for one request, so it can hold the request's session in an ordinary attribute. That removes a whole class of thread-safety worry, and costs a few microseconds to create the object each time.
Stack note: container-style dependency injection
| Option | Pick it when | Cost or catch |
|---|---|---|
Depends (built in) | Almost always. Request-scoped things, tests with overrides. | It only works inside FastAPI's request handling. Background scripts and consumers need their own wiring. |
Manual wiring in create_app() | Process-wide objects, shared by a web app and a worker. | You write the glue yourself, which is a few lines. |
dependency-injector, punq, svcs | A large codebase with many entry points (web, CLI, consumers) that must share one object graph. | One more concept to learn, and two ways to inject things in the same code base. I have not run them here, so check their current docs before adopting. |
Switch when: you have real code that is not an HTTP request (a Kafka consumer, a scheduled job) and you are tired of re-creating the same wiring. Until then, Depends is enough, and most Python teams never need a container.
05 · PersistenceSQLAlchemy 2.0, Transactions, Migrations and Idempotency
Most API incidents end in the database. This section covers the five that QuickBite met: the Session's lifetime, the N+1 query storm, the oversold item, the exhausted connection pool, and the migration that locked a table. It ends with the idempotency key that makes a retried POST safe.
Two incidents from QuickBite's launch weekend. First: GET /v1/orders for a customer with 50 orders took 900 ms. The code looked innocent: load the orders, return them with their lines. In the logs, one request produced 51 SQL statements.
On a laptop, each statement takes 0.2 ms, so 51 of them cost 10 ms and nobody noticed. In production, the database is on another machine and each round trip costs about 15 ms to 18 ms. Fifty-one round trips is roughly 900 ms. The query was not slow. There were just too many of them.
Second: the restaurant had one portion of chicken biryani left. Two customers tapped "Order" within the same few milliseconds. Both requests read stock = 1, both decided "there is enough", both wrote stock = 0, and both got "order confirmed". One customer got a biryani, and the other got an apology and a refund.
Both bugs come from not seeing what the ORM does. One level down, there is a small amount of machinery, and once you can see it, both problems are easy to spot.
Bridge: SQLAlchemy 2.0, one level down
SQLAlchemy has three objects you must keep apart. People who mix them up write code that works until it is under load.
- Engine: the thing that knows where the database is and owns the connection pool. You create one per process, at start-up (the lifespan from the last section). It is safe to share.
- Connection: one real connection to the database, borrowed from the pool and returned when you are done. A raw connection runs SQL text or Core statements.
- Session: the ORM's workspace for one unit of work. It borrows a connection when it first needs one, remembers every object you loaded or added, works out what changed, and writes those changes in one go. It is cheap to create, and it is not thread-safe.
Two phrases need translating. The unit of work is the Session's habit of collecting your changes (new objects, modified objects, deleted objects) and sending them together, in a safe order, inside one transaction. The identity map is its promise that inside one Session, one database row is one Python object: ask for order 7 twice and you get the very same object back, without a second query.
JPA · Hibernate
The EntityManager holds a persistence context. Changes to managed entities are written at flush or commit.
// illustrative
@Transactional
void takeStock(long id) {
MenuItem m = em.find(MenuItem.class, id);
m.setStock(m.getStock() - 1);
// no save(): dirty checking at commit
}SQLAlchemy · Session
The Session is the persistence context. Changes to loaded objects are found at flush and written on commit.
def take_stock(session, item_id):
with session.begin():
m = session.get(MenuItem, item_id)
m.stock = m.stock - 1
# no add(): the Session saw
# the change and flushes itThe shift: the concept is the same (a workspace that tracks objects and writes changes), but the Session's boundary is something you write as a with block, not an annotation on a proxy.
If you know JPA from Chapter E5, the mapping is direct: EntityManager is Session, the persistence context is the identity map, dirty checking is the flush, and FetchType.LAZY is SQLAlchemy's default lazy loading. The N+1 problem is the same in both worlds, and so are its fixes.
Typed models and a first round trip
SQLAlchemy 2.0 introduced a typed style. You annotate each attribute with Mapped[...] and, when you need options, add mapped_column(...). A plain Mapped[int] becomes a non-null integer column; Mapped[int | None] would be nullable. Relationships use relationship(), with back_populates naming the other side.
from datetime import datetime, timezone
from sqlalchemy import ForeignKey, String, UniqueConstraint
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
def utcnow() -> datetime:
return datetime.now(timezone.utc)
class Base(DeclarativeBase):
pass
class Customer(Base):
__tablename__ = "customers"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(80))
orders: Mapped[list["Order"]] = relationship(back_populates="customer")
class Restaurant(Base):
__tablename__ = "restaurants"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(80))
class MenuItem(Base):
__tablename__ = "menu_items"
id: Mapped[int] = mapped_column(primary_key=True)
restaurant_id: Mapped[int] = mapped_column(ForeignKey("restaurants.id"))
name: Mapped[str] = mapped_column(String(80))
price_cents: Mapped[int]
stock: Mapped[int] = mapped_column(default=0)
restaurant: Mapped["Restaurant"] = relationship()class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"), index=True)
restaurant_id: Mapped[int] = mapped_column(ForeignKey("restaurants.id"))
status: Mapped[str] = mapped_column(String(20), default="CREATED")
total_cents: Mapped[int] = mapped_column(default=0)
created_at: Mapped[datetime] = mapped_column(default=utcnow)
customer: Mapped[Customer] = relationship(back_populates="orders")
lines: Mapped[list["OrderLine"]] = relationship(back_populates="order", cascade="all, delete-orphan")
class OrderLine(Base):
__tablename__ = "order_lines"
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"), index=True)
menu_item_id: Mapped[int] = mapped_column(ForeignKey("menu_items.id"))
qty: Mapped[int]
price_cents: Mapped[int]
order: Mapped[Order] = relationship(back_populates="lines")
class IdempotencyKey(Base):
__tablename__ = "idempotency_keys"
key: Mapped[str] = mapped_column(String(80), primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"))
request_hash: Mapped[str] = mapped_column(String(64))
response_json: Mapped[str]
created_at: Mapped[datetime] = mapped_column(default=utcnow)Money is stored as integer cents (price_cents, total_cents). Floats cannot represent 249.90 exactly, and rounding errors in a bill are the kind of bug nobody forgives. The same rule applies to the API's JSON.
Now create the tables on SQLite and do one round trip, with SQL logging on. Reading statements is the habit that finds N+1 bugs, so do it early.
engine = create_engine("sqlite://", echo=False)
Base.metadata.create_all(engine)
logging.basicConfig(format="%(message)s")
logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO) # same as echo=True
with Session(engine) as session:
session.add_all([Customer(id=1, name="Asha"), Restaurant(id=1, name="Biryani House")])
session.add(MenuItem(id=1, restaurant_id=1, name="Chicken biryani", price_cents=24900, stock=5))
session.commit()
print("---- add an order with one line")
order = Order(customer_id=1, restaurant_id=1, total_cents=49800,
lines=[OrderLine(menu_item_id=1, qty=2, price_cents=24900)])
session.add(order)
session.commit()
print("---- read it back")
got = session.scalars(select(Order).where(Order.customer_id == 1)).one()
print("order", got.id, got.status, got.total_cents)BEGIN (implicit)
INSERT INTO customers (id, name) VALUES (?, ?)
[generated in 0.00012s] (1, 'Asha')
INSERT INTO restaurants (id, name) VALUES (?, ?)
[generated in 0.00009s] (1, 'Biryani House')
INSERT INTO menu_items (id, restaurant_id, name, price_cents, stock) VALUES (?, ?, ?, ?, ?)
[generated in 0.00008s] (1, 1, 'Chicken biryani', 24900, 5)
COMMIT
BEGIN (implicit)
INSERT INTO orders (customer_id, restaurant_id, status, total_cents, created_at) VALUES (?, ?, ?, ?, ?)
[generated in 0.00013s] (1, 1, 'CREATED', 49800, '2026-11-24 17:17:28.034718')
INSERT INTO order_lines (order_id, menu_item_id, qty, price_cents) VALUES (?, ?, ?, ?)
[generated in 0.00009s] (1, 1, 2, 24900)
COMMIT
BEGIN (implicit)
SELECT orders.id, orders.customer_id, orders.restaurant_id, orders.status, orders.total_cents, orders.created_at
FROM orders
WHERE orders.customer_id = ?
[generated in 0.00009s] (1,)
ROLLBACK
---- add an order with one line
---- read it back
order 1 CREATED 49800What you see: BEGIN (implicit) appears on its own. The Session started a transaction the moment it first touched the database. The inserts came in dependency order: customers and restaurants first, then menu items, then the order, then its line (the relationship() declarations are what tell the unit of work which table must go first). Each COMMIT ends one transaction. The final SELECT ends with ROLLBACK, which is just the Session closing a read-only transaction.
In queries, use the 2.0 style: session.scalars(select(Order).where(Order.customer_id == 1)).all(). The old session.query(Order) still works but is the legacy style, and new code should not use it.
Idiom: One Session per request, and the service owns the commit
The problem: a Session keeps state: identity map, pending changes, an open transaction. If it is shared across requests (a module-level global), one request's failure poisons the next, and two threads writing into it corrupt each other.
How it works: each request gets its own Session from a sessionmaker, via the yield dependency from the first half of this section. The service wraps its work in with session.begin():, which commits on success and rolls back on any exception.
- Create:
get_session()opensSessionLocal()and yields it. - Use: the service runs
with self.session.begin():. Inside the block, everything is one transaction. - Close: after the response, the dependency's
with SessionLocal() as sessioncloses the Session and returns its connection to the pool.
Make the invisible visible: a global Session (the trap) next to a Session per request. In both, request 1 breaks a unique constraint.
print("A) one global Session (the trap)")
shared = Session(engine) # ❌ TRAP: module-level, lives forever
def handler_shared(customer_id, name):
shared.add(Customer(id=customer_id, name=name))
shared.commit()
handler_shared(1, "Asha")
try:
handler_shared(1, "Duplicate id") # request 1 breaks a constraint, nobody rolls back
except Exception as e:
print(" request 1 failed:", type(e).__name__)
try:
shared.scalars(select(Customer)).all() # request 2 only wants to READ
except Exception as e:
print(" request 2 failed:", type(e).__name__ + ":", str(e)[:70], "...")
print("B) one Session per request")
def handler_scoped(customer_id, name):
with SessionLocal() as session, session.begin(): # opens, commits or rolls back, closes
session.add(Customer(id=customer_id, name=name))
try:
handler_scoped(1, "Duplicate id")
except Exception as e:
print(" request 1 failed:", type(e).__name__)
with SessionLocal() as session:
print(" request 2 reads:", [c.name for c in session.scalars(select(Customer))])A) one global Session (the trap)
request 1 failed: IntegrityError
request 2 failed: PendingRollbackError: This Session's transaction has been rolled back due to a previous exce ...
B) one Session per request
request 1 failed: IntegrityError
request 2 reads: ['Asha']Why: after a failed flush, a Session refuses to continue until someone calls rollback(). In the global version nobody did, so request 2, which only wanted to read, got PendingRollbackError. In production this looks like a healthy service that suddenly fails every request, until it is restarted.
- Works: every sync endpoint and service. It also works with
sessionmaker(expire_on_commit=False)when you return ORM objects after commit through a response model. - Fails: sharing a Session across requests, across threads, or across
asyncio.gathertasks. If you need parallelism, give each task its own Session.
- Interview takeaway: "One Session per request, opened and closed by a yield dependency. The service owns the transaction with session.begin(), so rollback on error is automatic and the Session is never shared."
The unit of work, step by step
Because the Session defers writing, there is a moment between "I changed an object" and "the database knows". The next demo shows that moment. It loads an item, changes its stock, adds a new order with a line, and prints what the Session knows before and after the flush.
with Session(engine) as s:
s.add(Customer(id=1, name="Asha"))
s.add(Restaurant(id=1, name="Biryani House"))
s.add(MenuItem(id=1, restaurant_id=1, name="Biryani", price_cents=24900, stock=5))
s.commit() SQL: INSERT INTO customers ...
SQL: INSERT INTO restaurants ...
SQL: INSERT INTO menu_items ...
1) track: nothing is sent while we change objects
SQL: SELECT menu_items.id ...
identity map holds: ['MenuItem']
session.new : ['Order', 'OrderLine']
session.dirty: ['MenuItem']
2) flush: the pending changes become SQL, parents before children
SQL: UPDATE menu_items SET stock=? WHER ...
SQL: INSERT INTO orders ...
SQL: INSERT INTO order_lines ...
3) get() again: same Python object, no SQL (identity map)
same object: True
4) commitWhat you see: the first SELECT comes from get. After that, changing stock and adding the order sent nothing. session.new and session.dirty list what is waiting. Only flush() produced the UPDATE and the two INSERT statements, with the order inserted before its line. The second get returned the same Python object without any SQL, which is the identity map at work.
This also explains the oversell bug that is coming. The Session writes what the object says now. It does not know that another request changed the row in the meantime.
Bridge: the N+1 problem, one level down
Go back to the 900 ms request. The endpoint did two innocent things: it loaded a customer's orders with one query, then looped over them and read order.lines to build the JSON.
The lines attribute is lazy by default. The first time you touch it for a given order, SQLAlchemy quietly runs SELECT ... FROM order_lines WHERE order_id = ? for that one order. Touch it for 50 orders and you get 50 extra queries, plus the 1 query for the orders: N + 1 with N = 50.
Make the invisible visible: an event listener that counts every statement sent to the database. The data is 50 orders, three lines each. We run the same loop three times, changing only how lines is loaded.
count = 0
@event.listens_for(engine, "before_cursor_execute")
def counter(*args):
global count
count += 1
def run(label, options=()):
global count
with Session(engine) as s:
count = 0
orders = s.scalars(select(Order).where(Order.customer_id == 1).options(*options)).unique().all()
total_lines = sum(len(o.lines) for o in orders) # touches o.lines for every order
print(f"{label:<28} statements={count:<3} orders={len(orders)} lines={total_lines}")run("lazy (default)")
run("selectinload(Order.lines)", [selectinload(Order.lines)])
run("joinedload(Order.lines)", [joinedload(Order.lines)])lazy (default) statements=51 orders=50 lines=150
selectinload(Order.lines) statements=2 orders=50 lines=150
joinedload(Order.lines) statements=1 orders=50 lines=150
InvalidRequestError: The unique() method must be invoked on this Result, as it contains results ...
rows the database actually sends: 150 (50 orders x 3 lines)What you see: 51 statements for the lazy version, 2 with selectinload, 1 with joinedload. The data returned is identical: 50 orders and 150 lines in all three.
n_plus_one.py. Bar length is proportional to the statement count, so the two fixed versions are barely visible, which is the point.The multiplication under the chart uses the 15 ms round trip from the incident, so 51 × 15 ms is 765 ms. The remaining time in the production figure of 900 ms was the work in the database and JSON building.
Idiom: Eager loading, chosen on purpose
The problem: lazy loading does hidden I/O at attribute access. The code reads like plain Python, but each dot can be a network round trip.
How it works: tell SQLAlchemy in the query which relationships you will need, so it loads them together with the parent rows.
selectinload(Order.lines): after the orders query, run one more query:SELECT ... FROM order_lines WHERE order_id IN (1, 2, 3, ...). Two statements, no duplicated parent rows. The right default for "one to many" collections.joinedload(Order.lines): a single query with aLEFT OUTER JOIN. One statement, but every order row is repeated once per line, so 50 orders with 3 lines come back as 150 rows.lazy="raise"on the relationship: make forgetting loud. Touching an unloadedlinesraises an error instead of silently querying.
The joined loading caveat is real, and SQLAlchemy forces you to notice it. If you forget .unique() on a result that joins a collection, it raises an error instead of returning duplicates. Here is the message, and the number of rows the database actually sent.
The trap: the full output above ends with the InvalidRequestError that asks for .unique(), and with 150 raw rows. joinedload on a collection with a LIMIT is worse: the limit applies to joined rows, not to orders, so SQLAlchemy has to wrap the query in a subquery. For paginated lists of orders with lines, selectinload is the safer choice.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Lazy (default) | You rarely touch the relationship, and never in a loop. | N+1 the moment you loop. It also fails in async code (see below). |
selectinload | Lists of parents with a collection. My default for orders and lines. | One extra statement. A very large IN list is split into batches. |
joinedload | A single parent, or a many-to-one link such as Order.customer (one row per order, no duplication). | Row duplication for collections, and trouble with LIMIT. |
subqueryload | Older code. selectinload replaced it for most uses. | Repeats the original query as a subquery. I have not benchmarked it here. |
| A plain join into a response row | Reports and dashboards where you do not need ORM objects. | You build the result shape yourself. |
- Works: setting the loader per query, in the repository, so the endpoint's data needs are visible in one place.
- Fails: loading everything eagerly "just in case", which fetches data you never use. Also failing: checking only the statement count with a 5-row test database. Test with realistic row counts.
- Interview takeaway: "N+1 is lazy loading inside a loop. I count statements in a test, load collections with selectinload, use joinedload for single parents, and can turn on lazy='raise' to make accidents loud."
A good habit is a test that fails when the statement count grows. It is the same event listener as in the demo, wrapped in a fixture, with an assertion such as assert count == 2. That turns "someone added a lazy attribute" into a red CI run instead of a slow Friday.
Sync or async SQLAlchemy
SQLAlchemy 2.0 also has an async API: create_async_engine, AsyncSession, and await session.execute(...). It needs an async driver (asyncpg or psycopg in async mode for PostgreSQL, aiosqlite for SQLite). Under the hood it runs the same sync code inside a small helper called a greenlet, which lets a sync call pause while the event loop does other work.
The price of that trick is visible in one place: lazy loading does not work. An attribute access cannot be awaited, so SQLAlchemy has no way to pause there. Run it and see the real error.
async def main():
engine = create_async_engine("sqlite+aiosqlite://")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
Session = async_sessionmaker(engine, expire_on_commit=False)
async with Session() as s:
s.add_all([Customer(id=1, name="Asha"), Restaurant(id=1, name="BH"),
MenuItem(id=1, restaurant_id=1, name="Biryani", price_cents=24900, stock=9)])
s.add(Order(customer_id=1, restaurant_id=1, total_cents=24900,
lines=[OrderLine(menu_item_id=1, qty=1, price_cents=24900)]))
await s.commit()
print("1) lazy load inside async code")
async with Session() as s:
order = (await s.execute(select(Order))).scalars().first()
try:
print(len(order.lines)) # ❌ TRAP: hidden I/O, no await
except Exception as e:
print(" ", type(e).__name__ + ":", str(e)[:100], "...")
print("2) eager load, then touch the attribute")
async with Session() as s:
order = (await s.execute(select(Order).options(selectinload(Order.lines)))).scalars().first()
print(" lines:", len(order.lines)) # ✅ already loaded
print("3) or ask for it explicitly")
async with Session() as s:
order = (await s.execute(select(Order))).scalars().first()
await s.refresh(order, attribute_names=["lines"])
print(" lines:", len(order.lines))
await engine.dispose()
asyncio.run(main())1) lazy load inside async code
MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected ...
2) eager load, then touch the attribute
lines: 1
3) or ask for it explicitly
lines: 1What you see: MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. It means "you triggered database I/O in a place that is not allowed to wait". The error message is confusing the first time. The cause is nearly always a lazy attribute touched in async code.
There are three fixes: load the relationship eagerly in the query (case 2), refresh it explicitly with await session.refresh(order, attribute_names=["lines"]) (case 3), or, in a handler that returns data, make sure the response model only reads attributes you have loaded. Also note expire_on_commit=False in the sessionmaker: without it, every attribute is expired by a commit, and the next read tries to reload it, which is the same error.
| Option | Pick it when | Cost or catch |
|---|---|---|
Sync Session, endpoints written with plain def | A normal CRUD API. Up to 40 concurrent database calls, which is more than most pools allow anyway. | Each in-flight request uses a thread. The thread limit (40) and the pool size must be considered together. |
Async Session, async def endpoints | Hundreds of concurrent, I/O-bound requests, or one endpoint that fans out to several databases and services at once. | No lazy loading, an async driver, and every library you call must also be async. One blocking call stalls the loop. |
Switch when: the 40 threads are your measured bottleneck (requests queue while the CPU is idle), or you need real concurrency inside one request. Not because async sounds faster. For most order-style CRUD APIs, the database is the slow part, and both styles wait on it just the same. A later question in the drill compares the two with measurements.
Bridge: transactions and the oversold biryani, one level down
A transaction is a group of statements that the database treats as one: all of them take effect, or none do. Other transactions running at the same time see the old data until you commit. That sounds like it should make the biryani bug impossible, but it does not, and the reason is worth understanding.
The bug is not a half-finished transaction. Each request's transaction was perfectly fine on its own. The problem is that the decision ("is there enough stock?") was made in Python using a value read earlier, and by the time of the write, that value was out of date.
The setup: one menu item with stock = 1. Two requests, A and B, each have their own Session. We interleave them by hand, exactly as two real requests can interleave, so that the demo is the same on every run.
Make the invisible visible: the naive "read, check in Python, write" version, then the safe version with one conditional UPDATE.
# ---- NAIVE: read in Python, decide in Python, write the result ----
reset()
a, b = Session(engine), Session(engine) # two requests, two sessions, interleaved
item_a = a.get(MenuItem, 1)
item_b = b.get(MenuItem, 1)
print("A reads stock:", item_a.stock, "| B reads stock:", item_b.stock)
for name, sess, item in (("A", a, item_a), ("B", b, item_b)):
if item.stock >= 1: # both checks pass: they saw the same 1
item.stock = item.stock - 1 # ❌ TRAP: writes an absolute value
sess.commit()
print(f"{name}: order accepted")
a.close(); b.close()
print("final stock:", stock(), " <- two orders accepted for one biryani\n")# ---- SAFE: one atomic conditional UPDATE, check rowcount ----
def take(qty):
with Session(engine) as s:
res = s.execute(update(MenuItem)
.where(MenuItem.id == 1, MenuItem.stock >= qty)
.values(stock=MenuItem.stock - qty))
s.commit()
return res.rowcount == 1 # 1 row changed = we got it
reset()
print("A takes 1:", "accepted" if take(1) else "OUT OF STOCK")
print("B takes 1:", "accepted" if take(1) else "OUT OF STOCK")
print("final stock:", stock())
with Session(engine) as s:
stmt = update(MenuItem).where(MenuItem.id == 1, MenuItem.stock >= 1).values(stock=MenuItem.stock - 1)
print("\nSQL sent:", str(stmt.compile(engine)).replace("\n", " "))A reads stock: 1 | B reads stock: 1
A: order accepted
B: order accepted
final stock: 0 <- two orders accepted for one biryani
A takes 1: accepted
B takes 1: OUT OF STOCK
final stock: 0
SQL sent: UPDATE menu_items SET stock=(menu_items.stock - ?) WHERE menu_items.id = ? AND menu_items.stock >= ?What you see: in the naive run, A and B both read stock = 1, both pass the check, and both are "accepted". Two orders for one biryani. In the safe run, A is accepted and B gets OUT OF STOCK.
Why: the safe version never reads the stock into Python. It sends one statement, UPDATE menu_items SET stock = stock - 1 WHERE id = ? AND stock >= 1, and looks at rowcount. The database checks and changes the row in one step, with a lock on that row. If another transaction got there first, the WHERE clause no longer matches, zero rows change, and we know we lost.
SQLite lets only one writer in at a time, so a real race is hard to produce on it. That is why the demo interleaves two sessions by hand. On PostgreSQL the same naive code races for real, and the atomic UPDATE still wins, because a row-level lock makes the second UPDATE wait for the first to commit and then re-check its WHERE.
Three tools against lost updates
| Option | Pick it when | Cost or catch |
|---|---|---|
Atomic conditional UPDATE ... WHERE stock >= :q | A counter or balance with a simple rule. Stock, seats, quotas. | Only works when the rule fits in a WHERE. You must check rowcount. |
Pessimistic lock: SELECT ... FOR UPDATE | You must read several rows, decide in Python, then write, and conflicts are likely. | Holds row locks while your code runs, so keep the transaction short. Not available on SQLite (SQLAlchemy ignores it there), so test on PostgreSQL. |
Optimistic lock: a version column | Conflicts are rare, and the user edits something for a while (order status changed by kitchen and rider). | The loser gets an error and must retry or re-read. No locks are held. |
The pessimistic version in SQLAlchemy is session.scalars(select(MenuItem).where(MenuItem.id == 1).with_for_update()).one(), which sends SELECT ... FOR UPDATE on PostgreSQL. I did not run it for this chapter: no PostgreSQL server was started, and SQLite does not support row locks, so a SQLite run would prove nothing. Treat this one as documented behaviour, not as something measured here.
The optimistic version I did run. You add a version column and tell the mapper about it with version_id_col. SQLAlchemy then adds AND version = ? to every UPDATE and bumps the number. Two actors read version 1; the first commit makes it 2; the second's UPDATE ... WHERE version = 1 matches nothing.
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
status: Mapped[str]
version: Mapped[int] = mapped_column(default=1)
__mapper_args__ = {"version_id_col": version} # SQLAlchemy adds "AND version = ?" itself
engine = create_engine("sqlite://", echo=False)
Base.metadata.create_all(engine)
with Session(engine) as s:
s.add(Order(id=1, status="CREATED"))
s.commit()
kitchen, rider = Session(engine), Session(engine)
o1, o2 = kitchen.get(Order, 1), rider.get(Order, 1)
print("both read: status =", o1.status, "version =", o1.version)
o1.status = "PREPARING"
kitchen.commit()
print("kitchen committed -> version", o1.version)
o2.status = "CANCELLED" # based on the OLD copy
try:
rider.commit()
except StaleDataError as e:
rider.rollback()
print("rider:", type(e).__name__ + ":", str(e)[:105], "...")
print(" -> API turns this into 409 Conflict and the client re-reads")both read: status = CREATED version = 1
kitchen committed -> version 2
rider: StaleDataError: UPDATE statement on table 'orders' expected to update 1 row(s); 0 were matched. ...
-> API turns this into 409 Conflict and the client re-readsWhat you see: the kitchen's change worked and moved the version to 2. The rider's change, based on the old copy, raised StaleDataError: "expected to update 1 row(s); 0 were matched". An API should turn that into 409 Conflict (or 412 Precondition Failed if the client sent If-Match) and let the client re-read.
Transactions in the service: begin, commit, rollback, savepoints
with session.begin(): is the pattern used throughout QuickBite. It commits at the end of the block, and rolls back if an exception leaves the block. Inside, you can call session.flush() to send pending SQL (for example to get a generated id) without committing.
A savepoint is a transaction inside a transaction. with session.begin_nested(): creates one. If the inner block fails, only its work is undone and the outer transaction carries on. Use it for "try this part, and fall back" logic, such as inserting an idempotency key and catching the duplicate. Savepoints are not free, so do not use one per row in a big loop.
Two rules keep services honest. First, one service method equals one transaction, and the method decides when it ends. Second, never call an external service (a payment provider, an email API) while a database transaction is open, unless you must. The transaction holds a pooled connection and maybe row locks while you wait on someone else's network.
Idiom: Size the connection pool from the fleet, not from the process
The problem: two failures that look opposite. Too small a pool: requests wait for a connection and then fail. Too large, across many processes: the database runs out of connections and refuses everyone, including the service that was fine.
How it works: SQLAlchemy's default pool, QueuePool, keeps up to pool_size connections open (default 5) and allows max_overflow extra ones during bursts (default 10). A request that finds none free waits up to pool_timeout seconds (default 30), then gets an error. The pool is per engine, and there is one engine per worker process.
- Count the worst case: total = pods × workers per pod × (
pool_size+max_overflow). - Compare with the database: PostgreSQL's
max_connectionsdefaults to 100. Keep about 10 slots for admins, migrations and monitoring. - If it does not fit: shrink the pools, run fewer workers per pod, or put a connection pooler (PgBouncer) in front so thousands of client connections share a few dozen real ones.
Make the invisible visible: what a too-small pool looks like. The pool allows 2 connections and no overflow, three requests check out at once, and the wait limit is 1 second.
engine = create_engine(f"sqlite:///{os.path.join(tempfile.mkdtemp(), 'p.db')}",
poolclass=QueuePool, pool_size=2, max_overflow=0, pool_timeout=1)
c1 = engine.connect()
c2 = engine.connect()
print("pool status:", engine.pool.status())pool status: Pool size: 2 Connections in pool: 0 Current Overflow: 0 Current Checked out connections: 2
third checkout failed after 1.00 s
TimeoutError: QueuePool limit of size 2 overflow 0 reached, connection timed out, timeout 1.00 (Background on this error at: https://sqlalche.me/e/20/3o7r)
after c1.close(): third checkout works
pool status: Pool size: 2 Connections in pool: 0 Current Overflow: 0 Current Checked out connections: 2What you see: the third checkout waited exactly the 1.00 s and then raised TimeoutError: QueuePool limit of size 2 overflow 0 reached, connection timed out, timeout 1.00. Once one connection was returned, the next checkout worked. In production with the default 30 s timeout, this error shows up as requests that hang for 30 seconds and then fail.
The usual cause is not "the pool is too small". It is a connection held too long: a transaction left open while calling a slow service, a session that was never closed, or an endpoint that holds a connection while it waits. Making the pool bigger hides the leak until the next traffic peak.
Make the invisible visible: the arithmetic of the whole fleet, with PostgreSQL's default of 100.
"""Connections the fleet can open: workers x pods x (pool_size + max_overflow)."""
PG_MAX = 100
RESERVED = 10 # superuser slots, migrations, a psql session, monitoring
rows = [ # label, pods, workers, pool_size, overflow
("launch week", 2, 2, 5, 5),
("scaled to 6 pods", 6, 2, 5, 5),
("6 pods, 4 workers each", 6, 4, 5, 5),
("20 pods, default pool", 20, 1, 5, 10),
("20 pods, small pool", 20, 1, 2, 1),
]
print(f"Postgres max_connections={PG_MAX}, usable by the app={PG_MAX - RESERVED}")
print(f"{'case':<26}{'pods':>5}{'workers':>8}{'pool':>5}{'ovf':>4}{'worst case':>11} verdict")
for label, pods, w, size, ovf in rows:
worst = pods * w * (size + ovf)
verdict = "OK" if worst <= PG_MAX - RESERVED else f"too many ({worst - (PG_MAX - RESERVED)} over)"
print(f"{label:<26}{pods:>5}{w:>8}{size:>5}{ovf:>4}{worst:>11} {verdict}")Postgres max_connections=100, usable by the app=90
case pods workers pool ovf worst case verdict
launch week 2 2 5 5 40 OK
scaled to 6 pods 6 2 5 5 120 too many (30 over)
6 pods, 4 workers each 6 4 5 5 240 too many (150 over)
20 pods, default pool 20 1 5 10 300 too many (210 over)
20 pods, small pool 20 1 2 1 60 OKWhat you see: the service is fine at launch (40 connections worst case) and breaks at 6 pods (120). The trap is that nothing changed in the code. Scaling out multiplied the pools. The last row shows a fix: 20 pods of one worker each, with pools of 2 plus 1 overflow, which is 60 connections in the worst case.
The trap: counting only pool_size. Overflow connections are real connections, and bursts are exactly when you hit them. Also remember pool_pre_ping=True, which tests a connection before use so that one killed by a firewall or a database restart does not become a user-visible error.
- Works: a small pool per worker (2 to 10),
pool_timeoutset to a few seconds so failures are quick,pool_pre_pingon, and the fleet total checked againstmax_connections. - Fails: raising
pool_sizeto fix timeouts without finding the held connection, and forgetting that the default is5 + 10per worker.
- Interview takeaway: "Total connections are pods times workers times pool size plus overflow. I compare that with max_connections, keep transactions short, use PgBouncer when the fleet is large, and fail fast with a short pool timeout."
The worker count itself is decided by the CPU, not by the database. See the worker sizing idiom for that side of the same formula.
Bridge: Alembic migrations, one level down
A migration is a small script that moves the database schema from one version to the next, stored in version control next to the code. Alembic keeps a table in your database, alembic_version, holding the id of the current revision. alembic upgrade head runs every script between "where the database is" and "the latest".
Alembic can write the script for you. alembic revision --autogenerate compares two things: the tables in the live database, and your SQLAlchemy models (Base.metadata). Wherever they differ, it writes the operations that would make the database match the models.
The setup: an Alembic project next to the demos (alembic_demo/). env.py imports the QuickBite Base.metadata. The database is an empty SQLite file. The first autogenerate creates the whole schema; then a "developer" adds a nullable delivery_note column and an index on orders.status, and we autogenerate again.
$ alembic init migrations
$ alembic revision --autogenerate -m "initial schema" --rev-id 0001
INFO [alembic.autogenerate.compare.tables] Detected added table 'order_lines'
INFO [alembic.autogenerate.compare.constraints] Detected added index 'ix_order_lines_order_id' on '('order_id',)'
Generating .../migrations/versions/0001_initial_schema.py ... done
$ alembic upgrade head
INFO [alembic.runtime.migration] Running upgrade -> 0001, initial schema
# ... developer edits the models: new column + new index ...
$ alembic revision --autogenerate -m "add delivery note and status index" --rev-id 0002
INFO [alembic.autogenerate.compare.tables] Detected added column 'orders.delivery_note'
INFO [alembic.autogenerate.compare.constraints] Detected added index 'ix_orders_status' on '('status',)'
Generating .../migrations/versions/0002_add_delivery_note_and_status_index.py ... done op.create_table('orders',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('customer_id', sa.Integer(), nullable=False),
sa.Column('restaurant_id', sa.Integer(), nullable=False),
sa.Column('status', sa.String(length=20), nullable=False),
sa.Column('total_cents', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['customer_id'], ['customers.id'], ),
sa.ForeignKeyConstraint(['restaurant_id'], ['restaurants.id'], ),
sa.PrimaryKeyConstraint('id')
)def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('orders', sa.Column('delivery_note', sa.String(length=200), nullable=True))
op.create_index('ix_orders_status', 'orders', ['status'], unique=False)
# ### end Alembic commands ###What you see: exactly the operations that were missing, with a matching downgrade() that reverses them. The header comment is honest: "auto generated by Alembic - please adjust!". Reading the generated file before committing it is part of the job, not an optional step.
What autogenerate cannot know
Autogenerate sees schema differences. It cannot see your intent, and it does not look at data. Four things it handles badly:
- Renames: a renamed column or table looks like "one thing removed, one thing added". Run it and see below.
- Data: filling a new column for existing rows is something you write by hand, usually as a batched
UPDATE. - Server defaults and some constraints: changes to server defaults, check constraints and some index options are not detected unless you switch on the matching comparison settings in
env.py. Check the Alembic docs for the version you pin. - Safety: it will happily write
nullable=Falsefor a new column on a table that already has rows, and the migration fails or locks.
class OldBase(DeclarativeBase): pass
class NewBase(DeclarativeBase): pass
class OldItem(OldBase):
__tablename__ = "menu_items"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] # the database has "name"
class NewItem(NewBase):
__tablename__ = "menu_items"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] # the model now says "title"
engine = create_engine("sqlite://")
OldBase.metadata.create_all(engine) # the live database
with engine.connect() as conn:
diff = produce_migrations(MigrationContext.configure(conn), NewBase.metadata)
print(render_python_code(diff.upgrade_ops))# ### commands auto generated by Alembic - please adjust! ###
op.add_column('menu_items', sa.Column('title', sa.String(), nullable=False))
op.drop_column('menu_items', 'name')
# ### end Alembic commands ###What you see: a model rename from name to title became add_column('title', nullable=False) followed by drop_column('name'). Run on a live table, that adds a NOT NULL column to rows that have no value for it, and then throws away every menu item name. The correct hand edit is op.alter_column('menu_items', 'name', new_column_name='title').
Idiom: Expand and contract migrations
The problem: during a rolling deploy, old and new versions of your code run at the same time against one database, for minutes. A migration that only the new code understands breaks the old pods. A migration that locks a big table freezes both. One QuickBite deploy ran ALTER TABLE orders ADD COLUMN ... NOT NULL DEFAULT ... on a table of 40 million rows, and orders stopped for four minutes while the database rewrote and locked it.
How it works: split one breaking change into several small safe ones. First expand (add the new shape next to the old), then migrate the data and the code, then contract (remove the old shape). Every intermediate state works with both old and new code.
- Add, nullable:
ADD COLUMN phone_e164 textwith no default and no NOT NULL. On PostgreSQL this is quick because it only changes the catalog. - Write both, backfill: new code writes the old and the new column. A job fills the new column for old rows in batches of a few thousand, each in its own short transaction.
- Switch reads: new code reads the new column. Old code, if it is still running, still works because the old column is still written.
- Enforce: once every row is filled, add
NOT NULL(on PostgreSQL, add aCHECK ... NOT VALID, thenVALIDATE CONSTRAINT, to avoid a long lock; check the docs for your version). - Drop the old column in a later release, when no deployed code mentions it.
Indexes need the same care. A plain CREATE INDEX on a large PostgreSQL table blocks writes while it builds. CREATE INDEX CONCURRENTLY does not, but it cannot run inside a transaction, so in Alembic you wrap it in with op.get_context().autocommit_block():.
def upgrade() -> None:
# step 1 (expand): nullable, no default, instant on PostgreSQL
op.add_column("customers", sa.Column("phone_e164", sa.String(16), nullable=True))
# index without blocking writers: must run outside a transaction
with op.get_context().autocommit_block():
op.create_index("ix_customers_phone_e164", "customers", ["phone_e164"],
postgresql_concurrently=True)
# step 2 (backfill) is a separate job, not part of the schema migration:
# UPDATE customers SET phone_e164 = normalise(phone)
# WHERE id BETWEEN :lo AND :hi AND phone_e164 IS NULL; -- batches of 5,000The trap: thinking the migration is one step because Alembic made one file. Each deploy is one release, and the "switch" and "contract" steps are separate releases. Another trap: running migrations at the start of every pod. With 20 pods starting together, 20 processes race to migrate. Run migrations as one job before the rollout (a later drill question covers this).
- Works: renames, type changes, splitting a column, adding NOT NULL to big tables, with no downtime.
- Fails: when the team skips the middle steps to save a release. That is when you get the four-minute lock, or a rollback that cannot work because the old column is gone.
- Interview takeaway: "Old and new code run together during a deploy, so I never make a breaking schema change in one step. I expand, backfill in batches, switch reads, enforce, and only then drop, using concurrent index builds on large tables."
For deployment mechanics, see Chapter E9 and Chapter E10 (rolling updates and migration jobs). For the general ideas behind schema evolution in APIs, Chapter E6 covers versioning.
Bridge: the lost reply, one level down
One more incident, the most expensive of the launch. A customer on a train taps "Place order". The request reaches QuickBite, the order is created, and the response is on its way back when the phone loses signal. The app sees a timeout.
The app does what a good client does and retries the POST. QuickBite receives a second request with the same body and, having no way to know it is a repeat, creates a second order. The kitchen cooks two dinners, and the customer is charged twice.
This is the same lost-reply problem that Chapter E7 describes for services and Chapter E17 for Kafka producers. From the sender's side, "my request failed" and "my request worked but the answer was lost" look identical. GET, PUT and DELETE are safe to repeat by definition. POST is not. The fix is to make a POST repeatable on purpose. See Chapter E6 for where this fits in API design.
Idiom: Idempotency key
The problem: the client cannot tell a lost request from a lost reply, so it must be allowed to retry, and the server must make the retry harmless.
How it works: the client generates a unique string (a UUID) for each intended order and sends it in an Idempotency-Key header. The server stores the key together with the response it produced, in the same transaction as the order. A repeat with the same key gets the stored response back, with the same order id.
- First request: no row for this key. Create the order, reserve stock, insert a row into
idempotency_keys(key, customer_id, request_hash, response_json), and commit all of it together. - Same key, same body: the row exists and the
request_hashmatches. Return the stored response. Nothing is created. - Same key, different body: that is a client bug (the key was reused for a different order). Reject it with 422 (or 409). Do not guess.
- Two requests with the same key at the same instant: both find no row. Both try to insert it. The primary key lets exactly one succeed, and the other gets an
IntegrityError, rolls back, and returns the winner's response.
The setup: the service below, in chunks. First the request models and the exceptions.
class OrderLineIn(BaseModel):
menu_item_id: int
qty: int = Field(gt=0, le=50)
class OrderCreate(BaseModel):
restaurant_id: int
lines: list[OrderLineIn] = Field(min_length=1)
class OutOfStock(Exception): ...
class KeyReuse(Exception): ...class OrderService:
def __init__(self, session: Session):
self.session = session
def create_order(self, customer_id: int, key: str, body: OrderCreate) -> tuple[dict, bool]:
request_hash = hashlib.sha256(body.model_dump_json().encode()).hexdigest()
try:
with self.session.begin(): # one transaction: order + stock + key
stored = self._find_key(key)
if stored is None:
result = self._insert_order(customer_id, body)
self.session.add(IdempotencyKey(key=key, customer_id=customer_id,
request_hash=request_hash,
response_json=json.dumps(result)))
return result, False
except IntegrityError: # a concurrent twin committed first
self.session.rollback()
with self.session.begin():
stored = self._find_key(key)
if stored.customer_id != customer_id or stored.request_hash != request_hash:
raise KeyReuse(key)
return json.loads(stored.response_json), TrueRead create_order slowly. Everything happens inside with self.session.begin(): the lookup, the order, the stock update, and the key insert. They commit together, or none of them does. The except IntegrityError branch handles the race in step 4.
def _find_key(self, key):
return self.session.get(IdempotencyKey, key)
def _insert_order(self, customer_id, body) -> dict:
order = Order(customer_id=customer_id, restaurant_id=body.restaurant_id)
total = 0
for line in body.lines:
item = self.session.get(MenuItem, line.menu_item_id)
took = self.session.execute(update(MenuItem) # atomic: check and decrement in one statement
.where(MenuItem.id == line.menu_item_id, MenuItem.stock >= line.qty)
.values(stock=MenuItem.stock - line.qty)).rowcount
if took != 1:
raise OutOfStock(item.name)
total += item.price_cents * line.qty
order.lines.append(OrderLine(menu_item_id=item.id, qty=line.qty, price_cents=item.price_cents))
order.total_cents = total
self.session.add(order)
self.session.flush() # assigns order.id
return {"order_id": order.id, "status": order.status, "total_cents": total}app = FastAPI()
@app.post("/v1/orders", status_code=201)
def post_order(body: OrderCreate, idempotency_key: str = Header(min_length=8, max_length=80),
session: Session = Depends(get_session)):
customer_id = 1 # from the JWT in the real app
try:
result, replayed = OrderService(session).create_order(customer_id, idempotency_key, body)
except OutOfStock as e:
raise HTTPException(409, f"out of stock: {e}")
except KeyReuse:
raise HTTPException(422, "Idempotency-Key was already used with a different request body")
return resultThe stock rule is the atomic UPDATE ... WHERE stock >= qty from the oversell bug: one statement, and rowcount tells us whether we got the item. If the rowcount is not 1, the whole transaction rolls back, and no key is stored. A failed attempt can therefore be retried with the same key later, for example after a restock.
Make the invisible visible: four scenarios through TestClient: a retry, a key reused with another body, an out-of-stock failure, and a concurrent twin. For the last one, the demo forces the race: the first lookup is made to miss because the twin commits just before our insert.
if __name__ == "__main__":
with SessionLocal.begin() as s:
s.add_all([Customer(id=1, name="Asha"), Restaurant(id=1, name="BH"),
MenuItem(id=1, restaurant_id=1, name="Biryani", price_cents=24900, stock=3)])
c = TestClient(app)
body = {"restaurant_id": 1, "lines": [{"menu_item_id": 1, "qty": 2}]}
h = {"Idempotency-Key": "mobile-retry-0001"}
print("1) same key, same body, sent twice (a mobile retry)")
for n in (1, 2):
r = c.post("/v1/orders", json=body, headers=h)
print(f" try {n}: {r.status_code} {r.json()}")
print(f" orders in database: {count(Order)} stock left:",
SessionLocal().get(MenuItem, 1).stock)
print("2) same key, DIFFERENT body")
r = c.post("/v1/orders", json={**body, "lines": [{"menu_item_id": 1, "qty": 1}]}, headers=h)
print(" ", r.status_code, r.json())
print("3) new key, but only 1 biryani left and we ask for 2")
r = c.post("/v1/orders", json=body, headers={"Idempotency-Key": "mobile-retry-0002"})
print(" ", r.status_code, r.json())
print(f" orders: {count(Order)} keys stored: {count(IdempotencyKey)} (the failed order left no key)")
print("4) a concurrent twin: both requests miss the lookup, one INSERT wins")
with SessionLocal.begin() as s:
s.get(MenuItem, 1).stock = 10 # restock so stock is not the story here
real_find = OrderService._find_key
calls = {"n": 0}
def racing_find(self, key):1) same key, same body, sent twice (a mobile retry)
try 1: 201 {'order_id': 1, 'status': 'CREATED', 'total_cents': 49800}
try 2: 201 {'order_id': 1, 'status': 'CREATED', 'total_cents': 49800}
orders in database: 1 stock left: 1
2) same key, DIFFERENT body
422 {'detail': 'Idempotency-Key was already used with a different request body'}
3) new key, but only 1 biryani left and we ask for 2
409 {'detail': 'out of stock: Biryani'}
orders: 1 keys stored: 1 (the failed order left no key)
4) a concurrent twin: both requests miss the lookup, one INSERT wins
201 {'order_id': 2, 'status': 'CREATED', 'total_cents': 24900}
orders: 2 stock: 9 (one new order; the loser's stock decrement was rolled back)What you see:
- Scenario 1: two identical POSTs return the same
order_idandtotal_cents. The database has one order, and stock fell from 3 to 1, not to minus 1. - Scenario 2: the same key with a different body is refused with 422, so a buggy client cannot silently get the wrong order back.
- Scenario 3: out of stock gives 409 and leaves no key behind, so the client is free to retry with the same key later.
- Scenario 4: the twin won the insert. Our request reached the key insert, failed with
IntegrityError, rolled back (including its own stock decrement, which is why stock ends at 9 and not 8), and returned the twin's order. One new order, not two.
The trap: doing the idempotency check outside the order's transaction ("check the key, then create the order, then store the key"). Between those steps a crash leaves an order with no key, and the retry creates another. The key row and the order must commit together.
Three further details a reviewer will ask about. Scope the key to the customer: the table stores customer_id, and the service compares it, so one customer cannot replay another's key. Expire old keys: a nightly job deletes rows older than 24 hours (the time you promise to honour retries). Hash the body, do not compare raw text: the demo hashes model_dump_json(), so field order and spacing in the client's JSON do not matter.
- Works: any non-idempotent
POSTthat creates something or moves money, retried by mobile clients, gateways or queue consumers. - Fails: if the key is generated per attempt rather than per intent (the client makes a new UUID on each retry), or if the stored response is not the one the first call returned.
- Interview takeaway: "The client sends one Idempotency-Key per intended action. The server stores key, request hash and response in the same transaction as the work, the primary key resolves concurrent duplicates, and a different body with the same key is rejected."
Publishing events without a dual write
After an order is created, other systems want to know: the kitchen display, a notification service, analytics. The tempting code is "save the order, then publish to Kafka". These are two separate systems, and the process can crash between them. Then you have an order nobody heard about, or, if you publish first, an event for an order that never saved. That is a dual write.
The fix is the transactional outbox: write the event as a row in an outbox table, in the same database transaction as the order. A separate relay process reads unpublished rows and sends them to Kafka later. The database transaction is the only place where "order exists" and "event exists" are decided together.
def place_order(total, fail=False):
with Session(engine) as s, s.begin():
order = Order(total_cents=total)
s.add(order)
s.flush()
s.add(Outbox(topic="orders.created", payload=json.dumps({"order_id": order.id, "total_cents": total})))
if fail:
raise RuntimeError("payment service said no") # both rows roll backsecond order failed: payment service said no
orders: 1 | outbox rows: 1
outbox: orders.created {"order_id": 1, "total_cents": 24900} published = FalseWhat you see: the first order committed with its outbox row. The second order failed after both rows had been added, and neither survived: one order, one outbox row. The event can never describe an order that does not exist.
The relay is a polling loop, or change-data-capture on the outbox table, which sends rows to the broker and marks them published. Delivery is "at least once", so consumers must handle duplicates, which is the same idempotency idea one level up. The pattern is explained in Chapter E7 (the transactional outbox), and the CDC relay in Chapter E17 (outbox via CDC).
Stack table: which persistence layer?
| Option | Pick it when | Cost or catch |
|---|---|---|
| SQLAlchemy ORM (2.0 style) | A domain with relationships, a unit of work, and several developers. My default for QuickBite. | The hidden I/O of lazy loading and the Session's lifecycle must be understood. This section is that cost. |
| SQLAlchemy Core | Reports, bulk inserts, and queries where objects get in the way. | You build results yourself. It can sit beside the ORM in the same app. |
| SQLModel | Small services that want one class to be both the table and the Pydantic model. | It was not installed here and I did not run it. One class doing both jobs works against the three-model rule, and it is a thin layer over SQLAlchemy. |
| Raw psycopg 3 | Few queries, performance-critical paths, or a team that prefers SQL. | No identity map, no unit of work, and more manual mapping. Parameterise every query. |
| Django ORM | You are already in Django. | Tied to Django's models and request cycle. Not a drop-in for FastAPI. |
| Tortoise ORM (async-first) | A fully async code base that wants a Django-like API. | A smaller ecosystem and fewer tools for migrations and tuning. Not run here. |
Switch when: an ORM query becomes harder to read than the SQL it produces (drop to Core or text() with bound parameters), or the service is a thin wrapper around three queries (raw psycopg may be simpler). Do not switch because of speed alone: measure first. In most order-style APIs the bottleneck is the number of round trips, which you now know how to count.
That finishes the data layer. The next section, security, uses the pieces built here: the same get_session, the same service, and the ownership checks that live in the repository.
06 · Security and behaviourAuthentication, Authorisation, Errors and API Behaviour
An API is a front door that strangers can knock on all day. This section covers how the door checks who is knocking (JWT validation), what each person may open (scopes and ownership), what it says when it refuses (problem details), and the small behaviours that decide whether clients trust it: pagination that does not skip rows, partial updates that do not erase data, conditional requests, and timeouts.
Here is a launch-week story from QuickBite. Two bugs reached production in the same release, and both were one line long.
The first: a developer was debugging a token problem on a Friday evening and changed the token check to jwt.decode(token, options={"verify_signature": False}). The comment said "temporary". The code worked, the demo worked, and the line shipped on Monday.
With that line, the server reads the claims inside a token but never checks who wrote them. Anyone can build a token that says "sub": "2" and be customer 2. A security researcher did exactly that in four minutes and sent QuickBite a polite email.
The second bug was quieter. GET /v1/orders/{id} looked the order up by its id and returned it. It never asked whose order it was. Order ids are small integers that count up, so a customer who changed /orders/1041 to /orders/1042 saw a stranger's address and phone number. This class of bug has a name: IDOR, insecure direct object reference.
Both bugs are easy to write and easy to miss, because the happy path works perfectly. You only see them when you play the attacker. So that is what we do next: run both bugs against the canonical QuickBite app and then run the fixes.
Make the invisible visible: the forged token, accepted by the "temporary" line and refused by the real check. Script: jwt_checks.py, run with PyJWT 2.14.
forged = jwt.encode({**good, "sub": "2"}, "attacker-chosen-secret-of-sufficient-length", algorithm="HS256")
print("forged, signature not checked ->", jwt.decode(forged, options={"verify_signature": False})["sub"]) # ❌ TRAP
try:
verify_token(forged, settings) # ✅
except jwt.InvalidTokenError as e:
print("forged, real verify_token ->", type(e).__name__)
valid RS256 token -> accepted, sub=1
expired 60 s ago -> ExpiredSignatureError: Signature has expired
wrong audience -> InvalidAudienceError: Audience doesn't match
wrong issuer -> InvalidIssuerError: Invalid issuer
no exp claim -> MissingRequiredClaimError: Token is missing the "exp" claim
alg none (unsigned) -> InvalidAlgorithmError: The specified alg value is not allowed
HS256 signed with the public key -> InvalidAlgorithmError: The specified alg value is not allowed
signed by someone else's key -> InvalidSignatureError: Signature verification failed
garbage -> DecodeError: Invalid header padding
# the 'temporary' bug: verify_signature=False accepts a forgery
forged, signature not checked -> 2 (accepted: any attacker is customer 2)
forged, real verify_token -> InvalidAlgorithmErrorWhy: a JWT is three base64 pieces: header, claims, signature. The first two are readable by anyone. Only the signature proves who made the token, and only if the server checks it with a key the attacker does not have. Skip the check and the claims are just text the attacker wrote.
Now the second bug. The script idor_demo.py adds a deliberately naive route next to the real one and calls both as customer 2, asking for customer 1's order.
Naive: look up by id
The route trusts the id in the URL. Authentication passed, so it assumes everything is allowed.
@app.get("/naive/orders/{order_id}")
def naive_get(order_id: int, session, user):
o = session.get(Order, order_id)
# ❌ TRAP: whose order is it?
return o
Correct: scope by owner
The owner is part of the query. A stranger's id matches no row, so the answer is "not found".
stmt = select(Order).where(Order.id == order_id)
if customer_id is not None:
stmt = stmt.where(
Order.customer_id == customer_id) # ✅
return session.scalars(stmt).first()
The shift: authentication answers "who are you?"; the data query must also answer "is this yours?". The second question belongs in the WHERE clause, not in a hope.
{"order_id": 1, "customer_id": 1, "total_cents": 300, "event": "order_created", "level": "info", "timestamp": "2026-11-24T17:14:16.246783Z", "request_id": "994c927b83cf438dae58cdc659945411"}
customer 1 placed order 1; customer 2 is the attacker
naive : 200 {'id': 1, 'customer_id': 1, 'total_cents': 300}
fixed : 404 Order not found - Order not found
missing: 404 Order not found (same answer: nothing leaks)
owner : 200Notice the last two lines before the owner check. A real order that belongs to someone else and an order id that does not exist give the same answer, 404 Order not found. We come back to why in the ownership idiom below.
Bridge: issuing tokens versus validating tokens
Security talk mixes two jobs that should not be mixed. One job is issuing a token: checking a password or a login with Google, then signing a short statement such as "this is customer 7, until 14:30". The other job is validating a token: reading that statement on every request and deciding whether to believe it.
Your API has to do the second job, always. It should rarely do the first. Issuing means storing password hashes, rate limiting logins, handling password resets, multi-factor prompts, social logins and account lockouts. That is a product in itself, and getting it slightly wrong is how breaches happen.
So the usual shape is: an identity provider (Keycloak, Auth0, Amazon Cognito, Microsoft Entra ID, or similar) issues tokens, and every API validates them using the provider's public key. The API never sees a password.
FastAPI's documentation shows an "OAuth2 password flow" with a /token endpoint that checks a username and password and issues a JWT. It is a teaching example, and it teaches the mechanics well. It is acceptable for a small internal tool with one user table, no social login, and a team that accepts owning password storage. For a public product, use a provider and validate its tokens.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Hosted provider (Auth0, Cognito, Entra ID) | You want login, MFA and social sign-in without running them, and per-user pricing is acceptable | Vendor lock-in; cost grows with active users; you still validate every token yourself |
| Self-hosted provider (Keycloak, Authentik) | Data residency or cost rules out hosted; you have someone to patch and upgrade it | You run a critical service; upgrades and database backups are your job |
Your own /token endpoint (FastAPI password flow) | One internal tool, a few dozen users, no external login, and you hash with Argon2 or bcrypt | You own password storage, reset flows and lockouts; most teams outgrow it inside a year |
| Session cookies from a monolith | A browser app on the same site as the API | Needs CSRF protection; awkward for mobile apps and other services |
Idiom: Verify a JWT with an allow-list
The problem: a token is data sent by the client. If the server lets the token decide how it is checked (which algorithm, which key, whether to check at all), the attacker decides.
How it works: the server decides everything in advance, from its own configuration: which algorithm is allowed, which key to use, which issuer and audience to expect, and which claims must be present. The token only supplies the data to be checked.
- Fix the allow-list in config:
algorithms=["RS256"]comes fromSettings, never from the token's header. - Pick the key from a trusted place: a PEM public key in settings, or the provider's JWKS (a published list of public keys) fetched and cached with
PyJWKClient. The token'skid(key id) only chooses among keys we already trust. - Demand the claims:
options={"require": ["exp","iss","aud","sub"]}. Withoutrequire, a token that simply omitsexpnever expires. - Check who it is for:
issuer=andaudience=. A valid token meant for a different API is still not for you.
jwt_checks.py.Here is the verification function from the canonical app, app/security.py. It is short on purpose: every line is one decision.
def verify_token(token: str, settings: Settings) -> dict:
"""Every check in one place. Raises jwt.InvalidTokenError (or a subclass) on any failure."""
algorithms = settings.jwt_algorithms() # allow-list from OUR config, never from the token header
if settings.jwt_jwks_url:
key = _jwk_client(settings.jwt_jwks_url).get_signing_key_from_jwt(token).key
elif settings.jwt_public_key:
key = settings.jwt_public_key
elif settings.jwt_secret:
key = settings.jwt_secret.get_secret_value()
else:
raise RuntimeError("no JWT verification key configured")
return jwt.decode(
token, key,
algorithms=algorithms,
audience=settings.jwt_audience,
issuer=settings.jwt_issuer,
options={"require": ["exp", "iss", "aud", "sub"]},
leeway=5,
)The leeway=5 allows five seconds of clock difference between the identity provider's server and yours. Without it, a token issued "now" by a server whose clock is two seconds ahead is rejected as not yet valid. More than a few seconds of leeway is a smell: fix the clocks instead (NTP).
Make the invisible visible: nine tokens, one function. Each failure raises a different PyJWT exception. Real output from jwt_checks.py, using a freshly generated 2048-bit RSA key pair (the cryptography package is installed).
valid RS256 token -> accepted, sub=1
expired 60 s ago -> ExpiredSignatureError: Signature has expired
wrong audience -> InvalidAudienceError: Audience doesn't match
wrong issuer -> InvalidIssuerError: Invalid issuer
no exp claim -> MissingRequiredClaimError: Token is missing the "exp" claim
alg none (unsigned) -> InvalidAlgorithmError: The specified alg value is not allowed
HS256 signed with the public key -> InvalidAlgorithmError: The specified alg value is not allowed
signed by someone else's key -> InvalidSignatureError: Signature verification failed
garbage -> DecodeError: Invalid header padding
# the 'temporary' bug: verify_signature=False accepts a forgery
forged, signature not checked -> 2 (accepted: any attacker is customer 2)
forged, real verify_token -> InvalidAlgorithmErrorRead the two lines about algorithms carefully, because they are the attacks you will be asked about.
alg: none. The JWT standard allows a token to declare "I am unsigned". A library that obeys the header accepts it, because nothing needs verifying. We pass algorithms=["RS256"], so the library says InvalidAlgorithmError before it looks at anything else.
Algorithm confusion. RS256 uses a private key to sign and a public key to verify. HS256 uses one shared secret for both. The public key is, by definition, public. If the server picks the verification algorithm from the token's header and the attacker writes HS256, a careless library uses the public key as the shared secret, and the attacker, who knows the public key, signs a perfect token. The allow-list stops it: HS256 is not in ["RS256"].
One honest note from running this. PyJWT 2.14 itself refuses to create an HS256 token with a PEM public key as the secret (InvalidKeyError), so the script builds that token by hand with hmac, as an attacker would. The defence on our side is the allow-list, not the library's politeness.
- Works: server-side allow-list, required claims, issuer and audience checked, keys from config or a cached JWKS. Every failure is one exception type you can log by name.
- Fails:
verify_signature=False"just for debugging";algorithmsread from the token header; norequire, so a token withoutexplives forever; not checkingaud, so a token for your billing API opens your orders API. - Interview takeaway: "The token never chooses how it is verified. I fix the algorithm list, the key, the issuer and the audience in my own config, and I require
exp, so the only thing the client controls is data I then check."
Bridge: JWKS and key rotation, one level down
Identity providers rotate their signing keys, often every few weeks. If your API had one PEM pasted into config, every rotation would be an outage. So providers publish a JWKS (JSON Web Key Set) at a URL: a JSON list of public keys, each with a kid.
Each token header names the kid that signed it. PyJWKClient(url) downloads the set, caches it, finds the key with that kid, and re-downloads when it sees an unknown one. In the canonical app this is the jwt_jwks_url setting, and _jwk_client is wrapped in lru_cache so one client (and one cache) lives for the whole process.
Two details matter in production. First, the download is a blocking network call, so it happens inside a plain def dependency, which FastAPI runs in the threadpool, not on the event loop. Second, set a short network timeout and cache the keys for an hour or so; a provider outage should not turn into your outage the moment the cache expires. The test test_jwks_mode_uses_the_key_the_client_returns replaces the client with a fake, which is how you test this without a network.
| Option | Pick it when | Cost or catch |
|---|---|---|
| PyJWT 2.14 (we use it) | You validate tokens in an API; small, well known, includes PyJWKClient | Signing and JWE support are basic; you must pass the right options yourself |
| Authlib | You need a full OAuth 2 / OpenID Connect client or server, JWE and JWK handling | Bigger surface to learn; more than a pure resource server needs |
| python-jose | Older tutorials use it | Slow maintenance history; most new projects pick PyJWT or Authlib instead (check its status before adopting it) |
| Gateway validation (Envoy, Kong, API gateway) | Many services, one policy; you want invalid tokens to die at the edge | Services still need to read claims, and an internal service reachable without the gateway is unprotected |
Idiom: Authentication as a dependency, ownership in the query
The problem: checks written inside each endpoint get forgotten in the endpoint someone adds next month. And a scope check alone does not stop IDOR: "customer 2 may read orders" does not mean "customer 2 may read customer 1's order".
How it works: split it into three layers, each checked in a different place.
- Authentication (who): a dependency
get_current_userreads theAuthorization: Bearerheader, runsverify_token, and returns a smallUser(id, role, scopes). Failure is 401 with aWWW-Authenticate: Bearerheader. - Coarse authorisation (what kind of action):
require_scope("orders:write")is a function that returns a dependency. It checks that the scope is in the token. Failure is 403. - Fine authorisation (which object): the repository query includes
WHERE customer_id = :user_id. Failure is "no row", which becomes 404.
The first two live in app/security.py. The third lives in OrderRepository.get_order. Here is how an endpoint opts in; the whole policy is its parameter list.
SessionDep = Annotated[Session, Depends(get_session)]
Reader = Annotated[User, Depends(require_scope("orders:read"))]
Writer = Annotated[User, Depends(require_scope("orders:write"))]Annotated[User, Depends(...)] turns a dependency into a type you can reuse. Reader and Writer are written once at the top; endpoints say user: Writer. Adding a new endpoint without a guard means writing a parameter that is visibly missing, which is easier to spot in review than a forgotten if in a function body.
Why 404 and not 403 for someone else's order? A 403 says "this order exists, but you may not see it". That tells an attacker which ids are real, which is already a leak: they can count your customers' orders, or confirm that a particular id exists. Returning 404 for both "does not exist" and "is not yours" gives them nothing. The tests pin it: test_idor_other_customers_order_is_404 checks GET and PATCH. A 403 is still right for the scope check, because the scope is about the caller, not about a particular object.
{"order_id": 1, "customer_id": 1, "total_cents": 300, "event": "order_created", "level": "info", "timestamp": "2026-11-24T17:14:16.246783Z", "request_id": "994c927b83cf438dae58cdc659945411"}
customer 1 placed order 1; customer 2 is the attacker
naive : 200 {'id': 1, 'customer_id': 1, 'total_cents': 300}
fixed : 404 Order not found - Order not found
missing: 404 Order not found (same answer: nothing leaks)
owner : 200Admins are the one exception, and the repository handles it explicitly with customer_id=None meaning "any owner". It is a visible, tested decision (test_admin_can_read_any_order), not a hole.
- Works: one place for each question; endpoints cannot forget authentication; the ownership filter sits in the same query that fetches the data, so it cannot be skipped by a later code path.
- Fails: checking ownership after loading ("fetch, then
if order.customer_id != user.id") works until someone adds a second endpoint that forgets theif; trusting acustomer_idfield in the request body instead of the token'ssub. - Interview takeaway: "Authentication and scopes are dependencies; object ownership is part of the query. Someone else's id and a missing id both return 404, so I leak nothing about what exists."
Spring Boot · Security
A filter chain authenticates; an annotation checks the rule on the method.
// illustrative
@PreAuthorize("hasAuthority('SCOPE_orders:write')")
@PostMapping("/v1/orders")
OrderOut create(@RequestBody @Valid OrderIn in,
@AuthenticationPrincipal Jwt jwt) {
return service.create(jwt.getSubject(), in);
}
FastAPI · security dependencies
No filter chain. A dependency is the check, and it is visible in the signature.
@router.post("", status_code=201,
response_model=OrderOut)
def create_order(payload: OrderCreate,
session: SessionDep,
user: Writer): # 401 / 403 here
return OrderService(session).create_order(
user.id, payload)
The shift: Spring applies security as a layer around your methods (filters plus method proxies); FastAPI makes it an ordinary argument that runs before the function body. Security(dep, scopes=["orders:write"]) exists too and adds the scope to the OpenAPI document, so the Swagger page shows which routes need what.
Bridge: how the 401 and 403 are produced, one level down
FastAPI collects every dependency in a route's signature before calling the function. If a dependency raises HTTPException, FastAPI stops, never calls the endpoint, and hands the exception to the exception handlers. That is the entire mechanism: "security" is "a dependency that sometimes raises".
The HTTPBearer(auto_error=False) helper only parses the header into an object, or gives None. We set auto_error=False so we can raise our own 401 with the right WWW-Authenticate header; the default raises 403 for a missing header in some versions, which is a historical quirk and confuses clients.
The status codes carry meaning for clients. 401 Unauthorized actually means "unauthenticated": no valid credentials, try again with a token. 403 Forbidden means "I know who you are and the answer is no", so a new login will not help.
API keys for service-to-service calls
Not every caller is a person with a login. A partner's system that calls your API once a night can use an API key: a long random string. Used well, it is simple. Used badly, it is a password stored in plain text.
- Generate it with a real random source:
secrets.token_urlsafe(32), about 43 characters and 256 bits of randomness. Show it to the owner once. - Store only a hash: SHA-256 of the key is enough, because the key itself is random (unlike a password, there is nothing to guess, so a slow hash adds nothing). Keep a short non-secret prefix in clear text so people can identify "qb_live_7f3a..." in a list.
- Compare in constant time:
hmac.compare_digest(a, b). A plain==stops at the first different character, and on a network that tiny timing difference can, in theory, leak the key one character at a time. - Allow two keys at once for rotation: the owner creates key B, switches their system over, then you revoke key A. A design with exactly one key per client forces downtime at every rotation.
import hashlib, hmac, secrets
def new_key() -> tuple[str, str]:
key = "qb_live_" + secrets.token_urlsafe(32) # shown once
return key, hashlib.sha256(key.encode()).hexdigest() # store the hash
def is_valid(presented: str, stored_hash: str) -> bool:
candidate = hashlib.sha256(presented.encode()).hexdigest()
return hmac.compare_digest(candidate, stored_hash) # constant time
An API key identifies a caller; it does not carry scopes or an expiry the way a JWT does, so give each key a row (owner, scopes, created, last used, revoked) and look it up. For anything beyond one or two partners, prefer short-lived tokens from your identity provider using the OAuth 2 client-credentials flow, so that a leaked token dies in an hour.
Bridge: CORS, one level down
CORS (cross-origin resource sharing) confuses people because it is enforced by the browser, not the server. Imagine a customer is logged in to QuickBite in one tab and opens evil.example in another. Without rules, a script on evil.example could call the QuickBite API using the customer's browser. The browser's default rule, the same-origin policy, stops the page from reading the response unless the API says it is fine.
An origin is scheme + host + port: https://app.quickbite.example and https://api.quickbite.example are different origins. So the web app calling the API needs the API's permission.
For "simple" requests the browser just sends the request and then checks the response header Access-Control-Allow-Origin. For anything else (a JSON body, an Authorization header, PATCH) the browser first sends a preflight: an OPTIONS request asking "may this origin send this method with these headers?". Only if the answer is yes does it send the real request.
FastAPI's CORSMiddleware answers preflights. In the canonical app, create_app adds it only when cors_origins is set. Real output:
preflight from https://app.quickbite.example: 200
access-control-allow-methods: GET, POST, PATCH
access-control-max-age: 600
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type, Idempotency-Key
access-control-allow-origin: https://app.quickbite.example
preflight from https://evil.example: 400
access-control-allow-methods: GET, POST, PATCH
access-control-max-age: 600
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type, Idempotency-Key
{"order_id": 1, "customer_id": 1, "total_cents": 300, "event": "order_created", "level": "info", "timestamp": "2026-11-24T17:14:19.480022Z", "request_id": "d69143f6a4e34e2687227e8085dfd138"}
GET 1: 200 ETag W/"79bfb99d77dc8dff" body bytes 197
GET 2 with If-None-Match: 304 body bytes 0
PATCH with fresh If-Match: 200 new ETag W/"091009756fcde4d2"
PATCH with stale If-Match: 412 Precondition FailedThe allowed origin gets 200 and an echo of itself in access-control-allow-origin. The stranger gets 400 and no allow-origin header, so the browser would block the call. Notice that this is not security for your data: curl, Postman and a server-side script ignore CORS completely. If you test with curl and it works but the browser complains, the server is fine; the CORS headers are missing.
Why allow_origins=["*"] with credentials is refused. "Credentials" means cookies or HTTP auth the browser would attach automatically. The CORS rules say a wildcard origin may not be combined with credentials, because "any site may make authenticated calls as the logged-in user" is exactly the attack CORS exists to prevent. Starlette's middleware cannot silently allow it either: with a wildcard, it does not echo credentials. List the real origins instead.
- Works: an explicit list of origins from settings, an explicit list of methods and headers, a long
max_ageso browsers cache the preflight (the output shows 600 seconds). - Fails: using CORS as access control (it is only a browser rule);
["*"]plus cookies; forgettingIdempotency-Keyinallow_headers, so the browser blocks the preflight for exactly the header the mobile web app needs.
Rate limiting
QuickBite's login-adjacent endpoints and its order endpoint need a ceiling per caller, or one buggy client in a retry loop takes the service down. There are three places to put it, and the order matters.
- At the gateway or load balancer first: NGINX, Envoy, an API gateway, a CDN. It rejects the flood before it costs Python any CPU. This is where "100 requests per minute per IP" belongs.
- In the app, for rules that need identity: "customer 7 may place 10 orders per minute". A gateway cannot easily know the customer; the app can, after authentication.
- In the database, for hard business limits: "one open order per customer per restaurant" is a unique index, not a counter.
For in-app limits, a shared counter is needed, because you run several worker processes and several pods; a counter in each process allows N times the limit. That is a Redis counter with an expiry (a fixed or sliding window).
The slowapi library packages this for FastAPI, and the redis client (8.1) is installed on the course machine, but neither slowapi nor a Redis server is, so this chapter describes rather than runs it. Check slowapi's current maintenance status before choosing it; writing 20 lines against Redis INCR plus EXPIRE is a common alternative.
When you refuse, say how to behave: status 429 Too Many Requests and a Retry-After header in seconds. Well-behaved clients wait that long. Without the header, they guess, and most guess "immediately".
Idiom: Errors as RFC 9457 problem details
The problem: by default, every error in a FastAPI app has a different shape. Validation errors are {"detail": [ ... ]}, an HTTPException is {"detail": "text"}, and an unhandled crash is the plain text Internal Server Error. A mobile client needs three code paths, and a stack trace may be one bug away from the response.
How it works: RFC 9457 (which replaced RFC 7807) defines one JSON shape for errors, served as application/problem+json. You register exception handlers once, and every error path produces the same shape.
| Member | Meaning | QuickBite example |
|---|---|---|
type | A URI naming the kind of problem; clients branch on it. Default about:blank | https://api.quickbite.example/problems/out-of-stock |
title | Short, the same for every problem of this type | Item out of stock |
status | The HTTP status again, so it survives being copied into logs | 409 |
detail | One sentence about this occurrence | Not enough stock of 'Chicken biryani' for quantity 9. |
instance | Which request, usually the path | /v1/orders |
| extensions | Any extra members you define | request_id, errors |
The canonical app has four handlers in app/errors.py, from most specific to most general. FastAPI picks the handler for the closest matching exception class.
RequestValidationError→ 422: Pydantic rejected the input. We keeploc,msgandtypefor each error, and dropinputandctx, so we never echo a user's data (a password typed into the wrong field) back or into a log.HTTPException→ its own status: 401, 403, 404, 405, 412 from routing and our guards, all reshaped into problems, with their headers kept (soWWW-Authenticatesurvives).DomainError→ its status: a base class for business rules.OutOfStockis 409,RestaurantClosed409,UnknownMenuItem422,IdempotencyConflict422,OrderNotFound404. Services raise them; they know nothing about HTTP except a number.Exception→ 500: the catch-all. It logs the full traceback with the request id, and answers with a fixed message plus the request id so a customer can quote it to support.
def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(RequestValidationError)
async def on_validation(request: Request, exc: RequestValidationError):
# Keep where / what / which rule; drop "input" and "ctx" so we never echo user data back.
errors = [{"loc": list(e["loc"]), "msg": e["msg"], "type": e["type"]} for e in exc.errors()]
return problem(request, 422, "Validation failed", "The request body or parameters are invalid.",
"https://api.quickbite.example/problems/validation", errors)
@app.exception_handler(StarletteHTTPException)
async def on_http(request: Request, exc: StarletteHTTPException):
return problem(request, exc.status_code, _phrase(exc.status_code), str(exc.detail), headers=exc.headers)
@app.exception_handler(DomainError)
async def on_domain(request: Request, exc: DomainError):
return problem(request, exc.status, exc.title, exc.detail,
f"https://api.quickbite.example/problems/{exc.slug}")
@app.exception_handler(Exception)
async def on_unexpected(request: Request, exc: Exception):
rid = request_id_of(request)
log.error("unhandled_exception", path=request.url.path, request_id=rid,
error=type(exc).__name__, exc_info=True)
return problem(request, 500, "Internal Server Error", "Something went wrong. Quote the request_id to support.")Here are real responses from the canonical app, one per path, from problem_details_demo.py. The 500 is triggered by a route that raises RuntimeError("password is hunter2"); look for that password in the response.
--- validation (422): 422 application/problem+json
{
"type": "https://api.quickbite.example/problems/validation",
"title": "Validation failed",
"status": 422,
"detail": "The request body or parameters are invalid.",
"instance": "/v1/orders",
"request_id": "9db0a1cd74914ee78835cda5007aff2d",
"errors": [
{
"loc": [
"body",
"lines",
0,
"qty"
],
"msg": "Input should be greater than 0",
"type": "greater_than"
}
]
}
--- domain: out of stock (409): 409 application/problem+json
{
"type": "https://api.quickbite.example/problems/out-of-stock",
"title": "Item out of stock",
"status": 409,
"detail": "Not enough stock of 'Chicken biryani' for quantity 9.",
"instance": "/v1/orders",
"request_id": "7ec4cc71e14943e0989c18a9c47ae558"
}
--- HTTPException: 404 route: 404 application/problem+json
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "Not Found",
"instance": "/nope",
"request_id": "b5d8206b302d4b71bd7ae000764da1a7"
}
{"path": "/boom", "request_id": "req-42", "error": "RuntimeError", "exc_info": true, "event": "unhandled_exception", "level": "error", "timestamp": "2026-11-24T17:14:17.373257Z"}
--- catch-all (500): 500 application/problem+json
{
"type": "about:blank",
"title": "Internal Server Error",
"status": 500,
"detail": "Something went wrong. Quote the request_id to support.",
"instance": "/boom",
"request_id": "req-42"
}
X-Request-ID header: req-42Two things to notice. The 500 response contains no exception text, no file names and no password; the details went to the log, tagged "request_id": "req-42". And the same id is in the response header and the body, so "my order failed around 3pm, request id req-42" lets an engineer find the log line in seconds.
422 versus 409 versus 400. The mapping we use: 422 when the request is well-formed JSON but the content breaks a rule that needs no database (a quantity of 0); 409 when the request is fine but conflicts with the current state of the world (out of stock, restaurant closed, status jump not allowed); 400 for requests that cannot be understood at all, such as a corrupted cursor. Teams differ on 400 versus 422; what matters is picking one rule and writing it down.
Bridge: why the catch-all needs a trick to know the request id
The catch-all handler for Exception is special. Starlette does not run it in the normal exception middleware; it runs it in ServerErrorMiddleware, the outermost layer, after the exception has already travelled out through all the other middleware, including our RequestIdMiddleware. By then the middleware's finally has reset the context variable, and the handler would see no id.
That is why RequestIdMiddleware also writes the id into scope["state"], a dictionary that belongs to the request and outlives the middleware. The handler reads request.scope["state"]["request_id"]. Test: test_unhandled_exception_is_500_without_stack_trace sends X-Request-ID: req-123 and asserts it comes back in body and header. Also note that the response from this layer does not pass through our middleware's header rewriting, so the handler puts the X-Request-ID header on the response itself.
One more test detail: Starlette's TestClient re-raises server exceptions into your test by default. To see the 500 response a client would see, build it with raise_server_exceptions=False, as the client fixture in conftest.py does.
- Works: one shape for every error; stable
typeURIs clients can switch on; a request id in every error; logs hold the stack trace and the response holds none. - Fails: returning
str(exc)to the client (leaks table names and passwords); using 200 with{"error": ...}(breaks every monitor that counts non-2xx); changingtitleper occurrence (clients cannot group them). - Interview takeaway: "I register handlers for validation, HTTP, domain and unexpected errors, all returning
application/problem+jsonwith a stable type and a request id. The stack trace goes to the log, never to the client."
Idiom: Cursor pagination
The problem: a customer's order history is a list that grows. GET /orders returning everything times out at 50,000 rows. The first fix, ?page=3&size=10 (offset pagination), looks fine until the list changes between two requests.
How it works: instead of "skip N rows", the client says "give me the rows after the last one I saw". The server hands back a cursor, an opaque string, with each page. The cursor encodes the sort key of the last row; the next query starts after it.
- Stable order:
ORDER BY created_at DESC, id DESC. Theidbreaks ties when two orders share a timestamp; without it, rows can be skipped or repeated at a tie. - Fetch one extra row: ask for
limit + 1. If that extra row exists, there is a next page; drop it from the answer and build the cursor from the last row you keep. - Encode the cursor: base64 of
[created_at, id]. "Opaque" means clients must not parse it, so you can change its contents later. (A cursor is not a secret; if the position must be tamper-proof, sign it.) - Seek, do not skip:
WHERE created_at < :ts OR (created_at = :ts AND id < :id). With an index on(customer_id, created_at, id)the database jumps straight to that spot. - Cap the limit:
Query(ge=1, le=100). The testtest_limit_is_capped_and_bad_cursor_is_400checks that 101 is refused.
def list_page(self, customer_id: int, limit: int, cursor: str | None) -> tuple[list[Order], str | None]:
stmt = (
select(Order)
.options(selectinload(Order.lines))
.where(Order.customer_id == customer_id)
.order_by(Order.created_at.desc(), Order.id.desc())
.limit(limit + 1)
)
if cursor:
ts, last_id = decode_cursor(cursor)
stmt = stmt.where(or_(Order.created_at < ts, and_(Order.created_at == ts, Order.id < last_id)))
rows = list(self.session.scalars(stmt))
next_cursor = None
if len(rows) > limit:
rows = rows[:limit]
next_cursor = encode_cursor(rows[-1].created_at, rows[-1].id)
return rows, next_cursorMake the invisible visible: 1,000 orders, newest first, 10 per page. Between page 1 and page 2, one newer order arrives. Script pagination_demo.py runs both styles.
page 1 (both): [1000, 999, 998, 997, 996, 995, 994, 993, 992, 991]
insert: one newer order arrives between page 1 and page 2
page 2 offset: [991, 990, 989, 988, 987, 986, 985, 984, 983, 982] repeats from page 1: [991]
page 2 cursor: [990, 989, 988, 987, 986, 985, 984, 983, 982, 981] repeats from page 1: []
offset page 100: 0.97 ms, page 1: 0.62 ms (the database still walks the skipped rows; only 1,000 here)The offset page 2 starts with id 991, which the customer already saw at the bottom of page 1. A client that appends pages shows a duplicate row; a client that deduplicates by id is hiding a bug. With the opposite situation (a row deleted between pages) offset pagination skips a row instead, and nobody notices at all. The cursor page 2 starts at 990 and continues without a gap.
pagination_demo.py.The last line of the output is the second reason. The timing for page 100 is small here only because the table has 1,000 rows. OFFSET 990 still makes the database read and throw away 990 rows; on 5 million rows, "page 50,000" reads 500,000 rows to show 10. A cursor query reads about 10. I am not claiming a number for a 5-million-row table because it was not measured here; the mechanism is the point.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Offset / page number | Small, rarely changing lists where users jump to "page 7" (admin tables) | Cost grows with the page number; duplicates or gaps when rows change; no stable position |
| Cursor / keyset (we use it) | Feeds, histories and anything infinite-scroll or exported by a program | No jump to page N; needs a unique sort key; sorting by an arbitrary user-chosen column needs care |
| Time-based "since" parameter | Sync clients that ask "what changed after 14:30" | Clock and tie problems; a cursor on (updated_at, id) is the safer version |
- Works: constant cost per page; stable under inserts and deletes; the response says
next_cursor: nullat the end. - Fails: sorting by a column that is not unique and not in the cursor; returning a total count on every page (a
COUNT(*)over a big table is itself slow, offer it only on request); letting clients choose limits of 100,000. - Interview takeaway: "Offset pagination skips rows by reading them, and it shows duplicates when data changes. I use a keyset cursor on
(created_at, id), fetch limit plus one to know if there is a next page, and cap the limit."
Idiom: Partial update with exclude_unset
The problem: a client sends PATCH /v1/orders/7 with {"status": "confirmed"}. The Pydantic model has two optional fields, status and delivery_note, both defaulting to None. If the code copies every field of the model onto the order, the note the customer wrote ("ring twice") becomes None. The client never mentioned the note.
How it works: Pydantic remembers which fields were present in the input, in model_fields_set. model_dump(exclude_unset=True) returns only those. "Not sent" and "sent as null" are different, and only this call can tell them apart.
fields the client sent : {'status'}
model_dump() : {'status': 'confirmed', 'delivery_note': None}
model_dump(exclude_unset): {'status': 'confirmed'}
naive apply -> {'status': 'confirmed', 'delivery_note': None}
fixed apply -> {'status': 'confirmed', 'delivery_note': 'ring twice'}
explicit null clears the note -> {'status': 'placed', 'delivery_note': None}The third line of output is the feature, not a bug: when the client sends {"delivery_note": null} on purpose, the note is cleared, and only the note. In the canonical app this is OrderService.update_order, which applies patch.model_dump(exclude_unset=True). Test test_patch_only_changes_fields_that_were_sent does both cases.
The difference from PUT: PUT means "replace the whole resource with this body". A PUT model has required fields, and anything not in the body goes to its default. PATCH means "change these fields". Use PUT when clients always hold the whole object and want simple semantics; use PATCH for large objects and for fields that different people edit.
Two edge cases to design deliberately. Some fields must never be null (our status: a null is ignored by the service). And when the same field is edited by two clients, PATCH alone gives "last write wins"; add the If-Match header described below to make that conflict visible.
Naive: dump everything
Every missing field looks like an instruction to set it to null.
changes = body.model_dump()
# ❌ TRAP: {'status': 'confirmed',
# 'delivery_note': None}
for k, v in changes.items():
setattr(order, k, v)
Correct: only what was sent
Missing stays missing; an explicit null still clears.
changes = body.model_dump(
exclude_unset=True) # ✅
# {'status': 'confirmed'}
for k, v in changes.items():
setattr(order, k, v)
The shift: a Python default of None hides the difference between "absent" and "null". Ask the model which fields were set instead of looking at their values.
- Works: small bodies, no data loss, explicit null to clear. Whitelisting is built in: the model only has the fields a client may change.
- Fails:
setattrin a loop with a model that includesidorcustomer_id(mass assignment: the client changes what they should not); usingexclude_none=Trueinstead, which makes clearing a field impossible. - Interview takeaway: "PATCH applies
model_dump(exclude_unset=True), because absent and null are different. The patch model lists only the fields a client may change, which also prevents mass assignment."
HTTP semantics: the status codes and headers that carry meaning
Clients, proxies, caches and monitoring tools all read status codes. A wrong code is a wrong instruction. This is the table to have in your head; every code here is used by the canonical app or its tests unless noted.
| Code | Use it when | Comes with | QuickBite example |
|---|---|---|---|
| 200 OK | Success with a body; also a replayed idempotent request | Idempotent-Replayed: true | second POST with the same key |
| 201 Created | A new resource now exists | Location header with its URL | POST /v1/orders |
| 202 Accepted | Work was queued, not done | a status URL to poll | "generate my invoice PDF" (not in the app) |
| 204 No Content | Success, nothing to return | no body at all | a DELETE that worked |
| 304 Not Modified | Conditional GET, nothing changed | no body, ETag | GET with If-None-Match |
| 400 Bad Request | Cannot be understood | problem body | corrupted cursor |
| 401 Unauthorized | No valid credentials | WWW-Authenticate: Bearer | expired token |
| 403 Forbidden | Known caller, not allowed | problem body | token lacks orders:write |
| 404 Not Found | No such thing, or not yours | problem body | someone else's order |
| 409 Conflict | Valid request, clashes with current state | problem body | out of stock |
| 412 Precondition Failed | If-Match no longer matches | problem body | stale PATCH |
| 422 Unprocessable Content | Well-formed but invalid | errors list | qty: 0 |
| 429 Too Many Requests | Rate limit hit | Retry-After: seconds | flooding client |
| 503 Service Unavailable | Temporarily cannot serve | Retry-After | /readyz with the database down |
Bridge: ETag and conditional requests, one level down
An ETag is a fingerprint of a response, sent in a header. The client remembers it. Next time it sends the fingerprint back, and the server can say "unchanged" without sending the body again. Two headers use it.
If-None-Matchon GET (saves bandwidth): "send the order only if it no longer has this fingerprint". If nothing changed, the answer is304 Not Modifiedwith an empty body.If-Matchon PATCH or PUT (prevents lost updates): "apply my change only if the order still has this fingerprint". If someone else changed it meanwhile, the answer is412 Precondition Failed. This is optimistic locking, expressed in HTTP.
In the canonical app the ETag is a weak validator (W/"...") computed as a SHA-1 prefix over the order's JSON. A weak ETag says "equivalent content", which is all we need. A real caveat: this computes the whole response first and only then decides it is unchanged, so it saves bandwidth but not database work. To save the database work too, use a version number or updated_at column as the validator.
preflight from https://app.quickbite.example: 200
access-control-allow-methods: GET, POST, PATCH
access-control-max-age: 600
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type, Idempotency-Key
access-control-allow-origin: https://app.quickbite.example
preflight from https://evil.example: 400
access-control-allow-methods: GET, POST, PATCH
access-control-max-age: 600
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type, Idempotency-Key
{"order_id": 1, "customer_id": 1, "total_cents": 300, "event": "order_created", "level": "info", "timestamp": "2026-11-24T17:14:19.480022Z", "request_id": "d69143f6a4e34e2687227e8085dfd138"}
GET 1: 200 ETag W/"79bfb99d77dc8dff" body bytes 197
GET 2 with If-None-Match: 304 body bytes 0
PATCH with fresh If-Match: 200 new ETag W/"091009756fcde4d2"
PATCH with stale If-Match: 412 Precondition FailedRead the second block of output from "GET 1" down. The 304 has zero body bytes against 197 for the full answer. The PATCH with a fresh If-Match succeeds and returns a new ETag; replaying the same old ETag a second time returns 412, so a second editor who started from the old copy learns that they would overwrite someone else's change.
Timeouts and retries for outbound calls
Your API also makes calls: to a payment service, to the restaurant's system, to the identity provider's JWKS endpoint. A call without a timeout is a promise to wait forever. One slow downstream service then holds one worker thread (or one coroutine, and one pooled connection) per request, and the queue grows until your own API is down.
Set four separate timeouts with httpx.Timeout(connect=1, read=2, write=2, pool=1): how long to open a connection, how long to wait for each chunk of the reply, how long to send, and how long to wait for a free connection in the client's pool. Notice that "read" is the gap between chunks, not the total time; for a hard cap on the whole call use asyncio.timeout() or the deadline of your caller.
Retries help against brief failures (a connection reset during a deploy) and hurt against overload (every client retries and the struggling service gets triple the traffic). The rules that make them safe:
- Only retry what is safe to repeat: GETs, and writes protected by an idempotency key. A retried
POST /chargewithout a key charges the customer twice. - Retry only transient errors: connection timeouts and 502, 503, 504. Never retry a 400 or 422; the same request will fail the same way.
- Back off with jitter: wait 0.1 s, 0.2 s, 0.4 s ... plus a random amount, so a thousand clients do not retry in the same millisecond.
- Cap the attempts and the total time: three or four tries, and stop when the caller's own deadline is near.
The tenacity library (installed) turns this into a decorator. The script uses httpx.MockTransport as a flaky fake: the first two calls time out, the third succeeds.
@retry(retry=retry_if_exception_type((httpx.ConnectTimeout, httpx.ReadTimeout)), stop=stop_after_attempt(4),
wait=wait_exponential_jitter(initial=0.05, max=1, jitter=0.05), reraise=True,
before_sleep=before_sleep_log(logging.getLogger("retry"), logging.INFO))
def get_payment_status(): # a GET: safe to repeat
return client.get("http://payments.internal/status/42").json()Retrying __main__.get_payment_status in 0.0602 seconds as it raised ConnectTimeout: simulated: no answer in 1 s.
Retrying __main__.get_payment_status in 0.1 seconds as it raised ConnectTimeout: simulated: no answer in 1 s.
HTTP Request: GET http://payments.internal/status/42 "HTTP/1.1 200 OK"
result: {'payment': 'ok'} after 3 callsThe two "Retrying" lines are tenacity's before_sleep log: it waited 0.06 s, then 0.1 s, and the third call returned. The wait times are small only so the demo is quick; in production, start around 100–200 ms. A circuit breaker (stop calling a service that has failed 20 times in a row, for 30 seconds) is the next layer; libraries such as pybreaker exist, but this chapter has not run one, and many teams get the same effect from a service mesh.
Putting the section together: what to say in the interview
If you are asked "how do you secure a FastAPI API?" the strong answer is a short list in order of attack, not a list of libraries.
- Edge: TLS, rate limits and body-size limits at the gateway; CORS only for known origins.
- Identity: validate JWTs from an identity provider with an algorithm allow-list, required
exp,issandaud. - Permission: scope dependencies for the action, ownership in the query for the object, 404 not 403 for others' objects.
- Input: Pydantic models with constraints (
qtyfrom 1 to 50), a cappedlimit, bounded lists. - Output: response models so internal fields cannot leak; problem details with no stack traces.
- Behaviour: idempotency keys for retried writes,
If-Matchfor concurrent edits, timeouts for every outbound call.
Each of those six has a test in the canonical suite; that is the answer to "how do you know?".
07 · ProductionTesting, Background Work, Observability and Deployment
A service is finished when you can change it without fear, find a single failed request in a million log lines, lose no work when a pod is replaced, and ship it as a small image that stops cleanly. This section builds each of those four abilities on the canonical QuickBite app and ends with the whole app, built chunk by chunk.
Here is how a bad week looks. QuickBite sent order-confirmation emails with FastAPI's BackgroundTasks: after the endpoint returns, send the email. It worked in every test. Then the team started deploying twice a day.
On every deploy, Kubernetes replaced the old pods. Customers who ordered in the last few seconds before a pod died got their order and no email. Support noticed on day three: "I paid, but nothing arrived." Nobody could say how many emails were lost, because a lost background task writes nothing anywhere.
The same week, one customer reported that their order failed at 7:42 pm with "Something went wrong". The logs held 3 million lines from 12 pods in that hour, and no line said which request it belonged to. Finding the failure took two engineers two hours, mostly by guessing from the customer's id and the minute.
Neither problem was a bug in the code the team wrote. Both were missing machinery: a durable queue for work that must not be lost, and a request id that threads through every log line. We will build those, plus the tests and the container that make the service safe to change and safe to replace.
Bridge: what "testing an API" actually means in FastAPI
A FastAPI app is a Python object that follows the ASGI protocol: a function called with a scope (what the request is), a receive channel and a send channel. A test does not need a network, a port or a running server. It can call that object directly and read what comes out. That makes tests fast: the whole QuickBite suite runs in about three and a half seconds.
There are two ways to call the app in-process, and they differ in who owns the event loop.
TestClient(app)(Starlette, built on httpx): synchronous. You write ordinarydef test_...functions. Inside, it starts a background thread with an event loop and runs each request on it. Use it for the large majority of tests.httpx.AsyncClient(transport=ASGITransport(app=app)): asynchronous. Your test isasync defand runs on the test runner's event loop, together with your code under test. Use it when the test itself mustawaitthings, or when you need to run several requests concurrently in one loop.
One trap with the second style: ASGITransport does not run the app's lifespan (startup and shutdown). If your app creates resources in lifespan, an AsyncClient test sees an app without them. TestClient runs the lifespan only when used as a context manager (with TestClient(app) as c:). The canonical suite tests both on purpose: test_lifespan_runs_startup_and_shutdown checks the startup and shutdown log lines, and test_async_client_with_asgi_transport creates and reads an order through the async client.
Idiom: Test the real app in process, replace the edges
The problem: tests that mock the database, the clock and the auth library test the mocks. Tests that need a running Postgres and a real identity provider are slow and flaky, so people stop running them.
How it works: run the real app, real routers, real services and real SQL, in process. Replace only the edges that cost time or need the outside world, using app.dependency_overrides.
- One database per test: an in-memory SQLite engine with
StaticPool. SQLite memory databases live inside one connection;StaticPoolmakes every session share that single connection, so tables created in the fixture are visible to requests. Each test gets a brand-new engine, so tests cannot affect each other. - Override
get_session: the fixture builds a session factory on the test engine. The app code is unchanged. - Override
get_settings: tests use a generated RSA key pair and a public key in the settings. No network, but the full RS256 path runs. - Token factory fixture:
make_token(sub=1, scope=..., exp_in=...)signs a real JWT with the test private key, so a test for an expired token is one argument:exp_in=-60.
@pytest.fixture
def engine():
"""A fresh in-memory SQLite database per test. StaticPool = one shared connection."""
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
with Session(engine) as s, s.begin():
seed(s)
yield engine
engine.dispose()
@pytest.fixture
def app(engine, settings):
app = create_app(settings, engine)
factory = sessionmaker(engine, expire_on_commit=False)
def override_get_session():
session = factory()
try:
yield session
except Exception:
session.rollback()
raise
finally:
session.close()
app.dependency_overrides[get_session] = override_get_session
app.dependency_overrides[get_settings] = lambda: settings
return app
@pytest.fixture
def client(app):
# raise_server_exceptions=False: we want to see the 500 response, not a re-raised exception
return TestClient(app, raise_server_exceptions=False)
@pytest.fixture
def make_token(rsa_keys):
def factory(sub=1, scope="orders:read orders:write", role="customer", exp_in=300,
aud=AUDIENCE, iss=ISSUER, key=None, alg="RS256", headers=None, **extra):
now = int(time.time())
claims = {"sub": str(sub), "scope": scope, "role": role, "iss": iss, "aud": aud,
"iat": now, "exp": now + exp_in, **extra}
return jwt.encode(claims, key or rsa_keys[0], algorithm=alg, headers=headers)
return factory
@pytest.fixture
def auth(make_token):
"""Headers for customer 1 (asha). auth_for(2) gives customer 2 (ben)."""
def headers_for(sub=1, **kw):
return {"Authorization": f"Bearer {make_token(sub=sub, **kw)}"}
return headers_for
ORDER_BODY = {"restaurant_id": 1, "lines": [{"menu_item_id": 1, "qty": 2}, {"menu_item_id": 2, "qty": 1}]}Look at what is not mocked: the JWT library, Pydantic validation, the routers, SQLAlchemy, the SQL itself. A test like test_idempotency_same_key_same_body_returns_same_order posts twice through HTTP and then runs select count(*) from orders against the real database to prove one row exists. A mock cannot prove that.
Make the invisible visible: the real suite, run with the course Python 3.12 environment. Real output, FastAPI 0.141.1.
$ python -m pytest -q
............................s................ [100%]
44 passed, 1 skipped, 1 warning in 3.60sThe one skipped test is the PostgreSQL test, which needs a container. The one warning comes from inside Starlette's test client (a deprecated alias in anyio), not from our code. The numbers: 15 tests in test_orders.py, 16 in test_security.py, 9 in test_errors_pagination.py, 4 in test_observability.py.
pytest --collect-only. Bar width is not to scale, but the shape is honest: this suite is a trophy, not a pyramid, because most of the code is wiring between layers.Spring Boot · test slice
A slice loads only the web layer; the service is a mock bean.
// illustrative
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@MockBean OrderService service;
@Test void createReturns201() throws Exception {
mvc.perform(post("/v1/orders")
.with(jwt())
.content(json))
.andExpect(status().isCreated());
}
}
FastAPI · TestClient
The whole app runs; only the database and settings are swapped.
def test_create_and_read_order(client, auth):
r = client.post("/v1/orders",
json=ORDER_BODY,
headers=auth(1))
assert r.status_code == 201
got = client.get(
r.headers["Location"],
headers=auth(1))
assert got.json() == r.json()
The shift: Spring's slice test is cheap because it leaves layers out and mocks them; FastAPI's app is so light that the whole stack is the cheap test, and dependency_overrides swaps just the parts that touch the outside world.
- Works: 44 tests in under four seconds; real SQL and real JWT verification; one failing test points at one behaviour.
- Fails: sharing one database across tests (order-dependent failures); an
async deftest with no async plugin (pytest silently skips or errors, depending on settings); forgettingraise_server_exceptions=Falsewhen you want to see a 500 response; testing with the app's real settings and accidentally calling the real identity provider. - Interview takeaway: "I test the real app in process with TestClient or ASGITransport, give every test a fresh in-memory database, and use dependency overrides only for the database, settings and clock, never for my own code."
Where SQLite lies: one real PostgreSQL test
SQLite is a perfect test database for logic and a poor one for concurrency and constraints. It has one writer at a time, so the "two buyers, one biryani" race cannot even happen in it. It also does not enforce foreign keys unless you turn them on, and it accepts almost any value in any column. Postgres does not.
So the suite includes tests/test_postgres.py, skipped unless QUICKBITE_TEST_PG_URL is set. It started a postgres:18-alpine container (the image was already on the machine), then ran eight threads, each placing an order for the single remaining kind of biryani, which has stock 5.
$ docker run -d --name qb-pg -e POSTGRES_PASSWORD=pw -p 55432:5432 postgres:18-alpine
$ QUICKBITE_TEST_PG_URL=postgresql+psycopg://postgres:pw@localhost:55432/postgres python -m pytest -q
............................................. [100%]
45 passed, 1 warning in 5.23sWhat the test asserts: exactly five requests got 201, three got 409, the stock ended at 0 (never negative) and exactly five order rows exist. That is the atomic UPDATE menu_items SET stock = stock - :q WHERE id = :id AND stock >= :q doing its job under real concurrency.
And a lesson the first run taught. The seed data inserted menu items and restaurants in one add_all call. SQLite did not complain. Postgres raised a ForeignKeyViolation, because SQLAlchemy had no relationship telling it to insert restaurants first. The fix is a relationship() from MenuItem to Restaurant, which the model now declares. That is the kind of bug only a real database finds.
| Option | Pick it when | Cost or catch |
|---|---|---|
| SQLite in memory (default here) | Most tests: logic, validation, status codes, queries without Postgres-only features | No real concurrency, loose constraints, no FOR UPDATE, JSONB or ON CONFLICT differences |
| Postgres in a container, one per run | Anything that is about locking, constraints, migrations, or Postgres types | Seconds of start-up; needs Docker in CI; clean-up between tests costs time (truncate or rollback) |
Testcontainers (testcontainers package) | You want the container started and stopped from the test code itself, with a random port | Not installed on the course machine, so not run here; adds a dependency and needs Docker access |
| A shared test database server | Rarely: huge schemas where a fresh one per run is too slow | Tests collide; flaky in parallel; hides ordering bugs |
The practical split is a pyramid in disguise: hundreds of SQLite tests, a handful of Postgres tests for the places where the databases differ.
Contract and load testing
A hand-written test checks what you thought of. Contract testing checks the API against its own published description. FastAPI generates an OpenAPI document from your routes and models, and a tool like schemathesis reads it, invents hundreds of requests (empty strings, huge numbers, missing fields), sends them, and verifies that every response matches the documented status codes and shapes.
It is good at finding the 500 that a strange input triggers. schemathesis is not installed on this machine, so this is described, not run; if you add it, point it at app.openapi() through the ASGI app, and treat each 500 it finds as a missing validation rule.
Load testing (locust, k6) answers a different question: how does it behave at 200 requests per second, and where does it break? Run it against a deployed copy, not TestClient, and read the results as percentiles, not averages: p50, p95 and p99 latency, plus the error rate. Watch the database connection count and the event-loop lag at the same time; the first thing to saturate is usually the connection pool (section 05), not the CPU.
Bridge: what BackgroundTasks really does
The name suggests a worker somewhere that processes jobs. It is not that. BackgroundTasks is a list of functions attached to the response. After the response body has been sent, Starlette calls them, in order, inside the same web process. A plain def task runs in the threadpool; an async def task runs on the event loop.
That means three things. The work lives only in memory: if the process dies, the task is gone and nothing remembers it was promised. The work shares the web process's CPU and threads, so a heavy task slows other requests. And a failing task cannot tell the client, because the client already has its answer.
Make the invisible visible: a task that takes 0.5 s, and one that raises. Script background_tasks_demo.py, run with Starlette's TestClient.
t= 0.03s endpoint returns
t= 0.53s email for order 1 sent
HTTP Request: POST http://testserver/orders "HTTP/1.1 200 OK"
t= 0.53s client got 200 {'id': 1}
HTTP Request: POST http://testserver/orders-broken "HTTP/1.1 200 OK"
client got 200 {'id': 2} <- the client never learns the email failedRead it with a caveat: TestClient does not return until the whole ASGI call, including background tasks, has finished, so the client "got 200" at t=0.53 s here. A real server hands the response to the client at once, as the next experiment shows. The second request is the important one: smtp down raised, the client got 200 {'id': 2}, and the test client printed nothing, because it was told to swallow server errors.
On a real server, the error goes to the server log, once, as an "Exception in ASGI application". That is the only trace. Here is the real log from uvicorn 0.53 running shutdown_app.py:
INFO: 127.0.0.1:50670 - "POST /orders-broken HTTP/1.1" 200 OK
ERROR: Exception in ASGI application
Traceback (most recent call last):
...
File ".../starlette/background.py", line 36, in __call__
await task()
...
File ".../shutdown_app.py", line 10, in broken
raise ConnectionError("smtp down")
ConnectionError: smtp down
The access log line says 200 OK first. The failure is logged after the success. Nothing retries it, nothing alerts on it unless you built that, and the customer has no email.
Idiom: Durable background jobs
The problem: some work must happen even if the web process dies one second after the response (send the confirmation, charge the card, update the restaurant's tablet). In-process tasks forget.
How it works: write the intention to a durable place first, in the same transaction as the order, and let a separate worker process read it and do the work, retrying on failure.
- Record the job durably: either enqueue to a broker (Redis, RabbitMQ, SQS) or, better when the job must be consistent with the database change, insert a row in an
outboxtable in the same transaction as the order. Either the order and the job both exist, or neither does. - A worker takes jobs: a different process, scaled and deployed on its own, with its own memory limits. It acknowledges a job only after finishing it.
- Retries with a limit: failures are retried with backoff; after N tries the job lands in a dead-letter list that someone is paged about.
- Make the job idempotent: a worker may run the same job twice (it crashed after sending, before acknowledging). "Send the confirmation for order 7 unless already sent" survives that.
The outbox variant is the same pattern as in the outbox pattern in Chapter E7, and shipping those rows to Kafka with change data capture is in Chapter E17. The email worker is then just one more consumer of "order created".
| Option | Pick it when | Cost or catch |
|---|---|---|
BackgroundTasks | Cheap, best-effort work where losing one is fine: warm a cache, log an analytics event | Lost on crash or deploy; shares the web process; no retry, no visibility |
| Celery + Redis or RabbitMQ | The established choice: retries, schedules, many task types, a big ecosystem | Heavy to configure; sync-first design; Redis as a broker can lose messages on failure unless tuned; many moving parts |
| arq (asyncio, Redis) | An async codebase and modest needs; small and easy | Redis only; fewer features and a smaller community than Celery |
| Dramatiq | A simpler, safer-by-default Celery alternative with good retry behaviour | Smaller ecosystem; you choose the broker (Redis or RabbitMQ) |
| RQ | The simplest possible Redis queue for a small team | Sync workers only; basic features |
| Outbox + Kafka consumer | The job is "something happened" and several systems care (email, analytics, search) | Needs Kafka and an outbox relay; more to run, strongest durability and fan-out |
| Managed (SQS + Lambda, Cloud Tasks) | You want no queue servers to operate | Cloud lock-in; local development is harder; limits on run time |
Check each project's current maintenance status before you choose; this table reflects general reputation as of late 2026, not a benchmark.
Now the experiment that explains the deploy incident. sigterm_experiment.sh starts uvicorn, posts an order whose background task needs 3 seconds, starts a slow 2-second request, and sends SIGTERM after half a second. First with a 10-second graceful-shutdown window:
[t=0] POST /orders -> {"id":1} (email task needs 3 s)
[t=0.5] SIGTERM
/slow -> HTTP 200 (in-flight request finished)
INFO: Shutting down
INFO: Waiting for connections to close. (CTRL+C to force quit)
INFO: 127.0.0.1:50678 - "GET /slow HTTP/1.1" 200 OK
INFO: Waiting for background tasks to complete. (CTRL+C to force quit)
email for order 1 sent
INFO: Application shutdown complete.
With enough time, uvicorn 0.53 waits for the in-flight request and for the running background task. So my first guess for the incident ("SIGTERM kills it immediately") was too simple. The task survives a polite shutdown. What kills it is a shutdown window shorter than the task. Same script, 1-second window:
[t=0.5] SIGTERM
/slow -> HTTP 500 (cut off)
INFO: Shutting down
INFO: Waiting for connections to close. (CTRL+C to force quit)
ERROR: Cancel 2 running task(s), timeout graceful shutdown exceeded
asyncio.exceptions.CancelledError: Task cancelled, timeout graceful shutdown exceeded
INFO: Application shutdown complete.
No "email for order 1 sent" line ever appears. The 2-second request got a 500 and the email task was cancelled. And this is the best case: a pod that is OOM-killed, a node that disappears, or a Kubernetes SIGKILL after terminationGracePeriodSeconds gives the task no cancellation message at all. That is why important work belongs in a queue, whatever the shutdown settings.
- Works: the order and its job commit together; the worker retries; a dead pod loses nothing; failures are visible in a queue dashboard.
- Fails: enqueueing to Redis after the database commit (crash in between loses the job); non-idempotent jobs under at-least-once delivery (double emails); long CPU work in
BackgroundTasks(blocks the threadpool for everyone). - Interview takeaway: "BackgroundTasks run in the web process after the response, so they die with it and their errors reach nobody. Anything that must happen goes to a durable queue or an outbox row written in the same transaction."
Observability: logs, traces and metrics
Three kinds of signal answer three questions. Logs say what happened in one request. Metrics say how the system behaves in aggregate, cheaply (a counter per second, not a line per event). Traces show one request's path across services with timings. QuickBite's two-hour hunt happened because the logs had no way to join lines to a request.
Idiom: Request id through middleware, contextvar and structured logs
The problem: with many requests in flight at once, log lines from different requests interleave. A line "order failed" does not say which request. Passing a request_id argument through every function is noisy and someone forgets.
How it works: one small piece of middleware assigns an id and stores it in a contextvars.ContextVar. A context variable is a variable whose value depends on the current task: asyncio gives each request's task its own copy, so each request sees its own id with no arguments passed. A log processor reads it and adds it to every line.
- Read or create: take
X-Request-IDfrom the incoming request (a gateway may already have set it), else generate one. Cut it to 64 characters; it is user input. - Store it:
request_id_var.set(rid), and keep the token so you can reset it infinally. - Log with it: a structlog processor adds
request_idto the event dictionary if the variable is set. - Return it: add
X-Request-IDto the response, so a customer's bug report can quote it.
"""Pure ASGI middleware: reads or creates X-Request-ID, exposes it, and echoes it back."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
incoming = dict(scope["headers"]).get(b"x-request-id")
rid = incoming.decode("latin-1")[:64] if incoming else uuid.uuid4().hex
scope.setdefault("state", {})["request_id"] = rid # survives past the contextvar reset
token = request_id_var.set(rid)
async def send_with_id(message):
if message["type"] == "http.response.start":
headers = [(k, v) for k, v in message.get("headers", []) if k.lower() != b"x-request-id"]
headers.append((b"x-request-id", rid.encode("latin-1")))
message = {**message, "headers": headers}
await send(message)
try:
await self.app(scope, receive, send_with_id)
finally:
request_id_var.reset(token)This is a pure ASGI middleware: a class with __call__(scope, receive, send) instead of Starlette's BaseHTTPMiddleware. The simple BaseHTTPMiddleware runs the rest of the app in a separate task, and historically that caused trouble with context variables set inside the endpoint and with streaming responses; the pure version has neither problem and costs less. It is more code, and worth it for middleware that runs on every request. Note that it ignores non-HTTP scopes such as the lifespan and WebSocket.
ContextVar, which asyncio gives each request its own copy of, so two overlapping requests never see each other's id.Make the invisible visible: two requests overlap: alice's takes 0.2 s, bob's 0.1 s. The handler logs "start" and "finish". Script request_id_demo.py, using the real middleware and the real logging configuration.
{"who": "alice", "event": "start", "level": "info", "timestamp": "2026-11-24T17:14:33.851473Z", "request_id": "req-A"}
{"who": "bob", "event": "start", "level": "info", "timestamp": "2026-11-24T17:14:33.851830Z", "request_id": "req-B"}
{"who": "bob", "event": "finish", "level": "info", "timestamp": "2026-11-24T17:14:33.952299Z", "request_id": "req-B"}
{"who": "alice", "event": "finish", "level": "info", "timestamp": "2026-11-24T17:14:34.051991Z", "request_id": "req-A"}
response headers: req-A req-BThe lines interleave: start A, start B, finish B, finish A. Without ids, "finish" is ambiguous. With them, grep req-A pulls out exactly one request's story. The test test_log_lines_carry_the_request_id checks that the order_created line from inside the service carries the id given in the header, even though the service function never receives it.
- Works: one id per request, in logs, error bodies and response headers; no function signature changes; safe under asyncio and in worker threads started with
asyncio.to_thread(which copies the context). - Fails: a plain
threading.Threador a thread pool you create yourself (does not copy the context, so ids vanish); trusting the incoming header blindly (a 5 MB header becomes 5 MB per log line, hence the cut); a module-level global instead of aContextVar(requests overwrite each other's id). - Interview takeaway: "A pure ASGI middleware sets a ContextVar and the response header; a structlog processor stamps every line. Context variables are per-task, so concurrent requests never mix ids."
The contextvar mechanics are explained from the Python side in Chapter E19, and its asyncio chapter at #concurrency covers why each task gets its own copy.
Traces, metrics and the two health routes
OpenTelemetry is the standard way to produce traces, metrics and logs. Its auto-instrumentation packages (opentelemetry-instrumentation-fastapi, -sqlalchemy, -httpx) wrap your app, your engine and your HTTP client, so each request becomes a trace with child spans for each SQL statement and each outbound call.
On the course machine, only the OpenTelemetry API, SDK and OTLP exporters are installed (1.44); the instrumentor packages are not, so I did not run them. Adding them is a few lines at start-up, and the request id and the trace id can be logged side by side.
Prometheus metrics follow the RED method: Rate (requests per second), Errors (the share of 5xx), Duration (a histogram, so you can compute p95 and p99). The prometheus-client package (installed) gives you counters and histograms; label them by route template (/v1/orders/{order_id}), never by the raw path, or every order id creates a new time series and the monitoring system runs out of memory. Alert on symptoms customers feel (error rate, p99 latency), not on causes (CPU at 70%).
The two health routes answer different questions, and mixing them causes outages.
| Route | Question | Checks | If it fails, Kubernetes |
|---|---|---|---|
/healthz (liveness) | Is this process alive and answering? | Nothing external. Returns {"status":"ok"} | Restarts the container |
/readyz (readiness) | Can it do useful work right now? | SELECT 1 against the database; 503 problem on failure | Stops sending it traffic, does not restart it |
The classic mistake is a liveness probe that checks the database. The database has a 30-second hiccup, every pod fails liveness, Kubernetes restarts all of them at once, and the restart storm (each pod reconnecting) turns a hiccup into an outage. Liveness checks only the process; readiness checks dependencies, and a failing readiness probe just takes the pod out of rotation until the dependency returns.
Performance: measure first
Where does time go in one request? Roughly: network and TLS, routing, dependency resolution, JWT verification, the database (almost always the largest), Pydantic validation of the input, your code, and serialisation of the output. Guessing wrong is expensive, so measure. A simple time middleware that records duration per route gives the first picture. Then a profiler: py-spy samples a running process without changing it, and pyinstrument shows a readable tree for one request. Neither is installed here, so I will not claim output from them.
One measurement I did run is the JSON response question. The old advice was "use ORJSONResponse, it is faster". The script orjson_timing.py returns 5,000 small items (332 KB of JSON) three ways, on FastAPI 0.141.1, 20 calls each through TestClient:
/default 9.9 ms per request, 331,881 bytes
/direct-default 22.5 ms per request, 331,881 bytes
/orjson 17.8 ms per request, 331,881 bytes
# measured on the course machine (12 cores); your numbers will differTwo findings, and the first surprised me. Running the script printed a FastAPIDeprecationWarning: as of 0.141, ORJSONResponse is deprecated. FastAPI now serialises directly to JSON bytes through Pydantic when you declare a return type or response_model. That path, /default at 9.9 ms, was the fastest of the three. The slowest, 22.5 ms, is the common hand-written pattern: calling model_dump() on every item to make dicts, then letting the response class serialise them. Using orjson on those dicts (17.8 ms) helps, but skipping the dict step helps more.
The lesson is the standing rule of performance work: do not carry old advice across a version. Declare response_model or a return type, return model instances or ORM objects with from_attributes, and let the framework serialise once. The numbers are timings of a test client on one machine, so treat the ratio as the message and the milliseconds as local.
Also avoid validating twice: returning a Pydantic instance from an endpoint that declares the same response_model avoids converting to a dict first; returning a dict makes FastAPI validate the dict against the model, which is the work you were trying to skip. And remember the biggest performance decisions are elsewhere: the N+1 queries and the pool size from section 05, and the def versus async def rule from section 02.
Deployment: the container
A container image for a Python API has three jobs: contain exactly the dependencies you tested, start fast, and run with the fewest privileges that work. The mistakes are easy: pip install without a lock file so production differs from tests, one big image with compilers and build caches (1 GB instead of 300 MB), and running as root.
Idiom: Multi-stage Dockerfile with uv, a lock file and a non-root user
The problem: the image built on Monday and the image built on Thursday have different dependency versions, because nothing pinned them. And the image carries uv, pip caches and build tools it never uses at run time.
How it works: a first stage ("builder") installs exactly the locked dependencies into a virtual environment. A second stage ("runtime") starts from a clean slim base and copies only that environment and the app code.
- Lock file:
uv lockrecords every package and version, with hashes, inuv.lock.uv sync --frozeninstalls exactly that and fails if the lock is out of date. - Dependencies before code: copy
pyproject.tomlanduv.lock, install, and only then copyapp/. Docker caches each step, so a code change does not reinstall dependencies. - Leave tools behind: the runtime stage copies
/srv/.venvand/srv/app, not uv or its cache. - Non-root: create a user with a fixed id (10001) and switch to it. A bug that lets an attacker run commands then lands in a user that cannot write to the system.
# syntax=docker/dockerfile:1
# ---- builder: resolve and install dependencies with uv, from the lock file ----
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:0.11 /uv /usr/local/bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
WORKDIR /srv
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project # cached layer: only changes with the lock file
COPY app ./app
# ---- runtime: no uv, no build tools, non-root ----
FROM python:3.12-slim AS runtime
ENV PATH="/srv/.venv/bin:$PATH" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
RUN useradd --system --uid 10001 --no-create-home quickbite
WORKDIR /srv
COPY --from=builder /srv/.venv ./.venv
COPY --from=builder /srv/app ./app
USER quickbite
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=3s CMD python -c "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/healthz')"
CMD ["uvicorn", "app.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--timeout-graceful-shutdown", "20"]This was built and run on the course machine, not just written down. The build took about 26 seconds, including pulling the base images and installing the packages; the final image is 289 MB. The container ran as uid=10001(quickbite), /healthz answered {"status":"ok"}, and docker stop returned in 0.54 seconds because the server was idle and exited on SIGTERM at once. Your time depends on your network and which layers are cached.
Two choices to explain. --no-install-project installs only dependencies in the cached layer. And the start command uses --factory, because our app is built by a function, create_app(), not exposed as a ready object. I verified in uvicorn --help that the flag exists in 0.53, along with --timeout-graceful-shutdown, --workers and --proxy-headers.
Behind a load balancer you also need --proxy-headers (and a list of trusted proxy addresses) if the app must see the real client IP and the https scheme; without it, every request looks like it came from the proxy, and rate limits by IP all hit the same counter.
| Option | Pick it when | Cost or catch |
|---|---|---|
| uv + multi-stage + lock (we use it) | Normal case: fast, reproducible installs and a small runtime image | Two stages to maintain; the lock file must be committed and refreshed on purpose |
pip install -r requirements.txt | Existing projects with a hash-pinned requirements file | Slower; the pinned file is easy to let rot; transitive versions drift if unpinned |
| Poetry or pip-tools to export a requirements file | The team already uses them | An extra export step; one more tool in CI |
| Distroless or Chainguard Python base | Security teams want almost no OS in the image | No shell for debugging; native wheels need a matching libc; setup takes longer |
| Alpine base (musl) | Rarely for Python | Many wheels are built for glibc, so installs compile from source and are slower and bigger than they look |
- Works: the same versions in CI and in production; code-only changes rebuild in seconds; the image has no compiler and no root user.
- Fails: copying the whole repository before installing dependencies (every edit busts the cache); forgetting
.dockerignore(the.venvand.envend up in the image, and a.envmay hold secrets); baking secrets into the image instead of the environment. - Interview takeaway: "A lock file, dependencies in their own cached layer, a multi-stage build that leaves tools behind, a non-root user, and configuration from the environment. The same image goes to every environment."
Configuration is the rest of the story. The same image runs in test, staging and production; only environment variables differ. Settings reads QUICKBITE_DATABASE_URL, QUICKBITE_JWT_PUBLIC_KEY and so on. Secrets come from the platform (Kubernetes Secrets, a cloud secret manager) as environment variables or mounted files, never from the image or the repository. jwt_secret is a SecretStr, so printing the settings object shows **********, not the value.
Idiom: Graceful shutdown that matches the platform
The problem: on every deploy, a few customers see an error or a lost email. The pods are replaced while requests are in flight.
How it works: shutdown is a sequence with several clocks, and they have to agree. The platform stops sending new traffic; the server finishes what it has; the process exits before the platform loses patience.
- Readiness goes false: Kubernetes removes the pod from the service's endpoints. Careful: this takes a few seconds to reach every load balancer, so requests can still arrive after SIGTERM.
preStopsleep: a 5-second sleep before SIGTERM gives the removal time to spread. Without it, the server stops accepting just as the last requests are still being routed to it.- SIGTERM: uvicorn stops accepting new connections, lets in-flight requests finish, runs lifespan shutdown (our app disposes the engine and logs "shutdown") and exits.
- The cap:
--timeout-graceful-shutdown 20tells uvicorn to give up on stragglers after 20 seconds and cancel them. Kubernetes'terminationGracePeriodSeconds(30) must be longer than preStop plus that: 5 + 20 = 25 < 30. After 30, Kubernetes sends SIGKILL, which cannot be caught.
BackgroundTask still running when the grace period ends is cancelled, and SIGKILL (or a crash, or an out-of-memory kill) stops it with no warning at all.spec:
terminationGracePeriodSeconds: 30
containers:
- name: quickbite-api
image: quickbite-api:e20
readinessProbe: { httpGet: { path: /readyz, port: 8000 }, periodSeconds: 5 }
livenessProbe: { httpGet: { path: /healthz, port: 8000 }, periodSeconds: 10 }
lifecycle:
preStop: { exec: { command: ["sleep", "5"] } }
The manifest above is an illustration of the settings (this chapter did not run a Kubernetes cluster); the Dockerfile's CMD already carries --timeout-graceful-shutdown 20. The earlier SIGTERM experiment is the real evidence for the uvicorn half: with a 10-second window both the 2-second request and the 3-second task finished; with a 1-second window the request got a 500 and the task was cancelled. Kubernetes details are in Chapter E10, and the container basics in Chapter E9.
- Works: readiness first, then a short preStop, then SIGTERM with a bounded drain; the three numbers (5, 20, 30) are chosen together, with the grace period as the largest.
- Fails: a grace period shorter than the drain (pods killed mid-request); shell-form
CMD python -m uvicorn ...in some images, where the shell is process 1 and swallows SIGTERM (use the exec form, as ours does); long-running requests with no cap, so one slow client holds a deploy for minutes. - Interview takeaway: "Flip readiness, sleep a few seconds, send SIGTERM, drain within
--timeout-graceful-shutdown, and keep Kubernetes' grace period longer than both. Anything that cannot finish in that window belongs in a queue."
The stack, and why
The one question that decides it: is this an API-first service with a database behind it, or a product with an admin, forms and an ORM-centred data model?
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Framework | FastAPI 0.141.1 (still 0.x: pin it) | Django + DRF, Django Ninja, Flask 3.1, Litestar, plain Starlette | Types become validation, docs and a typed client for free; dependencies and tests are simple; async when you need it. Catch: 0.x versions have changed behaviour between releases, as the ORJSON finding showed | You need the admin, auth and ORM batteries of a CRUD product (Django); you want a stable 1.x with built-in DI and plugins (Litestar, check its current release); the app is 5 routes (Flask or Starlette) |
| Validation | Pydantic 2.13 | dataclasses + manual checks, msgspec, attrs + cattrs | The ecosystem standard; FastAPI is built on it; Rust core | You serialise millions of messages per second and profiling shows validation dominates (msgspec) |
| Database access | SQLAlchemy 2.0.54 sync, in the threadpool | async SQLAlchemy, SQLModel, psycopg 3 raw, Django ORM | Mature, typed in 2.0 style, and sync code is simplest to reason about | Thousands of concurrent slow queries make threads the bottleneck (async engine) |
| Server | uvicorn 0.53 (one process per core, or per pod) | Gunicorn with Uvicorn workers, Granian, Hypercorn | Simple and fast; Kubernetes handles process supervision | You run on plain VMs and want a process manager with worker recycling (Gunicorn, installed: 26.2) |
| Auth | PyJWT + an identity provider | Authlib, your own password flow, gateway-only | Small, validates tokens and nothing more | You must also act as an OAuth server (Authlib) |
| Tests | pytest + TestClient + SQLite, one Postgres test | unittest, Testcontainers, schemathesis | Fast feedback, real SQL, real JWTs | Locking or JSONB behaviour matters in more than a handful of places (more Postgres tests) |
| Image | uv + python:3.12-slim, 289 MB | pip, Poetry, distroless | Locked and reproducible, small | A security review demands no shell in the image (distroless) |
FastAPI with Pydantic and SQLAlchemy is a good default for an API service; choose Django when the product is mostly admin screens and forms, and choose something other than Python when the limiting factor is raw CPU.
| Option | Pick it when | Cost or catch |
|---|---|---|
| FastAPI | JSON APIs, microservices, anything where the contract (OpenAPI) matters | You choose and assemble the ORM, auth and migrations; 0.x versioning |
| Django + DRF | A product with an admin, users, permissions and relational data in one codebase | Heavier; DRF serializers are slower to write than Pydantic models; async support is more recent and uneven |
| Django Ninja | You like Django's ORM and admin but want FastAPI-style typed endpoints | A smaller project depending on Django plus Pydantic; check its current Pydantic 2 support |
| Flask | Small services, prototypes, teams that know it well | You add validation, docs and async yourself; a 3.1 release is fine, but there is no type-driven contract |
| Litestar | You want a framework with built-in DI, DTOs and stable releases | A smaller community and fewer tutorials than FastAPI; not run in this chapter |
| Plain Starlette | Gateways and proxies where you want almost no framework | You rewrite what FastAPI gives for free (validation, OpenAPI) |
| gRPC (grpcio) | Internal service-to-service calls with strict schemas and streaming | Browsers need a proxy; harder to debug with curl; a second contract format (protobuf) |
When not to use Python for an API at all. Python's strengths are speed of writing and a huge ecosystem, and its limits are CPU-bound work and memory per process. If one service must do tens of thousands of requests per second per core, or hold hundreds of thousands of open connections at tiny cost, or run with a 10 MB footprint, a compiled language with cheap concurrency (Go, Java with virtual threads, Rust, .NET) will cost less to run.
Python 3.14's free-threaded build changes the CPU picture for threads, and the chapter on the Python deep dive explains it, but frameworks and libraries are still catching up. Most teams should pick on the people they have and the ecosystem they need; most APIs are limited by their database long before they are limited by Python.
Build it: the QuickBite orders API in seven chunks
Everything so far came from one running app. Here it is built from the ground up, one chunk at a time, in the order that each piece needs the last. The app is about 840 lines in code/e20-python-api/quickbite_api/ and 44 tests that run in under four seconds. Chunks show the important lines; the complete files are in that folder, and the key ones are listed at the end.
Build it in chunks
Seven chunks, from configuration to the full test run. After each one you can run the check and see something work; chunks 6 and 7 give you a running server and a green suite.
-
Chunk 1 — pin the dependencies and read configuration from the environment
Everything else needs to know which versions it runs on and where the database and keys are. Config comes first, because it has no dependencies of its own.
Step-by-step: what chunk 1 does, in plain English
pyproject.tomllists exact versions of FastAPI, SQLAlchemy, PyJWT and the rest, so every machine builds the same app.Settingsis a class whose fields are filled from environment variables that start withQUICKBITE_, or from a.envfile.SecretStrholds the secret so printing the settings shows stars, not the secret.jwt_algorithms()returns the allow-list: RS256 when a public key is set, HS256 only for local demos.get_settings()is cached withlru_cache, so one object exists per process and tests can override it.
pyproject.toml — chunk 1runs offline[project] name = "quickbite-api" version = "1.0.0" description = "QuickBite orders API: the running example of course chapter E20 (FastAPI)" requires-python = ">=3.12" dependencies = [ "fastapi==0.141.1", "uvicorn==0.53.0", "sqlalchemy==2.0.54", "pydantic-settings==2.15.0", "pyjwt[crypto]==2.14.0", "structlog==26.1.0", "psycopg[binary]==3.3.5",app/core/config.py — chunk 1runs offlinefrom functools import lru_cache from pydantic import SecretStr from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): """All configuration comes from environment variables (QUICKBITE_*) or a .env file.""" model_config = SettingsConfigDict(env_prefix="QUICKBITE_", env_file=".env", extra="ignore") database_url: str = "sqlite:///./quickbite.db" db_pool_size: int = 5 db_max_overflow: int = 5 create_tables: bool = False # True only for demos; real deployments use Alembic jwt_issuer: str = "https://id.quickbite.example" jwt_audience: str = "quickbite-api" jwt_public_key: str | None = None # PEM, RS256: what production uses jwt_jwks_url: str | None = None # alternative: fetch keys from the identity provider jwt_secret: SecretStr | None = None # HS256, tests and local demos only cors_origins: list[str] = [] def jwt_algorithms(self) -> list[str]: """The allow-list. The token never gets to choose its own algorithm.""" if self.jwt_public_key or self.jwt_jwks_url: return ["RS256"] return ["HS256"] @lru_cache def get_settings() -> Settings: return Settings()pydantic-settingsBaseSettingswithenv_prefix, andSecretStr.Run
QUICKBITE_DB_POOL_SIZE=3 QUICKBITE_JWT_SECRET=dev-secret-that-is-long-enough-for-hs256 python -c "from app.core.config import get_settings; s = get_settings(); print(s.database_url, s.db_pool_size, s.jwt_secret, s.jwt_algorithms())". You should seesqlite:///./quickbite.db 3 ********** ['HS256']. -
Chunk 2 — describe the tables and give every request its own database session
Now there is somewhere to keep data. Models say what a table looks like;
get_sessionhands one session to each request and cleans it up afterwards. The service, later, decides when to commit.Step-by-step: what chunk 2 does, in plain English
- Each class with
Mapped[...]fields becomes a table;ForeignKeylinks tables. - Money columns are integers:
price_cents,total_cents. MenuItem.restaurant = relationship()tells SQLAlchemy to insert restaurants before their menu items.make_enginebuilds the connection pool; SQLite gets no pool arguments, Postgres gets size and overflow.get_sessionyields a session, rolls back if the request raised, and always closes it.
app/models.py — chunk 2 (the tables that matter; Customer, Restaurant and IdempotencyKey follow the same pattern)runs offlineclass MenuItem(Base): __tablename__ = "menu_items" id: Mapped[int] = mapped_column(primary_key=True) restaurant_id: Mapped[int] = mapped_column(ForeignKey("restaurants.id")) name: Mapped[str] = mapped_column(String(100)) price_cents: Mapped[int] = mapped_column(Integer) stock: Mapped[int] = mapped_column(Integer) restaurant: Mapped[Restaurant] = relationship() # tells the unit of work: restaurants before menu items class Order(Base): __tablename__ = "orders" id: Mapped[int] = mapped_column(primary_key=True) customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"), index=True) restaurant_id: Mapped[int] = mapped_column(ForeignKey("restaurants.id")) status: Mapped[str] = mapped_column(String(20), default="placed") total_cents: Mapped[int] = mapped_column(Integer) delivery_note: Mapped[str | None] = mapped_column(String(200), default=None) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) lines: Mapped[list["OrderLine"]] = relationship(back_populates="order", cascade="all, delete-orphan") class OrderLine(Base): __tablename__ = "order_lines" id: Mapped[int] = mapped_column(primary_key=True) order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"), index=True) menu_item_id: Mapped[int] = mapped_column(ForeignKey("menu_items.id")) qty: Mapped[int] = mapped_column(Integer) price_cents: Mapped[int] = mapped_column(Integer) # price at the time of ordering order: Mapped[Order] = relationship(back_populates="lines") class IdempotencyKey(Base): __tablename__ = "idempotency_keys" key: Mapped[str] = mapped_column(String(100), primary_key=True) customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id")) request_hash: Mapped[str] = mapped_column(String(64)) response_json: Mapped[str] = mapped_column(Text)app/db.py — chunk 2runs offlinefrom collections.abc import Iterator from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.orm import Session, sessionmaker from app.core.config import Settings, get_settings def make_engine(settings: Settings) -> Engine: if settings.database_url.startswith("sqlite"): return create_engine(settings.database_url, connect_args={"check_same_thread": False}) return create_engine( settings.database_url, pool_size=settings.db_pool_size, max_overflow=settings.db_max_overflow, pool_timeout=5, pool_pre_ping=True, ) engine = make_engine(get_settings()) # lazy: no connection is opened until first use SessionLocal = sessionmaker(engine, expire_on_commit=False) def get_session() -> Iterator[Session]: """One Session per request. The service decides when to commit; this only cleans up.""" session = SessionLocal() try: yield session except Exception: session.rollback() raise finally: session.close()sqlalchemy.orm.Mapped/mapped_column(typed columns) and ayielddependency.Run
python -c "from sqlalchemy import create_engine, inspect; from app.models import Base; e = create_engine('sqlite://'); Base.metadata.create_all(e); print(sorted(inspect(e).get_table_names()))". You should see['customers', 'idempotency_keys', 'menu_items', 'order_lines', 'orders', 'restaurants']. - Each class with
-
Chunk 3 — define what clients may send and what they get back
The boundary comes before the logic: separate request and response models, so internal fields cannot leak and bad input stops at the door.
Step-by-step: what chunk 3 does, in plain English
Qtyis an integer greater than 0 and at most 50, reused wherever a quantity appears.OrderCreateneeds at least one line and rejects the same menu item twice.OrderOutlists exactly the fields we return, withfrom_attributesso it can read a database object.OrderStatusUpdatemakes every field optional, for PATCH withexclude_unset.Problemdocuments the error shape.
app/schemas.py — chunk 3runs offlinefrom datetime import UTC, datetime from typing import Annotated, Literal from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator Qty = Annotated[int, Field(gt=0, le=50)] OrderStatus = Literal["placed", "confirmed", "preparing", "out_for_delivery", "delivered", "cancelled"] class OrderLineIn(BaseModel): menu_item_id: int qty: Qty class OrderCreate(BaseModel): restaurant_id: int lines: Annotated[list[OrderLineIn], Field(min_length=1, max_length=100)] delivery_note: Annotated[str, Field(max_length=200)] | None = None @model_validator(mode="after") def no_duplicate_items(self): ids = [line.menu_item_id for line in self.lines] if len(ids) != len(set(ids)): raise ValueError("each menu item may appear once; raise qty instead") return self class OrderLineOut(BaseModel): model_config = ConfigDict(from_attributes=True) menu_item_id: int qty: int price_cents: int class OrderOut(BaseModel): model_config = ConfigDict(from_attributes=True) id: int customer_id: int restaurant_id: int status: str total_cents: int delivery_note: str | None = None created_at: datetime lines: list[OrderLineOut]Annotated[int, Field(gt=0, le=50)]reusable constraints, and amodel_validatorfor a cross-field rule.Run
OrderCreate.model_validate(...)withqty: 2, then withqty: 0. You should see the parsed model, then('lines', 0, 'qty') Input should be greater than 0. -
Chunk 4 — place an order: stock check, price, and idempotency in one transaction
This is the heart of the app and it needs no HTTP at all. The repository holds queries; the service holds the rules and owns the commit.
Step-by-step: what chunk 4 does, in plain English
- Open a transaction with
with self.session.begin(). - If an
Idempotency-Keywas given and already stored: same request returns the stored answer; a different request raisesIdempotencyConflict. - Check the restaurant is open; for each line, in a fixed order, run the atomic
UPDATE ... WHERE stock >= qty; no row updated meansOutOfStock, and the whole transaction rolls back. - Insert the order and its lines, and store the response under the key in the same transaction.
- If two identical requests race and the insert collides, the unique key makes one lose; it returns the winner's stored answer.
app/repositories.py — chunk 4 (take_stock)runs offlinedef take_stock(self, menu_item_id: int, qty: int) -> bool: """Atomic check-and-decrement: one statement, so two buyers cannot both win the last item.""" result = self.session.execute( update(MenuItem) .where(MenuItem.id == menu_item_id, MenuItem.stock >= qty) .values(stock=MenuItem.stock - qty) ) return result.rowcount == 1app/services.py — chunk 4 (create_order and replay)runs offlinedef create_order(self, customer_id: int, payload: OrderCreate, idempotency_key: str | None = None ) -> tuple[OrderOut, bool]: """Returns (order, replayed). replayed=True means we returned a stored answer.""" digest = request_hash(customer_id, payload) try: with self.session.begin(): if idempotency_key: stored = self._replay(idempotency_key, digest) if stored: return stored, True order = self._place(customer_id, payload) out = OrderOut.model_validate(order) if idempotency_key: self.repo.add_idempotency_key(IdempotencyKey( key=idempotency_key, customer_id=customer_id, request_hash=digest, response_json=out.model_dump_json())) log.info("order_created", order_id=order.id, customer_id=customer_id, total_cents=order.total_cents) return out, False except IntegrityError: # Two identical requests raced; the unique key on idempotency_keys let one win. if not idempotency_key: raise with self.session.begin(): stored = self._replay(idempotency_key, digest) if stored is None: raise return stored, True def _replay(self, key: str, digest: str) -> OrderOut | None: row = self.repo.get_idempotency_key(key) if row is None: return None if row.request_hash != digest: raise IdempotencyConflict("This Idempotency-Key was already used with a different request body.") return OrderOut.model_validate_json(row.response_json)An atomic conditional
UPDATEwithrowcount, and catchingIntegrityErrorafter a failed commit.Run the service twice with key
k-1, then ask for 9 biryanis. You should seefirst : 1 2400 replayed False,second: 1 2400 replayed True, andOutOfStock: Not enough stock of 'Chicken biryani' for quantity 9. - Open a transaction with
-
Chunk 5 — decide who is calling, and turn every failure into a problem response
The service can place orders; now it must know for whom, and say no politely. Security and errors come together because every refusal is an error response.
Step-by-step: what chunk 5 does, in plain English
get_current_userreads the bearer token, callsverify_token, and returns aUser; any failure becomes a 401.require_scope("orders:write")builds a dependency that answers 403 when the scope is missing.DomainErrorsubclasses carry an HTTP status and a type slug; services raise them.register_error_handlersmaps validation errors, HTTP errors, domain errors and any other exception toapplication/problem+json.
app/security.py — chunk 5 (user and scope checks)runs offlinedef get_current_user( creds: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)], settings: Annotated[Settings, Depends(get_settings)], ) -> User: if creds is None: raise unauthorized() try: claims = verify_token(creds.credentials, settings) return User(id=int(claims["sub"]), role=claims.get("role", "customer"), scopes=frozenset(claims.get("scope", "").split())) except (jwt.InvalidTokenError, ValueError) as exc: log.warning("token_rejected", reason=type(exc).__name__) # name only: never log the token raise unauthorized() from exc def require_scope(scope: str): """Factory: returns a dependency that needs the caller to hold `scope`.""" def checker(user: Annotated[User, Depends(get_current_user)]) -> User: if scope not in user.scopes: raise HTTPException(403, f"Missing scope: {scope}") return user return checkerapp/errors.py — chunk 5 (domain errors)runs offlineclass DomainError(Exception): """A business rule said no. Subclasses pick the HTTP status and a stable type slug.""" status = 400 slug = "domain-error" title = "Request cannot be processed" def __init__(self, detail: str | None = None): super().__init__(detail or self.title) self.detail = detail or self.title class OutOfStock(DomainError): status, slug, title = 409, "out-of-stock", "Item out of stock" class RestaurantClosed(DomainError): status, slug, title = 409, "restaurant-closed", "Restaurant is closed" class UnknownMenuItem(DomainError): status, slug, title = 422, "unknown-menu-item", "Unknown menu item" class OrderNotFound(DomainError): status, slug, title = 404, "order-not-found", "Order not found" class IdempotencyConflict(DomainError): status, slug, title = 422, "idempotency-key-reused", "Idempotency-Key reused with a different request" class InvalidTransition(DomainError): status, slug, title = 409, "invalid-status-transition", "Status change not allowed" class InvalidCursor(DomainError): status, slug, title = 400, "invalid-cursor", "Invalid pagination cursor"A dependency factory (
require_scopereturns a function) and FastAPI exception handlers.Run
verify_tokenon a good HS256 token and on one with the wrong audience. You should see7(the subject), thenInvalidAudienceError. -
Chunk 6 — expose it over HTTP and start the server
With the rules and the guards in place, the router is thin: parse, call the service, set headers.
create_appassembles everything.Step-by-step: what chunk 6 does, in plain English
APIRouter(prefix="/v1/orders")groups the four order endpoints; each takesuser: Readeroruser: Writer.- POST returns 201 with a
Locationheader; a replayed idempotent request returns 200 andIdempotent-Replayed: true. - GET and PATCH add the
ETag,If-None-MatchandIf-Matchbehaviour. create_app()adds the request-id middleware, optional CORS, the handlers and the routers; the lifespan logs start-up and shutdown and disposes the engine.
app/routers/orders.py — chunk 6 (create and list)runs offline@router.post("", status_code=201, response_model=OrderOut) def create_order(payload: OrderCreate, response: Response, session: SessionDep, user: Writer, idempotency_key: Annotated[str | None, Header(max_length=100)] = None): order, replayed = OrderService(session).create_order(user.id, payload, idempotency_key) response.headers["Location"] = f"/v1/orders/{order.id}" if replayed: response.status_code = 200 response.headers["Idempotent-Replayed"] = "true" return order @router.get("", response_model=OrderPage) def list_orders(session: SessionDep, user: Reader, cursor: str | None = None, limit: Annotated[int, Query(ge=1, le=100)] = 20): items, next_cursor = OrderService(session).list_orders(user.id, limit, cursor) return OrderPage(items=items, next_cursor=next_cursor)app/main.py — chunk 6runs offlinefrom contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from sqlalchemy.engine import Engine from app import db from app.core.config import Settings, get_settings from app.core.logging import RequestIdMiddleware, configure_logging, get_logger from app.errors import register_error_handlers from app.models import Base from app.routers import health, orders log = get_logger("quickbite.main") @asynccontextmanager async def lifespan(app: FastAPI): settings: Settings = app.state.settings log.info("startup", database=settings.database_url.split("://")[0]) if settings.create_tables: Base.metadata.create_all(app.state.engine) yield # the app serves requests here app.state.engine.dispose() log.info("shutdown") def create_app(settings: Settings | None = None, engine: Engine | None = None) -> FastAPI: settings = settings or get_settings() configure_logging() app = FastAPI(title="QuickBite API", version="1.0.0", lifespan=lifespan) app.state.settings = settings app.state.engine = engine or db.engine register_error_handlers(app) if settings.cors_origins: app.add_middleware(CORSMiddleware, allow_origins=settings.cors_origins, allow_methods=["GET", "POST", "PATCH"], allow_headers=["Authorization", "Content-Type", "Idempotency-Key"]) app.add_middleware(RequestIdMiddleware) # added last = outermost = sees every request first app.include_router(health.router) app.include_router(orders.router) return appcreate_app()as an application factory, started withuvicorn app.main:create_app --factory.Run
python -m app.seed, start uvicorn, andcurl localhost:8123/healthz. You should see{"status":"ok"}. Posting an order twice with the sameIdempotency-Keygives a 201 body with"total_cents":2400and thenreplay -> HTTP 200. -
Chunk 7 — prove it with tests that run the real app against a fresh database
Last, the safety net: fixtures that give each test its own SQLite database, a signing key and a token factory.
Step-by-step: what chunk 7 does, in plain English
- The
enginefixture builds an in-memory SQLite database withStaticPooland seeds it. - The
appfixture overridesget_sessionandget_settings. make_tokensigns real RS256 tokens, so tests for expiry, audience and scope are one argument each.- Tests call the app with
TestClient; a few useAsyncClientwithASGITransport.
tests/test_security.py — chunk 7 (two of the 16 security tests)runs offlinedef test_forged_token_without_signature_check_is_rejected(client): """The 'temporary' bug: decode(..., verify_signature=False) would accept this.""" now = int(time.time()) forged = jwt.encode({"sub": "2", "iss": ISSUER, "aud": AUDIENCE, "exp": now + 300, "scope": "orders:read"}, "attacker-chosen-secret-of-sufficient-length", algorithm="HS256") assert get_orders(client, forged).status_code == 401 def test_alg_none_is_rejected(client): now = int(time.time()) unsigned = jwt.encode({"sub": "1", "iss": ISSUER, "aud": AUDIENCE, "exp": now + 300, "scope": "orders:read"}, key=None, algorithm="none") assert get_orders(client, unsigned).status_code == 401tests/test_orders.py — chunk 7 (the idempotency test)runs offlinedef test_idempotency_same_key_same_body_returns_same_order(client, auth, engine): first = place(client, auth, key="k-1") second = place(client, auth, key="k-1") assert first.status_code == 201 and second.status_code == 200 assert second.headers["Idempotent-Replayed"] == "true" assert first.json()["id"] == second.json()["id"] from sqlalchemy import text with engine.connect() as c: assert c.execute(text("select count(*) from orders")).scalar() == 1app.dependency_overridesand a session-scoped RSA key fixture.Run
python -m pytest -q. You should see44 passed, 1 skipped(the skip is the Postgres test). - The
The whole program
The app is a package, so there is no single file. The tree shows which chunk each file belongs to; below it are the three files that tie the chunks together: services.py (chunk 4), routers/orders.py (chunk 6) and main.py (chunk 6), complete. The rest are in code/e20-python-api/quickbite_api/.
# illustrative
quickbite_api/
├── pyproject.toml # chunk 1 dependencies, pinned
├── uv.lock # chunk 1 exact versions, with hashes
├── Dockerfile # deployment, section 07
├── README.md
├── app/
│ ├── main.py # chunk 6 create_app(), lifespan
│ ├── core/
│ │ ├── config.py # chunk 1 Settings
│ │ └── logging.py # request-id middleware, structlog
│ ├── db.py # chunk 2 engine, SessionLocal, get_session
│ ├── models.py # chunk 2 tables
│ ├── schemas.py # chunk 3 Pydantic models
│ ├── repositories.py # chunk 4 queries only
│ ├── services.py # chunk 4 rules, transactions, idempotency
│ ├── security.py # chunk 5 verify_token, get_current_user, require_scope
│ ├── errors.py # chunk 5 problem details
│ ├── seed.py # demo data
│ └── routers/
│ ├── orders.py # chunk 6 /v1/orders
│ └── health.py # chunk 6 /healthz, /readyz
└── tests/ # chunk 7 44 tests + 1 opt-in Postgres test
import hashlib
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.core.logging import get_logger
from app.errors import (IdempotencyConflict, InvalidTransition, OrderNotFound, OutOfStock,
RestaurantClosed, UnknownMenuItem)
from app.models import IdempotencyKey, Order, OrderLine
from app.repositories import OrderRepository
from app.schemas import OrderCreate, OrderOut, OrderStatusUpdate
log = get_logger("quickbite.orders")
ALLOWED = {
"placed": {"confirmed", "cancelled"},
"confirmed": {"preparing", "cancelled"},
"preparing": {"out_for_delivery"},
"out_for_delivery": {"delivered"},
"delivered": set(),
"cancelled": set(),
}
def request_hash(customer_id: int, payload: OrderCreate) -> str:
body = payload.model_dump_json() # same JSON in, same hash out; the customer id is part of it
return hashlib.sha256(f"{customer_id}:{body}".encode()).hexdigest()
class OrderService:
"""Business rules and transactions. The service owns the commit."""
def __init__(self, session: Session):
self.session = session
self.repo = OrderRepository(session)
def create_order(self, customer_id: int, payload: OrderCreate, idempotency_key: str | None = None
) -> tuple[OrderOut, bool]:
"""Returns (order, replayed). replayed=True means we returned a stored answer."""
digest = request_hash(customer_id, payload)
try:
with self.session.begin():
if idempotency_key:
stored = self._replay(idempotency_key, digest)
if stored:
return stored, True
order = self._place(customer_id, payload)
out = OrderOut.model_validate(order)
if idempotency_key:
self.repo.add_idempotency_key(IdempotencyKey(
key=idempotency_key, customer_id=customer_id,
request_hash=digest, response_json=out.model_dump_json()))
log.info("order_created", order_id=order.id, customer_id=customer_id,
total_cents=order.total_cents)
return out, False
except IntegrityError:
# Two identical requests raced; the unique key on idempotency_keys let one win.
if not idempotency_key:
raise
with self.session.begin():
stored = self._replay(idempotency_key, digest)
if stored is None:
raise
return stored, True
def _replay(self, key: str, digest: str) -> OrderOut | None:
row = self.repo.get_idempotency_key(key)
if row is None:
return None
if row.request_hash != digest:
raise IdempotencyConflict("This Idempotency-Key was already used with a different request body.")
return OrderOut.model_validate_json(row.response_json)
def _place(self, customer_id: int, payload: OrderCreate) -> Order:
restaurant = self.repo.get_restaurant(payload.restaurant_id)
if restaurant is None or not restaurant.is_open:
raise RestaurantClosed("The restaurant does not exist or is not taking orders.")
items = self.repo.get_menu_items([line.menu_item_id for line in payload.lines])
total = 0
lines: list[OrderLine] = []
for line in sorted(payload.lines, key=lambda x: x.menu_item_id): # fixed order avoids deadlocks
item = items.get(line.menu_item_id)
if item is None or item.restaurant_id != payload.restaurant_id:
raise UnknownMenuItem(f"Menu item {line.menu_item_id} is not on this restaurant's menu.")
if not self.repo.take_stock(item.id, line.qty):
raise OutOfStock(f"Not enough stock of '{item.name}' for quantity {line.qty}.")
total += item.price_cents * line.qty
lines.append(OrderLine(menu_item_id=item.id, qty=line.qty, price_cents=item.price_cents))
order = Order(customer_id=customer_id, restaurant_id=payload.restaurant_id, total_cents=total,
delivery_note=payload.delivery_note, lines=lines)
return self.repo.add(order)
def get_order(self, order_id: int, customer_id: int | None) -> OrderOut:
with self.session.begin():
order = self.repo.get_order(order_id, customer_id)
if order is None:
raise OrderNotFound() # 404 for both "missing" and "not yours"
return OrderOut.model_validate(order)
def list_orders(self, customer_id: int, limit: int, cursor: str | None):
with self.session.begin():
rows, next_cursor = self.repo.list_page(customer_id, limit, cursor)
return [OrderOut.model_validate(r) for r in rows], next_cursor
def update_order(self, order_id: int, customer_id: int | None, patch: OrderStatusUpdate) -> OrderOut:
changes = patch.model_dump(exclude_unset=True) # only what the client actually sent
with self.session.begin():
order = self.repo.get_order(order_id, customer_id)
if order is None:
raise OrderNotFound()
new_status = changes.get("status")
if new_status is not None and new_status != order.status:
if new_status not in ALLOWED[order.status]:
raise InvalidTransition(f"Cannot go from '{order.status}' to '{new_status}'.")
for field, value in changes.items():
if field == "status" and value is None:
continue # status is never cleared
setattr(order, field, value)
self.session.flush()
return OrderOut.model_validate(order)import hashlib
from typing import Annotated
from fastapi import APIRouter, Depends, Header, Query, Request, Response
from sqlalchemy.orm import Session
from app.db import get_session
from app.errors import problem
from app.schemas import OrderCreate, OrderOut, OrderPage, OrderStatusUpdate
from app.security import User, require_scope
from app.services import OrderService
router = APIRouter(prefix="/v1/orders", tags=["orders"])
SessionDep = Annotated[Session, Depends(get_session)]
Reader = Annotated[User, Depends(require_scope("orders:read"))]
Writer = Annotated[User, Depends(require_scope("orders:write"))]
def owner_filter(user: User) -> int | None:
return None if user.role == "admin" else user.id # admins see every order
def etag_of(order: OrderOut) -> str:
return 'W/"' + hashlib.sha1(order.model_dump_json().encode()).hexdigest()[:16] + '"'
@router.post("", status_code=201, response_model=OrderOut)
def create_order(payload: OrderCreate, response: Response, session: SessionDep, user: Writer,
idempotency_key: Annotated[str | None, Header(max_length=100)] = None):
order, replayed = OrderService(session).create_order(user.id, payload, idempotency_key)
response.headers["Location"] = f"/v1/orders/{order.id}"
if replayed:
response.status_code = 200
response.headers["Idempotent-Replayed"] = "true"
return order
@router.get("", response_model=OrderPage)
def list_orders(session: SessionDep, user: Reader,
cursor: str | None = None, limit: Annotated[int, Query(ge=1, le=100)] = 20):
items, next_cursor = OrderService(session).list_orders(user.id, limit, cursor)
return OrderPage(items=items, next_cursor=next_cursor)
@router.get("/{order_id}", response_model=OrderOut)
def get_order(order_id: int, request: Request, response: Response, session: SessionDep, user: Reader,
if_none_match: Annotated[str | None, Header()] = None):
order = OrderService(session).get_order(order_id, owner_filter(user))
tag = etag_of(order)
if if_none_match == tag:
return Response(status_code=304, headers={"ETag": tag})
response.headers["ETag"] = tag
return order
@router.patch("/{order_id}", response_model=OrderOut)
def patch_order(order_id: int, patch: OrderStatusUpdate, request: Request, response: Response,
session: SessionDep, user: Writer, if_match: Annotated[str | None, Header()] = None):
service = OrderService(session)
if if_match is not None:
current = service.get_order(order_id, owner_filter(user))
if if_match != etag_of(current):
return problem(request, 412, "Precondition Failed", "The order changed since you read it.")
updated = service.update_order(order_id, owner_filter(user), patch)
response.headers["ETag"] = etag_of(updated)
return updatedfrom contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.engine import Engine
from app import db
from app.core.config import Settings, get_settings
from app.core.logging import RequestIdMiddleware, configure_logging, get_logger
from app.errors import register_error_handlers
from app.models import Base
from app.routers import health, orders
log = get_logger("quickbite.main")
@asynccontextmanager
async def lifespan(app: FastAPI):
settings: Settings = app.state.settings
log.info("startup", database=settings.database_url.split("://")[0])
if settings.create_tables:
Base.metadata.create_all(app.state.engine)
yield # the app serves requests here
app.state.engine.dispose()
log.info("shutdown")
def create_app(settings: Settings | None = None, engine: Engine | None = None) -> FastAPI:
settings = settings or get_settings()
configure_logging()
app = FastAPI(title="QuickBite API", version="1.0.0", lifespan=lifespan)
app.state.settings = settings
app.state.engine = engine or db.engine
register_error_handlers(app)
if settings.cors_origins:
app.add_middleware(CORSMiddleware, allow_origins=settings.cors_origins,
allow_methods=["GET", "POST", "PATCH"],
allow_headers=["Authorization", "Content-Type", "Idempotency-Key"])
app.add_middleware(RequestIdMiddleware) # added last = outermost = sees every request first
app.include_router(health.router)
app.include_router(orders.router)
return appHow to read it: a request enters main.py's middleware (request id), is matched by routers/orders.py, which resolves Writer (authentication, then scope) and the session, validates the body against OrderCreate, and hands plain values to OrderService. The service runs one transaction and raises domain errors; the repository only builds queries. The handlers turn any failure into a problem response, and the response model decides which fields leave the building.
Test counts by file: 15 in test_orders.py, 16 in test_security.py, 9 in test_errors_pagination.py, 4 in test_observability.py, and 1 optional in test_postgres.py. Run against a real PostgreSQL 18 container, all 45 pass.
08 · DrillASGI, Routing and Pydantic — Q1–Q40
The first forty questions cover what happens between the network socket and your function, how FastAPI turns a URL and a JSON body into typed Python values, and how Pydantic v2 validates and shapes them. Senior rounds probe the mechanism behind each rule (why def runs in a thread, why a route never matches) rather than the vocabulary.
Every answer is written to be said aloud, and every demo was run on the course machine with FastAPI 0.141.1, Starlette 1.6.0 and Pydantic 2.13.5. Say yours first, then reveal. Scripts live in code/e20-python-api/D/.
These questions test whether you can follow one request through the server, the event loop and the threadpool, and say which of them is busy at each moment.
Q1. "What is ASGI, and how is it different from WSGI?"
Reveal answer
The real test Whether you can say "an async callable that exchanges events" and name what that buys (streaming, WebSockets, many waiting connections on one thread), instead of "ASGI is the async version of WSGI".
Strong answer ASGI (Asynchronous Server Gateway Interface) is the contract between a Python web server (uvicorn, Granian, Hypercorn) and a Python web application (Starlette, FastAPI). The server owns the sockets. The application owns the logic. ASGI says exactly how they talk.
The application is one async function: async def app(scope, receive, send). scope is a dict describing the connection (type, path, headers). receive() hands over events such as "a chunk of request body arrived". send(...) pushes events back such as "response headers" and "a chunk of body".
WSGI (the older standard behind Flask and Django) is one plain function: app(environ, start_response) that returns the whole body. One call, one thread, one request. There is no way to say "send this chunk now, wait for more later".
Because ASGI talks in events, one connection can live a long time: a WebSocket, a server-sent-events stream, a streaming upload. And because the callable is async, one thread can hold thousands of connections that are merely waiting.
Picture it Same hello, two contracts. The WSGI function returns once; the ASGI function receives and sends several events. This runs with no framework at all.
The setup: A WSGI callable and an ASGI callable, each answering a request. The ASGI one is called through httpx's in-process transport, so the "server" is a few lines of httpx.
import asyncio, httpx
def wsgi_app(environ, start_response): # WSGI: one call, returns the whole body
start_response("200 OK", [("content-type", "text/plain")])
return [b"hello from wsgi"]
async def asgi_app(scope, receive, send): # ASGI: an async callable that talks in events
print("scope:", scope["type"], scope["method"], scope["path"])
event = await receive() # the request body arrives as an event
print("received:", event["type"], event["body"])
await send({"type": "http.response.start", "status": 200,
"headers": [(b"content-type", b"text/plain")]})
await send({"type": "http.response.body", "body": b"part 1 ", "more_body": True})
await send({"type": "http.response.body", "body": b"part 2"})
print("sent: start + 2 body events")
async def main():
out = []
body = wsgi_app({}, lambda status, headers: out.append(status))
print("wsgi returned:", out[0], body)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=asgi_app), base_url="http://t") as c:
r = await c.post("/orders", content=b"{}")
print("client got:", r.status_code, r.text)
asyncio.run(main())Make the invisible visible: Run it and watch the events.
wsgi returned: 200 OK [b'hello from wsgi']
scope: http POST /orders
received: http.request b'{}'
sent: start + 2 body events
client got: 200 part 1 part 2What you see: The WSGI function got its answer in one return value. The ASGI function saw the scope, received one http.request event, then sent three events: start, body part 1 (marked more_body), body part 2.
Why: Everything FastAPI does (routing, validation, dependencies) sits inside that one async def. Knowing the callable shape makes middleware, streaming and WebSockets obvious: they are all just more events.
Servlet API · Java
One method per request, on a pool thread, returning when the response is written.
// illustrative
void doGet(HttpServletRequest req,
HttpServletResponse res) {
res.setStatus(200);
res.getWriter().write("hello");
} // thread is held until this returnsASGI · Python
One async callable per connection, trading events with the server.
async def app(scope, receive, send):
await send({"type": "http.response.start",
"status": 200, "headers": []})
await send({"type": "http.response.body",
"body": b"hello"})The shift: A servlet holds a thread for the whole call; an ASGI app yields the thread whenever it awaits, so waiting is nearly free.
Land it I describe ASGI as an event conversation between server and app, which is why it can stream, hold WebSockets and keep thousands of waiting requests on one thread.
- "Is ASGI slower than WSGI for ordinary requests?"
-
No, not by an amount you would notice for one simple request. The time a request takes is almost all your own code and the database call, and the server-to-app handoff is a few microseconds in either standard.
Where ASGI changes the picture is capacity, not speed. Say each request spends 200 ms waiting on a database. A WSGI worker with 16 threads can hold 16 such requests at once. One ASGI event loop can hold thousands of them, because a request that is only waiting costs a small object in memory, not a whole thread with its own stack.
The opposite case matters too. If every request is CPU-heavy, neither standard helps, because one Python process runs one stream of bytecode at a time (the GIL, covered in E19). Then you scale with processes.
So I would never pick ASGI for raw speed on a quiet service. I pick it when many connections are waiting, or when I need streaming and WebSockets.
- "Can a WSGI app run under ASGI, or the reverse?"
-
Yes, in one direction and with adapters. A WSGI app can be mounted inside an ASGI app, so a Flask application can sit under FastAPI. The reverse is not possible in general.
The adapter works by running the whole blocking WSGI function in a worker thread and turning its finished return value into ASGI events. Starlette ships
WSGIMiddlewarefor this, now deprecated in favour of the separatea2wsgipackage. Check which one your version recommends.The reverse fails because WSGI has no vocabulary for "send this chunk now, more later". A WSGI server expects the full body from one call, so a WebSocket or an event stream cannot be expressed at all.
The adapter is the usual migration path from Flask to FastAPI. I mount the old app at
/legacy, move routes one at a time into the new app, and delete the mount when the last route has moved (Q146). Remember the legacy routes run in threads, so they share the 40-thread pool. - "What is in the
scopedict?" -
It is a plain Python dict that the server builds once per connection and hands to the app. It describes the connection, not the body. The body comes later, through
receive().The keys I use most are in the block below. Header names are lower-case bytes, which surprises people who expect strings.
scope keysruns offlinetype "http" | "websocket" | "lifespan" method "POST" path "/v1/orders" query_string b"limit=20" headers [(b"host", b"api"), (b"authorization", b"Bearer ...")] client ("10.0.0.7", 51234) app the FastAPI object (set by Starlette)The
typekey is why one callable serves three jobs: normal HTTP, WebSockets, and the start-up and shut-down conversation called lifespan (Q45).The server owns the scope. If you need to pass data from middleware to the endpoint, put it in
scope["state"]orrequest.state, not in a global. Starlette'srequest.url,request.headersandrequest.clientare friendly wrappers around these same keys, so nothing is hidden. - "Where does the framework fit in the picture?"
-
The framework is the application. The server calls one function,
app(scope, receive, send), and the framework is whatever object answers that call.In Starlette that function is
Starlette.__call__. On the first call it builds the middleware stack. Then each request passes inward through the layers, the router picks a route by method and path, and the route calls your endpoint.FastAPI is a subclass of Starlette. It does not replace the plumbing. It adds a smarter route class that reads your function signature, validates values with Pydantic, runs
Dependsfunctions and builds the OpenAPI document (Q7).So "ASGI app", "Starlette app" and "FastAPI app" name the same object seen at three layers. This matters when debugging: a stack trace that starts in
uvicornand passes throughstarlette/middlewarebefore reachingfastapi/routing.pyis exactly this picture. I read traces from the bottom layer up to find which layer produced the symptom.
Q2. "Walk one request from the TCP socket to your endpoint in FastAPI."
Reveal answer
Strong answer Eight steps, and I name the owner of each. First, the kernel accepts the TCP connection. Second, uvicorn (running an event loop, the single thread that juggles all waiting connections) reads bytes and parses them as HTTP, using httptools if installed.
Third, uvicorn builds the scope dict and calls the ASGI app. Fourth, Starlette's middleware stack runs: error handling, CORS, your own middleware, each wrapping the next. Fifth, the router matches method and path and picks the route.
Sixth, FastAPI's dependency solver reads the endpoint signature, parses path, query, header and body values, validates them with Pydantic and runs Depends functions. Seventh, your endpoint runs: on the event loop if async def, in a worker thread if plain def.
Eighth, FastAPI passes the return value through the response model (validate and filter), serialises to JSON bytes, and sends http.response.start and http.response.body events back down the same path. Uvicorn writes them to the socket.
Picture it One tiny app that prints a line at each stage it controls, so the order is visible rather than remembered.
The setup: A middleware, a dependency, a def endpoint and a response model that drops a field.
import asyncio, httpx, threading
from fastapi import FastAPI, Depends, Request
from pydantic import BaseModel
app = FastAPI()
@app.middleware("http")
async def mw(request: Request, call_next):
print("1 middleware in (before routing)")
response = await call_next(request)
print("7 middleware out (response object exists)")
return response
def get_user():
print("3 dependency get_user runs")
return "cust-7"
class OrderOut(BaseModel):
id: int
owner: str
@app.get("/orders/{order_id}", response_model=OrderOut)
def get_order(order_id: int, user: str = Depends(get_user)):
print("4 endpoint runs in thread:", threading.current_thread().name.split("_")[0])
return {"id": order_id, "owner": user, "secret": "dropped"}
async def main():
print("0 uvicorn parsed the HTTP bytes, built scope, called the ASGI app")
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
r = await c.get("/orders/5")
print("8 client sees:", r.status_code, r.json())
asyncio.run(main())Make the invisible visible: Run it.
0 uvicorn parsed the HTTP bytes, built scope, called the ASGI app
1 middleware in (before routing)
3 dependency get_user runs
4 endpoint runs in thread: AnyIO worker thread
7 middleware out (response object exists)
8 client sees: 200 {'id': 5, 'owner': 'cust-7'}What you see: The numbers skip 2, 5 and 6. Those are the parts that print nothing: router matching, request validation, and response serialisation. Notice step 4 reports "AnyIO worker thread": the plain def endpoint left the event loop.
Why: The secret key the endpoint returned never reached the client: step 6 of the real list (response model) filtered it. Order matters when you debug: a 422 means the failure happened before your endpoint, a leaked field means it happened after.
Land it I can name the owner of each hop (kernel, uvicorn, middleware, router, solver, endpoint, serialiser) and I debug by asking which hop produced the symptom.
- "Where does request validation happen relative to dependencies?"
-
They are resolved together, by one solver, in the sixth step of the walk. The solver reads the signature, orders dependencies so each runs after the ones it needs, and collects every parsing error as it goes.
If any parameter fails validation, FastAPI gathers all the errors and returns one 422. Your endpoint is never called. The client sees every problem at once, not one per attempt.
The subtle part is that a dependency may already have run when another parameter's error aborts the request. A
get_sessiondependency could have opened a database session before a bad query parameter was found. Nothing is wrong with that, but it means cleanup code must run even on failure.That is exactly why yield dependencies put their cleanup in a
finallyblock (Q43). I assume any dependency can be started and then abandoned, so it must be safe to throw away at any moment. - "Does middleware see the request before routing?"
-
Yes. Middleware wraps the whole application, so it runs before the router has even decided which route will match. At that point the only things known are the scope: method, path string, headers.
Two consequences follow. First, middleware cannot read path parameters such as
order_id, because those are produced by the router, which runs later. Second, middleware cannot tell a public route from a protected one without matching the path itself.That is why per-route concerns belong in dependencies, not middleware (Q50). A dependency is attached to a router or a route, so it only runs where it applies, and it sees the parsed parameters.
What does belong in middleware is anything every request needs no matter which route it hits: a request id, timing, a last-resort error catcher, CORS headers. A test for placement: if I can describe the rule without naming a route, it is middleware. If I need to say "except the health check", it is a dependency.
- "What does uvicorn do while my
defendpoint runs in a thread?" -
It keeps serving other connections. The event loop thread only hands the call to the threadpool and moves on. That is the whole point of putting
defendpoints in threads.When the thread finishes, it tells the loop through a callback, the loop wakes the waiting request, and the response goes back down the path. The handoff costs a few tens of microseconds each way, so a tiny
defendpoint is not slower in any way you would notice.The limit is the pool. AnyIO allows 40 threads at once. Request 41 waits for a free slot, and during that wait the loop is still healthy, but that request is queued. Nothing shows in CPU graphs.
So the symptom of pool exhaustion looks different from a blocked loop. With a blocked loop, every endpoint slows, including
/healthz. With a full pool, only thedefendpoints queue, andasyncones stay fast. I use that difference to tell the two apart quickly. - "Where would I measure each stage?"
-
Each stage has its own tool, and I measure from the outside in.
- Total time: uvicorn access logs, or the proxy's request time, give the number the user felt.
- App time: a small timing middleware records time from entering the app to the first response byte.
- Your code: a timer inside a dependency or the endpoint isolates your own work, and OpenTelemetry spans (Q130) show the same split in production.
The rule of thumb is a subtraction. If total time is far above endpoint time, the cause is queueing before your code ran: a blocked loop, an exhausted threadpool, a saturated worker, or a full connection pool.
If the gap is small and endpoint time is large, the problem is inside your code, usually the database. I always compare at the same percentile, say p99 against p99, because averages hide queueing.
Q3. "def versus async def endpoints — what does FastAPI do with each?"
Reveal answer
Strong answer FastAPI checks whether the function is a coroutine function. For async def it simply awaits it on the event loop. For plain def it runs it in a worker thread through AnyIO's threadpool, so the loop stays free.
That threadpool has a default limit of 40 threads (AnyIO's default "capacity limiter" with 40 tokens). A 41st concurrent def request waits for a free token. This is the same number I quote everywhere in this chapter.
The rule: use async def only when everything you await inside is truly non-blocking (an async database driver, httpx.AsyncClient, asyncio.sleep). Use plain def when you call blocking libraries (a sync SQLAlchemy session, requests, time.sleep, file I/O).
Never call a blocking function inside async def. It freezes the single event loop, so every other request on that worker waits. That one mistake causes more Python API incidents than any other (Q4).
Picture it Two endpoints, one thread name each, printed from inside the handler.
import asyncio, httpx, threading
from fastapi import FastAPI
app = FastAPI()
def where():
loop = "on the event loop" if _in_loop() else "in a worker thread"
return f"{threading.current_thread().name} -> {loop}"
def _in_loop():
try:
asyncio.get_running_loop(); return True
except RuntimeError:
return False
@app.get("/sync")
def sync_endpoint(): # plain def: FastAPI hands it to the AnyIO threadpool
return {"where": where()}
@app.get("/async")
async def async_endpoint(): # async def: awaited directly on the loop
return {"where": where()}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for p in ("/sync", "/async"):
print(p, (await c.get(p)).json())
asyncio.run(main())Make the invisible visible: Run it.
/sync {'where': 'AnyIO worker thread -> in a worker thread'}
/async {'where': 'MainThread -> on the event loop'}What you see: The def endpoint ran in "AnyIO worker thread", the async def endpoint ran in the main thread, which is the event loop's thread.
Why: The thread name is the proof of what FastAPI did. In the primer's 50-request experiment (100 ms of work each) the same split showed up in time: async def + time.sleep took 5.06 s, async def + asyncio.sleep 0.11 s, plain def 0.27 s.
Naive
An async handler that blocks.
@app.get("/price")
async def price():
time.sleep(0.1) # ❌ TRAP
return {"ok": True}Correct
Plain def, or offload the call.
@app.get("/price")
def price(): # ✅ threadpool
time.sleep(0.1)
return {"ok": True}The shift: async is a promise that you never block; if you cannot keep it, drop the keyword.
Land it I pick async def only when every awaited call is non-blocking and plain def otherwise, and I remember the pool holds 40 threads.
- "Can I make the threadpool bigger?"
-
Yes. Raise the limiter's total tokens once at start-up, inside the lifespan:
anyio.to_thread.current_default_thread_limiter().total_tokens = 100. The limit is a setting, not a hard cap.The arithmetic shows what it buys. In the primer, 100 requests that each took 0.5 s in a
defendpoint finished in 1.57 s with 40 tokens. That is about three waves: 40, then 40, then 20, each wave about 0.5 s.Raising the limit only helps when the work is I/O waiting, since threads that compute fight over the GIL. It also needs the database pool to be larger, because a thread holding a session needs a connection. With 100 threads and a pool of 15, 85 threads wait for a connection and you have moved the queue, not removed it (Q60).
So I raise it in step with the pool, then load test. If p99 does not improve, I put the number back.
- "Is a plain
defendpoint ever the better choice even when an async driver exists?" -
Yes, and I choose it deliberately. If the endpoint is a short chain of blocking calls, say one ORM query plus a little logic, a plain
defis simpler and very hard to get wrong. FastAPI runs it in the threadpool and the loop stays free.Async has a price. Every call inside must be awaited, and one forgotten blocking call freezes the loop for everyone. With an async ORM session, lazy loading no longer works the way people expect, and a missed eager load becomes an error (Q59).
Async pays off when a request waits on many slow things at once: ten partner calls in parallel, a streaming response, thousands of idle connections. A CRUD endpoint doing one 5 ms query gains very little.
My rule is to start with
deffor the data path and useasync defwhere the waiting is the point. Then I measure before switching anything. Q58 lays out the trade-offs. - "What about CPU-heavy work in a
defendpoint?" -
It runs, but not in parallel. The thread keeps the request off the event loop, yet the GIL (the lock that lets only one thread run Python bytecode at a time) means two CPU-bound threads take turns on one core.
There is a second cost. A thread that computes holds the GIL in bursts, and the event loop thread needs the GIL too. So a PDF render in a
defendpoint can make every other request on that worker slower, includingasyncones. The loop is not blocked by a call, it is starved of the lock.A concrete scenario: ten 200 ms renders arriving together take about 2 s of one core's time, no matter that they use ten threads. Meanwhile unrelated requests see their latency rise.
CPU-heavy work belongs elsewhere: a process pool, or a separate worker fed by a queue (Q148). The endpoint then only submits the job and returns a job id. I keep threads for waiting and processes for computing.
- "Does
async defmake the endpoint faster?" -
No. It makes the endpoint cheaper to wait, not quicker to finish. A request that does 50 ms of work takes 50 ms either way, and it can even be a few microseconds slower from the extra scheduling.
What changes is how many requests one worker can hold in flight. A
defendpoint occupies one of 40 thread tokens for its whole 50 ms. Anasync defendpoint that awaits occupies only a small object while waiting, so thousands can overlap.The arithmetic: with 40 tokens and 50 ms each, a worker tops out near 40 / 0.05 = 800 requests per second of pure waiting work. The async version has no such token ceiling. It is limited by CPU, the database pool and the downstream services.
That is the honest sales pitch for async: higher ceiling under concurrent waiting, same latency per request. If load never reaches the ceiling, async gives you nothing except new ways to block the loop by mistake.
Q4 · Scenario. "p99 went from 40 ms to 2 s under load after someone added requests.get inside an async endpoint. Diagnose and fix."
Reveal answer
The real test Whether you connect "p99 explodes while CPU stays low" to a blocked event loop and offer more than one fix, with the trade-off of each.
Strong answer requests.get is blocking: it holds the one thread that runs the event loop until the HTTP call returns. While it waits, no other request on that worker makes progress, not even /healthz. Latency grows with queue depth, not with the work itself, which is why p99 jumps first.
How I confirm it. CPU is low (the loop is sleeping inside a socket call, not computing). Latency of unrelated endpoints rises at the same time. Turning on asyncio debug mode logs "Executing ... took 0.9 seconds" for any callback that blocks the loop for more than 100 ms.
Three fixes, in order of preference. One: replace requests with httpx.AsyncClient (a shared one from lifespan, Q46) and await it. Two: make the endpoint plain def so it runs in the threadpool. Three: keep it async and wrap the single blocking call in await run_in_threadpool(...) (or asyncio.to_thread).
I also add an outbound timeout, since one slow partner can now hold a thread or a loop slot for a long time (Q98).
Picture it The same 100 ms blocking call, 20 requests at once, three ways. This is a different workload from the primer's 50-request run, so the totals differ, but the shape is the same.
The setup: Three endpoints call the same slow_call() which sleeps 100 ms (standing in for requests.get).
import asyncio, time, httpx
from fastapi import FastAPI
from starlette.concurrency import run_in_threadpool
app = FastAPI()
def slow_call(): # stands in for requests.get(...): blocks 100 ms
time.sleep(0.1)
@app.get("/bad")
async def bad():
slow_call(); return {} # ❌ TRAP: blocks the event loop
@app.get("/fix-def")
def fix_def():
slow_call(); return {} # ✅ plain def: runs in the threadpool
@app.get("/fix-offload")
async def fix_offload():
await run_in_threadpool(slow_call); return {} # ✅ one blocking call offloaded
async def hit(c, path, t0):
await c.get(path); return time.perf_counter() - t0 # latency measured from the common start
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for p in ("/bad", "/fix-def", "/fix-offload"):
t = time.perf_counter()
lat = await asyncio.gather(*[hit(c, p, t) for _ in range(20)])
print(f"{p:13} 20 requests: fastest {min(lat):5.2f}s slowest {max(lat):5.2f}s")
asyncio.run(main())Make the invisible visible: Run it.
/bad 20 requests: fastest 0.10s slowest 2.02s
/fix-def 20 requests: fastest 0.12s slowest 0.12s
/fix-offload 20 requests: fastest 0.14s slowest 0.14sWhat you see: In the first row the fastest request needs 0.10 s but the slowest waits 2.02 s: 20 requests × 0.1 s lined up on one thread. In the other rows all 20 finish together, around 0.12 s.
Why: Sequential blocking gives latency ≈ position in queue × work time. At p99 you are always the person at the back of the queue.
Naive
Blocking call inside async def.
@app.get("/rate")
async def rate():
r = requests.get(URL) # ❌ blocks loop
return r.json()Fixed
Shared async client, awaited.
@app.get("/rate")
async def rate(c: Client = Depends(client)):
r = await c.get(URL, timeout=2) # ✅
return r.json()The shift: One awaited call lets the loop serve everyone else while this request waits.
Land it I find the blocked loop by its signature (low CPU, high latency everywhere), then make the call truly async or move it to a thread, and add a timeout.
- "How would I find the blocking call if I did not know which one it was?"
-
I would make the blocked loop confess. There are three tools, from development to production.
- Debug mode: run with
PYTHONASYNCIODEBUG=1, orasyncio.run(main(), debug=True). Asyncio then logs any callback that held the loop longer than 100 ms, with the coroutine name. - A sampler: in production I run py-spy
dumpon the stuck process. If the main thread sits insocket.recvortime.sleepunder anasync def, that frame is the culprit. - A lag metric: a background task that awaits
sleep(0.1)in a loop and records how late it wakes.
If it wakes 0.9 s late, something held the loop for 0.9 s. I alert on that number, so the next blocking call is found by a graph, not by a customer.
- Debug mode: run with
- "Why not just add more workers?"
-
More workers multiply the number of event loops, so the symptom shrinks, but the bug stays. With four workers, four slow calls at once freeze everything again, just at a higher load.
It also has real costs. Each worker is a full copy of the app in memory, often 60 to 150 MB, and each one has its own database pool, so connections multiply (Q6). Worse, the extra capacity hides the cause. The next traffic spike or slower partner brings the same incident back, and nobody remembers why.
A rough check of the scale of the problem: if each blocked call holds a loop for 0.9 s, one worker serves about 1 request per second. Four workers serve about 4. Fixing the call serves hundreds.
So the order is: fix the blocking call first, add the timeout, and only then size workers for the CPU you actually need (Q6). Workers are for using more cores, not for covering up a frozen loop.
- "Is
asyncio.to_threadthe same asrun_in_threadpool?" -
They are close, but they draw from different pools.
asyncio.to_threaduses asyncio's own default executor, which allows aboutmin(32, cpu_count + 4)threads. On the course machine that is 16.Starlette's
run_in_threadpooluses the AnyIO limiter, the same 40 tokens that plaindefendpoints and sync dependencies use. So there is one budget for "threads serving requests".The difference becomes real under load. Suppose 40
defrequests are running and oneasync defendpoint callsasyncio.to_thread. It still gets a thread from the other pool, so the total number of live threads can reach 56. Withrun_in_threadpoolit would wait for one of the 40 tokens, which is the honest queue.Inside FastAPI I prefer
run_in_threadpool, so one limit controls the thread count and one place to tune it. Outside a web app,asyncio.to_threadis the natural choice. - "What if the library only exists in sync form, like a vendor SDK?"
-
Then I wrap it in one place, behind an adapter. The SDK is blocking, so its calls must never appear directly in an
async defendpoint.The adapter is a small class with an
async defmethod that callsrun_in_threadpool(sdk.call, ...), wrapped inasyncio.timeout(...)so a hung vendor cannot hold a request forever. Callers see an async method and never learn the SDK is blocking.One caution about timeouts: cancelling the await does not stop the thread. The vendor call keeps running in its thread until it returns, still holding a token. So a slow vendor can slowly eat all 40 tokens even if every caller gave up.
If the SDK is heavy or called often, I give it a dedicated
ThreadPoolExecutorwith a small size, say 8, throughloop.run_in_executor. Then the worst a vendor outage can do is fill its own 8 threads, and the rest of the API keeps its 40.
Q5. "Uvicorn, Gunicorn with Uvicorn workers, or Granian — how do you run FastAPI in production?"
Reveal answer
Strong answer My default is plain uvicorn with --workers N, or one uvicorn process per container with the orchestrator providing the replicas. Modern uvicorn supervises its own worker processes and restarts those that die, which removes most of the old reason to put Gunicorn in front.
Gunicorn is a process manager with years of hardening: graceful reload, max-requests recycling, many signal hooks. It used uvicorn.workers.UvicornWorker; on this machine that class now emits a DeprecationWarning pointing to the separate uvicorn-worker package, so a new project should either use uvicorn's own --workers or install that package deliberately.
Granian is a Rust-based server supporting ASGI and RSGI, often faster in synthetic benchmarks. I would pick it after measuring on my own app, and only if the team is comfortable with a newer, less battle-tested piece. Hypercorn is the choice if I need HTTP/2 or HTTP/3 from the app server itself.
In Kubernetes I run one or two workers per pod and scale pods (Q6). Behind a load balancer or ingress I add --proxy-headers so client IPs and schemes come from X-Forwarded-*, and --timeout-graceful-shutdown so deploys drain (Q141).
Picture it The flags I actually use, confirmed against this machine's uvicorn before quoting them.
The setup: A script runs uvicorn --help and prints the line for each flag.
import subprocess, sys
help_text = subprocess.run([sys.executable, "-m", "uvicorn", "--help"], capture_output=True, text=True).stdout
for flag in ("--workers", "--factory", "--timeout-graceful-shutdown", "--proxy-headers", "--limit-concurrency", "--timeout-keep-alive"):
for line in help_text.splitlines():
if line.strip().startswith(flag):
print(line.strip()[:78]); break
else:
print(flag, "NOT FOUND")Make the invisible visible: Output.
--workers INTEGER Number of worker processes. Defaults to the
--factory Treat APP as an application factory, i.e. a
--timeout-graceful-shutdown INTEGER
--proxy-headers / --no-proxy-headers
--limit-concurrency INTEGER Maximum number of concurrent connections or
--timeout-keep-alive INTEGER Close Keep-Alive connections if no new dataWhat you see: All six flags exist in uvicorn 0.53. --factory lets me start app.main:create_app without a module-level app object, which keeps tests and settings clean.
Why: Quoting flags from memory is how deployments get a typo that only shows at 2 a.m. Printing them is five seconds.
Spring Boot
One embedded server, threads managed inside.
# illustrative
java -jar quickbite.jar \
--server.tomcat.threads.max=200FastAPI
A server process you configure on the command line.
uvicorn app.main:create_app --factory \
--host 0.0.0.0 --port 8000 --workers 2 \
--proxy-headers --timeout-graceful-shutdown 25The shift: In Spring the server is a library inside your JAR; in Python it is a separate program that imports your app.
Land it I run uvicorn with a small worker count per container, behind a proxy with proxy headers and graceful shutdown on, and I reach for Gunicorn or Granian only for a measured reason.
- "When is Gunicorn still worth it?"
-
When I need its process-management features, and only then. The main three are recycling workers after a number of requests to contain a slow memory leak (
--max-requestswith--max-requests-jitter), a graceful reload on SIGHUP, and the fact that a team already runs it everywhere with known dashboards.The jitter matters. Without it, all workers recycle at the same moment and capacity drops together. With a jitter of, say, 100 on a base of 1,000, each worker restarts at a slightly different request count.
Recycling is a bandage. A leak that needs recycling every 50,000 requests should still be found and fixed. I treat
--max-requestsas a safety net while the real fix is in progress.If I do use Gunicorn, I use the maintained
uvicorn-workerpackage, not the deprecateduvicorn.workers.UvicornWorkerclass. For a new project in containers, I start with plain uvicorn and add Gunicorn only for a named reason. - "Why not use
--reloadin production?" -
Because it is a development tool, and every part of what it does is wrong for production.
--reloadstarts a watcher process that restarts the server whenever a file changes.The costs show up in three places. It adds an extra process and file-system watching, which costs CPU in some setups. A half-written file, or a changed file you did not mean to deploy, can restart or crash the server mid-traffic. And it reloads only one process, so it conflicts with
--workers.The deeper reason is how production works. The container image is immutable: the code is whatever was built. A change reaches production by rolling out a new image, where the old pods drain and new pods start, not by editing files in a running container.
I keep
--reloadin a development compose file only. A quick safeguard is that the production Dockerfile's command never contains it, and a CI check greps for it. - "Does the number of workers equal the number of requests I can serve at once?"
-
No. The number of workers is the number of event loops, not the number of requests you can serve. One loop can have thousands of requests in flight if they are all waiting on I/O.
The real limit is what the requests do. If they are CPU-bound or call blocking code, a worker serves them one at a time. Four workers then means four at a time, and the rest queue in the socket backlog.
Because waiting is cheap and queueing is invisible, I want a safety valve.
--limit-concurrency Nmakes uvicorn answer 503 once N connections are open in a worker. A fast 503 that the load balancer can retry on another pod is better than a request that waits 30 s and times out.I pick N from load tests, not from a formula. I raise load until p99 doubles, note the concurrency there, and set the limit somewhat above it. Pair it with a
Retry-After-aware client and a health check that reflects the overload. - "How do uvicorn workers share a port?"
-
The parent process opens the listening socket once, then each worker process inherits it. All workers wait on the same socket.
When a new connection arrives, the operating system kernel wakes one of the waiting workers, and that worker accepts it. There is no application-level balancing, no round-robin written in Python. The spread comes from whichever worker happens to be idle and asking first.
Two consequences matter. First, a connection stays with its worker for its whole life. A WebSocket or a keep-alive HTTP connection from one client pins one worker, so a few very long connections can make the load uneven. Second, busy workers accept fewer connections only indirectly, since a busy worker is simply slower to pick up the next one.
If even spread matters, I put a proper load balancer in front and run workers per pod, so balancing happens per request across pods, not per connection inside one machine. I also cap connection lifetime where clients allow it.
Q6. "How many workers should you run, and how does that interact with the database pool?"
Reveal answer
Strong answer For an I/O-bound API, start with workers ≈ CPU cores available to the container, then measure. One worker is one process, so one event loop and (for Python code) one core. Two workers use two cores. More workers than cores only adds memory and context switching.
Each worker has its own SQLAlchemy engine and therefore its own connection pool. So the database sees workers × pods × (pool_size + max_overflow) connections. This multiplication is the thing people forget, and it is how a service that was fine on one VM exhausts PostgreSQL after scaling out (Q143).
In Kubernetes I give each pod a small CPU limit (1 or 2 cores), run 1 or 2 workers per pod, and scale by adding pods. That keeps the failure unit small and makes the pool arithmetic simple.
I start by choosing the database budget (for example 60 of PostgreSQL's 100 connections for this service), divide it by the number of worker processes, and set the pool from the result, not the other way round.
Picture it The formula, tried on five realistic configurations, with the PostgreSQL default of 100 connections as the ceiling.
The setup: workers × pods × (pool_size + max_overflow) against max_connections = 100 (about 97 usable).
# total database connections = workers x pods x (pool_size + max_overflow)
def total(workers, pods, pool_size, overflow):
return workers * pods * (pool_size + overflow)
print("PostgreSQL default max_connections = 100 (about 3 reserved for superusers)")
for workers, pods, ps, ov in [(1, 1, 5, 10), (4, 3, 5, 10), (4, 20, 5, 10), (4, 20, 2, 0), (2, 20, 3, 2)]:
t = total(workers, pods, ps, ov)
print(f"workers={workers} pods={pods:2} pool={ps}+{ov:2} -> {t:4} connections {'OVER 97' if t > 97 else 'ok'}")Make the invisible visible: Run it.
PostgreSQL default max_connections = 100 (about 3 reserved for superusers)
workers=1 pods= 1 pool=5+10 -> 15 connections ok
workers=4 pods= 3 pool=5+10 -> 180 connections OVER 97
workers=4 pods=20 pool=5+10 -> 1200 connections OVER 97
workers=4 pods=20 pool=2+ 0 -> 160 connections OVER 97
workers=2 pods=20 pool=3+ 2 -> 200 connections OVER 97What you see: One worker with the SQLAlchemy defaults (5+10) is fine. Four workers on three pods with those same defaults is already 180. Even a deliberately small 2+0 pool on 4 workers × 20 pods asks for 160.
Why: The pool setting that is safe on one process is dangerous at fleet scale. Either lower the per-worker pool, put PgBouncer (a connection pooler) in front, or scale pods less aggressively.
Naive
Defaults copied to every worker.
engine = create_engine(url)
# pool_size=5, max_overflow=10 per process
# 4 workers x 20 pods = 1200 possible connsBudgeted
Pool derived from a budget.
BUDGET, PROCS = 60, 4 * 20
per = max(1, BUDGET // PROCS) # = 1
engine = create_engine(url, pool_size=per,
max_overflow=0)The shift: Size the pool from the database's capacity divided by processes, not from a framework default.
Land it I size workers to cores, then split the database's connection budget across every worker process in the fleet.
- "What if the arithmetic says each worker gets one connection?"
-
It means the database cannot support this many processes directly, so you change the shape instead of squeezing the pool to one. Say the budget is 60 connections and you run 20 pods with 3 workers each: 60 processes, one connection each, and any request that needs two (a transaction plus a lock check) will queue.
There are three real options.
- PgBouncer in transaction mode: many app connections share a few server connections. Session features such as advisory locks,
SETand some prepared-statement setups need care. - Fewer, bigger pods: 5 pods with 3 workers is 15 processes and 4 connections each.
- A read replica: read-heavy endpoints use a second budget.
I would not just raise
max_connections. Each PostgreSQL connection is a server process using several MB, and more connections usually make the server slower, not faster. - PgBouncer in transaction mode: many app connections share a few server connections. Session features such as advisory locks,
- "Do async endpoints need as many connections as sync ones?"
-
Often fewer, but they behave differently. A
defendpoint holds its connection for the whole life of its thread, and up to 40 threads can be in flight per worker. Anasyncendpoint holds a connection only while it awaits a query, so 5 or 10 connections can serve a lot of requests.The catch is the other side of the same coin. Async can have thousands of requests in flight, so thousands may want a connection at the same moment. The pool becomes the queue, and a request that cannot get a connection waits.
That wait must be short. SQLAlchemy's
pool_timeoutdefaults to 30 seconds, which turns overload into a 30-second hang that users see as a frozen app. I set it to a second or two, so overload becomes a quick 503 that the client or load balancer can retry (Q61).In the course app, the measured pool timeout is 1.00 s for this reason. A fast failure is a feature.
- "Why not one big process with many threads, like Tomcat?"
-
Because of the GIL: threads in one process share one core for Python code. Tomcat's 200 threads can run on 8 cores at once, because Java threads run in parallel. Python threads only overlap their waiting.
Take a CPU-bound endpoint that needs 100 ms of computing. One Python process, however many threads, finishes about 10 per second. Eight processes finish about 80 per second. That is the whole reason workers exist in Python: processes are how you use many cores.
Free-threaded Python (the 3.14t build) removes the GIL, so threads could run in parallel. But many C extensions in an API stack were not yet checked for it, and single-thread code can be slower. In E19 the measured overhead was about 23% on one workload.
So for production today I would still use processes and treat free-threading as something to test, not rely on, and revisit once my dependencies declare support.
- "How does memory change with workers?"
-
Each worker imports the whole application and keeps its own copy of everything: modules, Pydantic models, caches, connection buffers. A small FastAPI app often uses 60 to 150 MB per worker, so four workers cost roughly four times that.
An example: 4 workers at 100 MB is 400 MB per pod. With 10 pods that is 4 GB just for idle copies. If a memory limit is 512 MB per pod, one leak or one large response can push a worker over and the container gets killed.
There is a sharing trick. If the app is loaded before the process forks (Gunicorn's
--preload), workers share the same memory pages copy-on-write. But Python's reference counting writes to objects even when you only read them, so the pages are slowly copied anyway. The saving is real at first and fades.My habit is to measure resident memory per worker under load, then set the container limit about 30% above the peak, and prefer one or two workers per pod.
Q7. "What is Starlette, and what does FastAPI add on top of it?"
Reveal answer
Strong answer Starlette is a small ASGI toolkit: routing, requests and responses, middleware, static files, WebSockets, background tasks, the lifespan protocol and a test client. It does not know what a "typed parameter" or an "OpenAPI schema" is.
FastAPI is a subclass of Starlette (class FastAPI(Starlette)) that adds four things. One: it reads your function signature and builds the parameter parsing from type hints. Two: it validates and serialises with Pydantic. Three: it has the Depends dependency system. Four: it generates OpenAPI and serves /docs.
So the runtime engine (middleware, routing, ASGI plumbing) is Starlette, and the developer experience (typed parameters, 422 errors, docs) is FastAPI. This course machine runs Starlette 1.6.0 under FastAPI 0.141.1.
Practical consequence: Starlette's Request, Response, StreamingResponse, BackgroundTasks and middleware classes are imported in FastAPI code, and Starlette release notes can change FastAPI behaviour.
Picture it The same route in raw Starlette and in FastAPI, called with a bad query value.
The setup: GET /hello?n=abc. Starlette parses nothing; FastAPI was told n: int.
import fastapi, starlette
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route
import asyncio, httpx
print("FastAPI subclasses Starlette:", issubclass(fastapi.FastAPI, Starlette))
print("versions: fastapi", fastapi.__version__, "starlette", starlette.__version__)
async def hello(request): # raw Starlette: you parse everything yourself
return PlainTextResponse("hi " + request.query_params.get("n", "?"))
raw = Starlette(routes=[Route("/hello", hello)])
app = fastapi.FastAPI()
@app.get("/hello")
def hello2(n: int): # FastAPI: n is parsed, validated, documented
return {"n": n}
async def main():
for name, a, url in (("starlette", raw, "/hello?n=abc"), ("fastapi", app, "/hello?n=abc")):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=a), base_url="http://t") as c:
r = await c.get(url); print(name, r.status_code, r.text[:90])
print("fastapi adds /openapi.json:", "/hello" in app.openapi()["paths"], "| starlette has", [r.path for r in raw.routes])
asyncio.run(main())Make the invisible visible: Run it.
FastAPI subclasses Starlette: True
versions: fastapi 0.141.1 starlette 1.6.0
starlette 200 hi abc
fastapi 422 {"detail":[{"type":"int_parsing","loc":["query","n"],"msg":"Input should be a valid intege
fastapi adds /openapi.json: True | starlette has ['/hello']What you see: Starlette happily returned 200 with the string abc, because nobody asked it to check. FastAPI answered 422 with a structured error naming the location ["query","n"]. Only FastAPI has /openapi.json.
Why: Everything on that 422 body came from one annotation, n: int. That is the entire value proposition: the type hint is the validator, the documentation and the parser.
Starlette
You read and check everything.
async def hello(request):
n = request.query_params.get("n")
if not (n and n.isdigit()):
return JSONResponse({"error": "n"}, 400)
...FastAPI
The hint does it.
@app.get("/hello")
def hello(n: int):
...The shift: With Starlette you write the checks; with FastAPI you write the types and the framework writes the checks.
Land it I say FastAPI is Starlette plus typed parameters, Pydantic validation, dependency injection and generated OpenAPI.
- "When would I use plain Starlette?"
-
When the service is a thin layer where validation and OpenAPI add nothing. Good examples are a small gateway, a proxy, a WebSocket relay, or a tiny internal tool that passes bytes along.
Plain Starlette has fewer moving parts. There is no signature inspection, no Pydantic model building at start-up, and a smaller import tree, so start-up is faster and the surface to upgrade is smaller. That helps in a function-as-a-service setting where cold start counts.
The price is that you write the parsing yourself. You read
request.query_params, callawait request.json(), and check every field by hand. For two or three fields that is trivial. For forty it is the code FastAPI would have generated for you, with none of the documentation.My test is simple: if I catch myself writing schemas or checking types by hand, or a client team asks for an OpenAPI file, I am on the wrong framework and should move to FastAPI.
- "Can I mount a Starlette app inside FastAPI?"
-
Yes.
app.mount("/legacy", other_asgi_app)works for any ASGI app, whether it is Starlette, another FastAPI app or an adapter around Flask. A request to/legacy/anythingis handed to that app with the path prefix removed.Mounted apps are opaque to the parent. They do not appear in the parent's OpenAPI document, they do not share dependencies or exception handlers, and their middleware is their own. A mounted FastAPI sub-app even has its own
/docs.That separation is useful. I mount three kinds of things: a Flask app through an adapter during a migration, a
StaticFilesdirectory for assets, and a separately versioned sub-API such as/v2so it can have its own docs and error format (Q35).One thing to remember: because the parent's lifespan does not automatically run the child's startup in every version, I check that resources used by a mounted app are created where it expects them.
- "Does FastAPI's speed come from Starlette?"
-
Partly, but less than people say. Starlette is lean, uvicorn with uvloop is fast, and Pydantic v2's Rust core validates quickly. Together they make the framework overhead small, often well under a millisecond per request.
In a real endpoint that overhead is not what you wait for. A typical request spends 1 to 5 ms on a database round trip and maybe a few more on JSON of a few hundred bytes. If the framework costs 0.2 ms of a 15 ms request, even making it twice as fast saves under 1%.
The headline claim that FastAPI is as fast as Node comes from hello-world benchmarks, where the endpoint does nothing and the framework is the entire cost. Such a test is real, but it measures the wrong thing for most services.
So when someone asks me about speed, I turn to the things I control: the number of queries, the size of the response, and whether the loop ever blocks. Those move p99 by orders of magnitude more than the framework choice does.
- "Which Starlette pieces do I touch most?"
-
A short list covers almost all of it. The ones I touch daily are below.
- Request: headers, client address, raw body, and
request.statefor per-request values such as a request id. - Response classes:
StreamingResponse,FileResponseandRedirectResponsefor things that are not plain JSON. - Plumbing:
BackgroundTasks,CORSMiddleware,TestClient, andapp.statefor objects created in the lifespan (Q45).
All of these are either re-exported by
fastapior used by it directly, so most imports can come fromfastapiitself. The ones that are not re-exported I import fromstarletteexplicitly, such as the middleware classes.The practical lesson is to read the Starlette docs for these pieces. FastAPI's own docs cover its additions, but the behaviour of a streaming response or a middleware lives in Starlette, and a Starlette release can change it.
- Request: headers, client address, raw body, and
Q8. "How does middleware ordering work — the onion?"
Reveal answer
Strong answer Middleware wraps the app like layers of an onion. A request travels inward through the layers, reaches the route, and the response travels outward through the same layers in reverse.
The ordering rule that surprises people: the middleware added last is the outermost. With add_middleware(A) then add_middleware(B), a request meets B first, then A, then the endpoint; the response leaves via A, then B. Starlette inserts each new middleware at the front of the list.
So order encodes responsibility. The outermost layers should be the ones that must see everything: request-id assignment, timing, a catch-all for errors, then CORS (so even error responses get CORS headers), then authentication, then the rest.
Two kinds exist. @app.middleware("http") and BaseHTTPMiddleware are easy to write but add overhead and complicate streaming responses and background tasks. A pure ASGI middleware (a class with __call__(scope, receive, send)) is faster and exact; I use it for request ids and anything on every request.
Picture it Two middlewares, registered A then B, around one endpoint.
The setup: Each middleware prints "before" and "after".
import asyncio, httpx
from fastapi import FastAPI, Request
app = FastAPI()
def make(name):
async def mw(request: Request, call_next):
print(f" {name}: before"); r = await call_next(request); print(f" {name}: after"); return r
return mw
app.middleware("http")(make("A (added first)"))
app.middleware("http")(make("B (added second)"))
@app.get("/")
async def root():
print(" endpoint"); return {}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
await c.get("/")
asyncio.run(main())Make the invisible visible: Run it.
B (added second): before
A (added first): before
endpoint
A (added first): after
B (added second): afterWhat you see: B, registered second, ran first on the way in and last on the way out. A sat next to the endpoint.
Why: Think of each add_middleware as putting another coat on over the previous ones: the last coat is the one the rain hits first.
Spring Boot
Filter order is explicit.
// illustrative
@Component
@Order(1) // lower number = outermost
class LogFilter extends OncePerRequestFilter {
void doFilterInternal(...) {
chain.doFilter(rq, rs);
}
}FastAPI
Order is registration order, reversed.
app.add_middleware(Auth) # inner
app.add_middleware(CORS) # middle
app.add_middleware(RequestId) # outermostThe shift: Spring numbers its filters; Starlette's outer-to-inner order is the reverse of the order you add them.
Land it I treat middleware as an onion where the last one added is outermost, and I keep only cross-cutting, every-request concerns there.
- "Where does CORS go relative to authentication?"
-
Outside it. A failed authentication returns 401, and the browser must still see an
Access-Control-Allow-Originheader on that 401. If it does not, the browser hides the real response and reports a vague CORS error, and the front-end developer chases the wrong problem (Q88).Because the last middleware added is the outermost, CORS is added after authentication, which places it further out. A request meets CORS first, then auth, then the route. The response leaves through auth first, then CORS stamps its headers on whatever came out, including error responses.
A related trap is the preflight. The browser sends an
OPTIONSrequest with no credentials before the real call. If auth runs first, it rejects the preflight with 401 and the real call never happens. With CORS outside, it answers the preflight itself and never reaches auth.I test this with one request from an allowed origin carrying a bad token, and assert both the 401 and the CORS header.
- "Why is
BaseHTTPMiddlewarediscouraged for hot paths?" -
It runs the rest of the app in a separate task and copies messages between the two through in-memory streams. That is extra work on every request, and it changes how things behave around the edges.
The costs are three. There is time per request, small but real on a hot path. There is the streaming problem: the wrapper is built around a complete response object, which complicates streaming responses and background tasks. And in older versions, context variables set inside the middleware could fail to reach the endpoint, because the endpoint ran in a different task.
A pure ASGI middleware avoids all of it. It is a class with
__call__(scope, receive, send)that wrapssendto see or change the response start. There is no copying and no extra task.The price is writing the plumbing by hand. My rule:
BaseHTTPMiddlewarefor a rarely used internal tool, pure ASGI for anything on every request, like request ids and timing. - "Does middleware run for exceptions raised in the endpoint?"
-
Yes, with a detail that surprises people. How far the exception travels depends on who handles it.
Exceptions that FastAPI knows how to handle, such as
HTTPExceptionand validation errors, are turned into responses by exception handlers before they reach your middleware. So your middleware sees a normal 404 or 422 response and never sees a raised exception.Unhandled exceptions travel outward until they hit Starlette's
ServerErrorMiddleware, which sits at the very outside, logs a traceback and sends a plain 500. Your own middleware, being inside it, sees the exception pass through if it catches it, but a logging middleware that only readsresponse.status_codesees nothing.The practical consequence: if you want one place to log every failure with its cause, register an exception handler for
Exceptionthat logs and returns the Problem body. Middleware alone gives you the status code but not the reason, and I want both in the log. - "Should authentication be middleware or a dependency?"
-
A dependency, almost always. Middleware runs before routing, so it cannot know which route matched. It cannot tell a public route from a protected one, and whatever it decides is invisible to the OpenAPI document.
Compare what a dependency gives me. I attach it to a router or a single route, so only the routes that need protection get it. FastAPI's security classes, such as
HTTPBearer, add the padlock and the Authorize button to/docs. And in tests I replace it withapp.dependency_overridesin one line (Q50, Q84).A concrete scenario: with middleware auth you end up writing "skip if path is
/healthz, or/docs, or starts with/public". That list becomes a security bug the first time someone adds a path and forgets it.Middleware keeps its place for things with no per-route meaning: a request id, an access log, a size limit. The test is whether the rule needs to know the route. If yes, it is a dependency.
Q9 · Scenario. "A middleware that reads the request body makes the endpoint hang or fail. Why?"
Reveal answer
Strong answer The request body is not a value; it is a stream you pull from receive(). Each chunk can be read once. If middleware drains the stream and then calls the app with the same receive, the endpoint asks for the body and there is nothing left. It then waits for a message that never comes, so the request hangs until the client gives up.
Compare the Part A demo (middleware_body.py): there the middleware read only the first of the two messages httpx's test transport sends, so the endpoint got the empty closing message and returned 422 instead of hanging. How much was consumed decides whether you see a 422 or a hang; the cause is the same.
In older Starlette versions the same mistake also showed up with BaseHTTPMiddleware and await request.body(). Modern Starlette caches the body on the Request object for that wrapper, which hides the problem, but it still reads the whole body into memory before your code runs.
My fix order. First, do not read the body in middleware: validate size from the Content-Length header, or read the body in a dependency, where FastAPI already handles it once. Second, if I truly must (signature checks over raw bytes), read all chunks, then give the app a replacement receive that replays them.
Reading in middleware also defeats streaming: a 2 GB upload gets buffered in memory just so a middleware can look at it.
Picture it A pure ASGI middleware that drains the stream, and one that replays it, in front of the same echo endpoint.
The setup: POST /echo with a 10-byte body; the endpoint returns the number of bytes it saw. A 3-second timeout stands in for the client giving up.
import asyncio, httpx
from fastapi import FastAPI, Request
app = FastAPI()
class ReadBodyBad: # pure ASGI middleware that drains the stream
def __init__(self, app): self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] == "http":
body = b""
while True:
m = await receive(); body += m.get("body", b"")
if not m.get("more_body"): break
print("middleware read", len(body), "bytes, then called the app with the SAME receive")
await self.app(scope, receive, send) # ❌ TRAP: the endpoint's receive() has nothing left
class ReadBodyGood: # ✅ read, then replay the bytes
def __init__(self, app): self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http": return await self.app(scope, receive, send)
chunks = []
while True:
m = await receive(); chunks.append(m)
if not m.get("more_body"): break
replay = iter(chunks)
async def receive2():
return next(replay, {"type": "http.disconnect"})
await self.app(scope, receive2, send)
@app.post("/echo")
async def echo(request: Request):
return {"len": len(await request.body())}
async def call(a):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=a), base_url="http://t") as c:
try:
r = await asyncio.wait_for(c.post("/echo", content=b'{"qty": 2}'), 3)
print(" ->", r.status_code, r.text)
except Exception as e:
print(" ->", type(e).__name__, str(e)[:70])
async def main():
for name, mw in (("bad", ReadBodyBad), ("good", ReadBodyGood)):
a = FastAPI(); a.router.routes = app.router.routes.copy(); a.add_middleware(mw)
print(name); await call(a)
asyncio.run(main())Make the invisible visible: Run it.
bad
middleware read 10 bytes, then called the app with the SAME receive
-> TimeoutError
good
-> 200 {"len":10}What you see: The "bad" variant read 10 bytes and the endpoint never answered: TimeoutError after 3 seconds. The "good" variant returned {"len": 10}.
Why: The difference is two lines: collect the messages, then hand the app a receive that yields them again. Without that, the first reader consumes the only copy.
Naive
Read, then forward unchanged.
body = await drain(receive)
await self.app(scope, receive, send)
# ❌ TRAP: stream already used upCorrect
Replay or avoid.
msgs = await collect(receive)
await self.app(scope, replay(msgs), send)
# ✅ or check Content-Length onlyThe shift: A body is a stream you can pull once; either buffer-and-replay it or do not touch it.
Land it I never consume the body in middleware unless I replay it, and I prefer checking size headers or reading it in a dependency.
- "How do I limit request body size safely?"
-
I enforce it in two places, because either alone can be fooled.
- Early check: read
Content-Lengthand reject with 413 if it exceeds the limit. This costs nothing and stops honest oversized uploads before any bytes are read. - Streaming count: the header can be absent, as with chunked uploads, or simply wrong. A pure ASGI middleware that adds up the bytes seen in
receiveand aborts when a threshold is crossed handles that.
The count is cheap, because the middleware only adds integers as chunks pass and never stores them. A 2 GB upload costs a few kilobytes of memory and is cut off at, say, 10 MB.
The first wall is the reverse proxy: nginx's
client_max_body_sizerefuses large bodies before Python is involved (Q109). I set the app limit slightly above the proxy's limit, so the proxy is the one normally answering, and the app's check is the backstop if the app is reached directly. - Early check: read
- "How do I log request bodies for debugging without breaking things?"
-
I log a redacted copy of the parsed model from inside a dependency, never the raw body from middleware. By the time a dependency has the model, the body has been read once, validated, and I know which fields are safe.
The reasons against raw logging are practical. Raw bodies contain tokens, passwords and personal data, and once they are in a log aggregator they are copied, indexed and kept for months (Q97). The replay trick that makes middleware reading safe also holds a second copy of the body in memory, so a large upload doubles its cost.
My redaction is a small function: dump the model, replace values for keys named
password,token,cardand similar with a fixed mask,.If I truly need raw capture to reproduce a bug, I do it at the proxy with sampling, such as 1% of requests, and a short retention. It keeps the sensitive copy outside the app and outside normal logs.
- "What about verifying a webhook signature over the raw bytes?"
-
That is the one case where reading raw bytes is correct, because the signature is computed over the exact bytes the sender transmitted. If I parse the JSON and re-serialise it, key order and whitespace change and the signature no longer matches.
I write a dependency on that single route. It declares
request: Request, callsawait request.body()once, computes an HMAC with the shared secret, and compares it to the header usinghmac.compare_digest. That function compares in constant time, so an attacker cannot learn the signature byte by byte from timing.Only after the signature passes do I parse the JSON, from those same bytes, with
Model.model_validate_json(raw).Two extras make it robust. I check a timestamp in the signed payload and reject anything older than five minutes, which blocks replays. And I cap the body size first, since a webhook endpoint is public and the HMAC check happens only after the body is read. Because it is one route's dependency, no global middleware buffers anything.
- "Why did the hang not raise an error?"
-
Because from the ASGI point of view nothing is wrong. The app has called
await receive(), which is allowed to wait for as long as it likes, since a body could legitimately be slow. No exception is raised and nothing is logged.Only something outside ends it. That could be the client giving up and disconnecting, a timeout in the proxy, or a server timeout. A hung request therefore shows up as a long request, not as an error, which is why it is harder to diagnose than a crash.
The symptoms point to it. CPU is idle, memory flat, one endpoint's requests pile up, and the proxy reports 504s while the app logs nothing. In py-spy the coroutine sits waiting inside
receive.My defences are boring but effective: set read and idle timeouts at the proxy so the wait ends in a clear 504, set uvicorn's
--timeout-keep-alive, and add a test that sends a body through the full middleware stack, so the bug fails in CI, not in production.
Q10. "Spring Boot versus FastAPI request handling — threads versus the event loop."
Reveal answer
Strong answer Classic Spring MVC on Tomcat is thread-per-request: a pool (default 200 threads) takes each request and keeps that thread until the response is written, even while it waits on a database. Capacity is roughly "pool size ÷ average request time". Blocking code is normal and safe.
FastAPI is event loop plus a threadpool. The loop (one thread per worker process) handles many async def requests by switching whenever one awaits. Plain def endpoints go to a pool of 40 threads. Capacity depends on whether your code awaits or blocks.
Spring has changed too: with Java 21 virtual threads (spring.threads.virtual.enabled=true) each request gets a cheap virtual thread and blocking code scales much further. The mental model then looks closer to FastAPI's async: waiting is cheap, but with the old simple blocking code style.
The big difference is the failure mode. In Spring, a blocking call wastes one thread. In FastAPI async def, a blocking call freezes the loop for everyone on that worker. And Python cannot use more than one core per process for Python code, so scaling out means more processes.
Picture it Two thousand requests each waiting 0.5 s, held by one thread. This is the loop's superpower in numbers.
The setup: 2000 coroutines, each await asyncio.sleep(0.5); count OS threads before and during.
import asyncio, threading, time
# Spring-style: one thread per in-flight request. Event loop: one thread, many awaiting requests.
async def handler(i): await asyncio.sleep(0.5) # waiting costs a coroutine, not a thread
async def main():
before = threading.active_count()
t = time.perf_counter()
peak = 0
tasks = [asyncio.create_task(handler(i)) for i in range(2000)]
await asyncio.sleep(0.1); peak = threading.active_count()
await asyncio.gather(*tasks)
print(f"2000 requests waiting 0.5 s each finished in {time.perf_counter()-t:.2f}s")
print(f"threads before: {before}, threads while 2000 requests were in flight: {peak}")
asyncio.run(main())Make the invisible visible: Run it.
2000 requests waiting 0.5 s each finished in 0.51s
threads before: 1, threads while 2000 requests were in flight: 1What you see: 2000 concurrent waits finished in 0.51 s and the process still had exactly one thread. A thread-per-request server would need 2000 threads (about 2 GB of stack address space at 1 MB each, or a pool that queues most of them).
Why: Waiting costs a coroutine object (a few KB). The price is discipline: any call that does not yield makes everyone else wait.
Spring MVC · Tomcat
A thread per request, 200 by default.
// illustrative
@GetMapping("/orders/{id}")
Order get(@PathVariable long id) {
return repo.findById(id).orElseThrow();
} // thread blocked inside findById is fineFastAPI · uvicorn
One loop; awaits give the thread away.
@router.get("/orders/{order_id}")
async def get(order_id: int,
s: AsyncSession = Depends(sess)):
return await s.get(Order, order_id)The shift: Spring spends a thread to wait; FastAPI spends a coroutine, and so must never block the one thread it has.
Land it I explain it as capacity per thread versus capacity per loop: Spring pays threads for waiting, FastAPI pays discipline, and both scale out by adding processes.
- "Would Spring's virtual threads make FastAPI unnecessary?"
-
No. Virtual threads solve a Spring problem, not a Python one, so they change the comparison but do not decide it.
The real choice is driven by three things: the skills of the team, the ecosystem, and operations. A team that knows Java, has Spring security and monitoring in place, and builds a plain CRUD API will be happy with Spring plus virtual threads. It scales well and blocking code stays simple.
FastAPI wins where the service must live next to Python. If the endpoint calls a trained model, shares code with a data pipeline, or the team already writes Python daily, the cost of crossing languages is higher than any framework difference. Libraries for data, machine learning and scientific work are in Python, not Java.
A concrete test: write down what the service has to import. If the answer is mostly pandas, numpy or a model runtime, I choose FastAPI. If it is JDBC, Kafka clients and JVM libraries, I choose Spring. Concurrency model comes third.
- "Which handles CPU-heavy requests better?"
-
Neither does well in the default setup, but the JVM has a structural advantage here. Java threads run in parallel on all cores, so one JVM process can use a whole 8-core machine for CPU work.
A Python worker runs Python bytecode on one core at a time. Take a request that computes for 100 ms. One JVM with enough threads handles about 80 per second on 8 cores. One Python worker handles about 10, and 8 workers about 80 but with 8 copies of the app in memory.
So the Python answer is structural: move the heavy computing out of the request path. The endpoint submits a job to a process pool or a queue (Q148) and returns an id, or the work runs in a separate worker service. Libraries such as numpy also release the GIL inside their native code, so numeric work parallelises better than pure Python loops.
In Java the same endpoint can just use more threads. My honest note: for CPU-heavy APIs I rate Java ahead on simplicity.
- "What is the closest Spring equivalent to FastAPI's
async defstyle?" -
It is Spring WebFlux with Reactor. It is non-blocking from end to end, runs on a small number of event-loop threads, and has the same rule as FastAPI's
async def: a blocking call on an event-loop thread stalls other requests.The trap is therefore identical. In WebFlux you use a scheduler (
boundedElastic) to wrap blocking calls, much as FastAPI uses a threadpool. A JDBC call inside a reactive pipeline blocks the loop in the same wayrequests.getdoes in Python.The difference is how readable it is. Reactor builds pipelines from operators like
flatMapandzipWith, and the stack traces and debugging are famously hard. Python'sasyncandawaitread like ordinary sequential code.So when a Spring engineer asks "what is this like?", I answer: WebFlux's model with much friendlier syntax. And note that with virtual threads, many teams now skip WebFlux entirely, since blocking-style code scales.
- "How would I compare throughput fairly?"
-
I change one variable at a time and measure the thing that actually differs. The setup is the same hardware, the same database with the same data, the same payload, and a warm-up period so the JIT and caches have settled.
Then I compare p99 latency at several concurrency levels, not the average at one. At 10, 50, 200 and 1,000 concurrent clients, I record the p50 and p99 and the error rate (Q124). A framework that wins at 10 may lose at 1,000.
The scenario that separates the designs is a database call that takes 20 ms. At high concurrency, a thread-per-request server holds a thread for each of those 20 ms and hits its pool limit. An event loop holds almost nothing. Virtual threads close much of that gap.
Hello-world endpoints mostly measure the framework's own overhead, which is rarely your bottleneck. I distrust any comparison that does not include a realistic slow dependency, and I report the setup so someone else can repeat it.
These questions test whether you know FastAPI's parameter rules well enough to predict behaviour, and whether you can explain the response model as a runtime filter and not only as documentation.
Q11. "Path, query, header, cookie and body parameters — how does FastAPI decide which is which?"
Reveal answer
Strong answer FastAPI decides from three clues in the function signature, checked in this order. If the name appears inside {braces} in the route path, it is a path parameter. If the annotation is a Pydantic model (or the default is Body()), it is part of the JSON body. Otherwise a simple type (int, str, bool, float) becomes a query parameter.
Header, cookie and form values are never guessed: you mark them with Header(), Cookie() or Form(). A list needs Query() explicitly, because list[str] alone would be read as a body. Header names convert underscores to hyphens, so x_request_id reads X-Request-ID.
If there are two or more body parameters, FastAPI expects one JSON object keyed by parameter names ({"line": {...}, "note": "..."}), not a bare model. With exactly one body model, the JSON is the model itself. Body(embed=True) forces the keyed form.
The Annotated[T, Query(...)] style is the current recommended spelling; it keeps the default value separate from the metadata and works in both FastAPI and plain Python call sites.
Picture it One endpoint with every kind of parameter, and the OpenAPI document FastAPI generated from it.
The setup: POST /orders/{order_id} with a path id, a query limit and list, a header, a cookie, a model and an extra body scalar.
from typing import Annotated
from fastapi import FastAPI, Header, Cookie, Query, Path, Body
from pydantic import BaseModel
app = FastAPI()
class Line(BaseModel):
item_id: int
qty: int
@app.post("/orders/{order_id}")
def create(order_id: int, # in the path template -> path
limit: int = 10, # simple type, not in path -> query
tags: Annotated[list[str], Query()] = [], # list needs Query() to stay a query
x_request_id: Annotated[str | None, Header()] = None, # header (x_request_id -> x-request-id)
session: Annotated[str | None, Cookie()] = None, # cookie
line: Line = ..., # Pydantic model -> JSON body
note: Annotated[str, Body()] = ""): # extra scalar forced into the body
...
spec = app.openapi()
op = spec["paths"]["/orders/{order_id}"]["post"]
for p in op["parameters"]:
print(f'{p["in"]:7} {p["name"]}')
ref = op["requestBody"]["content"]["application/json"]["schema"]["$ref"].split("/")[-1]
print("body schema:", ref, "->", list(spec["components"]["schemas"][ref]["properties"]))Make the invisible visible: Run it.
path order_id
query limit
query tags
header x-request-id
cookie session
body schema: Body_create_orders__order_id__post -> ['line', 'note']What you see: order_id is path, limit and tags are query, the header and cookie were found by the markers, and because there were two body values the body schema is a combined object with keys line and note.
Why: The rule is mechanical, so you can predict the generated docs from the signature alone. Surprises (a list that shows up in the body) come from forgetting the marker.
Spring Boot
Annotation per source.
// illustrative
@PostMapping("/orders/{id}")
Order create(@PathVariable long id,
@RequestParam int limit,
@RequestHeader("X-Request-ID") String r,
@RequestBody OrderCreate body) { ... }FastAPI
Types and markers.
@router.post("/orders/{order_id}")
def create(order_id: int,
limit: int,
x_request_id: Annotated[str, Header()],
body: OrderCreate): ...The shift: Spring labels every parameter's source; FastAPI infers most of them from the path template and the type.
Land it I explain it as path if it is in the template, body if it is a model, query if it is a simple type, and anything else needs an explicit marker.
- "How do I validate a query parameter, say
limitbetween 1 and 100?" -
I put the rule inside the type with
Annotated[int, Query(ge=1, le=100)] = 20. A request outside the range gets a 422 before the endpoint runs, and the limits appear in the OpenAPI schema asminimumandmaximum, so generated clients know them too.The default stays after the
=, solimitis optional and falls back to 20. The names are short:gemeans greater than or equal,leless than or equal,gtandltare the strict versions.This is the guard that stops
?limit=1000000from becoming a full table scan and a 200 MB response. An unbounded list parameter is one of the cheapest ways for a client to hurt a service, so every list endpoint I write has an upper bound (Q38).I also pick the bound from the cost, not from taste. If one row serialises to about 1 KB and I never want a response above 100 KB, the limit is 100. The number goes in the contract, so clients plan their paging around it.
- "What happens when a required parameter is missing?"
-
FastAPI answers 422 and never calls the endpoint. The body says exactly which value was missing and where it was expected, so the client can fix it without reading your code.
I ran a route with a required query parameter and a required header on FastAPI 0.141.1. Each missing value became one error, with a type and a location.
q11_missing.py · FastAPI 0.141.1runs offlinemissing ['query', 'limit'] missing ['header', 'x-request-id'] less_than_equal ['query', 'limit'] {'le': 100}The first two lines come from a request with nothing supplied. The third is
?limit=1000againstle=100, and thectxshows the limit that was broken. Note the header's location is lower-case with a hyphen.To make a value optional I give it a default or use
| None = None. Otherwise the parameter is required, and I let that be the documentation: no default means the client must send it. - "Can I read the raw request when I need something unusual?"
-
Yes. Declare
request: Requestas a parameter, and FastAPI passes you the Starlette request object. From it you can read raw headers, the client address, cookies, the unparsed body withawait request.body(), andrequest.state.I use it for a few specific jobs. One is a raw-body signature check on a webhook, where I need the exact bytes. Another is reading something set by middleware, such as a request id. A third is building absolute URLs with
request.url_for.I keep it rare because of what you lose. A parameter declared in the signature is validated, converted, shown in the OpenAPI document and visible to a generated client. A value pulled out of
requestby hand is none of those. The route's documentation says nothing about it, and a typo in a header name is a silentNone.My habit is to declare everything the client controls in the signature, and use
Requestonly for what the framework or middleware controls. - "Why do boolean query parameters accept
yes,1andtrue?" -
Because Pydantic's default lax mode converts a set of common strings and numbers to
bool. The accepted values includetrue,1,yes,onandtfor true, and their opposites for false, in any case.That is convenient for query strings, since everything there arrives as text and clients write flags in many styles. It also means a typo such as
?active=tureis rejected with a 422, which is a reasonable outcome.If the API needs strictness, I narrow it. One way is
Literal["true", "false"]and a conversion, which makes the contract say exactly what is accepted. Another is validating withStrictBool, though a query value always arrives as a string, so a strict bool would reject every request. For query flags, theLiteralis the useful one.Q22 shows lax and strict side by side with real output. My habit is to document accepted spellings in the field description, so clients do not guess.
Q12 · Scenario. "You have /orders/{order_id} and /orders/latest, and one of them never matches. Why?"
Reveal answer
Strong answer Starlette matches routes in registration order and takes the first path pattern that fits. /orders/{order_id} fits the text latest, so if it was registered first it claims the request, and /orders/latest is never reached.
What you see depends on the type of order_id. With order_id: int, the first route matches the path, then validation fails on "latest" and the client gets 422. With order_id: str, the wrong handler silently runs and returns an order lookup for the id "latest".
The fix is to register the specific route before the generic one. A rule I follow: literals first, then parameters, and I add a test that calls the literal paths. Another fix is a different URL shape such as /orders:latest or /me/orders/latest, which cannot be confused with an id.
A third fix is a Starlette path converter, /orders/{order_id:int}, which only matches digits (see the last follow-up).
Picture it Four combinations: int or str id, and which route is registered first.
The setup: The same two handlers, rebuilt four ways, each asked for /orders/latest.
import asyncio, httpx
from fastapi import FastAPI
async def hit(app, path):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
r = await c.get(path); return r.status_code, r.json()
def build(id_type, latest_first):
app = FastAPI()
def by_id(order_id): return {"handler": "by_id", "order_id": order_id}
def latest(): return {"handler": "latest"}
by_id.__annotations__["order_id"] = id_type
routes = [("/orders/latest", latest), ("/orders/{order_id}", by_id)]
for path, fn in (routes if latest_first else routes[::-1]):
app.get(path)(fn)
return app
async def main():
for id_type in (int, str):
for first in (False, True):
name = f"order_id: {id_type.__name__:3} latest registered {'FIRST' if first else 'second'}"
code, body = await hit(build(id_type, first), "/orders/latest")
print(f"{name} -> {code} {str(body)[:60]}")
asyncio.run(main())Make the invisible visible: Run it.
order_id: int latest registered second -> 422 {'detail': [{'type': 'int_parsing', 'loc': ['path', 'order_i
order_id: int latest registered FIRST -> 200 {'handler': 'latest'}
order_id: str latest registered second -> 200 {'handler': 'by_id', 'order_id': 'latest'}
order_id: str latest registered FIRST -> 200 {'handler': 'latest'}What you see: With an int id and the wrong order the answer is 422; with a str id it is 200 from by_id with order_id: 'latest'. Registering latest first fixes both.
Why: The 422 is the better failure because it is loud. The silent str case is the dangerous one: a fake "order" lookup that may return a 404 or, worse, data.
Naive
Generic route first.
@router.get("/{order_id}")
def get(order_id: str): ...
@router.get("/latest") # ❌ never reached
def latest(): ...Correct
Specific first, typed id.
@router.get("/latest") # ✅ literal first
def latest(): ...
@router.get("/{order_id}")
def get(order_id: int): ...The shift: Routes are an ordered list, not a lookup table: the first pattern that fits wins.
Land it I register literal paths before parameter paths, type the id as int, and keep a test that calls the literal route.
- "Does Spring have the same problem?"
-
No, and the difference is worth knowing. Spring's
PathPatternmatching ranks the patterns that fit by how specific they are, so the literal/orders/latestbeats/orders/{id}no matter which one was declared first.FastAPI follows Starlette's simpler rule: go through the routes in registration order and use the first one whose path pattern fits. Specificity plays no part.
Each rule has a cost. Spring's ranking removes a class of bug, but a reader must know the ranking rules to predict which handler wins when two patterns overlap in a less obvious way, such as a wildcard against a regex pattern. Starlette's rule is easy to explain in one line, and you can see the whole order by reading the file from top to bottom.
That is also why FastAPI teams need a habit and a test. I write literal routes first, and I have one test that requests every literal path and asserts which handler answered. The framework will not protect me, but the test does.
- "How would I catch this in review or CI?"
-
I would add a check that makes the mistake impossible to merge. There are two cheap ways.
- A handler test: request each literal path (
/orders/latest) and assert the right handler ran, for instance by checking a field only that response contains. - A start-up assertion: loop over
app.routesin order, and fail if a literal path appears after a parameter pattern that would match it. - Review smell: in the OpenAPI document, a generic path listed above a literal one is the warning sign.
The second check is about ten lines. It compares each pair of paths, replacing
{name}segments with a wildcard match.I like the test best because it documents intent. A future reader sees
test_latest_not_shadowedand understands why the order in the file matters. Without it, someone alphabetises the routes during a tidy-up and the bug returns. - A handler test: request each literal path (
- "Why not use a path converter like
{order_id:int}?" -
You can, and for integer ids it is good practice. Starlette converters such as
:int,:uuidand:pathwork in FastAPI path strings, and a route whose converter does not fit simply lets matching fall through to the next route. I ran it with the generic route registered first, which would normally shadowlatest.q12b_converter.py · Python 3.12 · FastAPI 0.141.1runs offline/orders/latest 200 {'handler': 'latest'} /orders/42 200 {'handler': 'by_id', 'order_id': 42} openapi path key: ['/orders/{order_id}', '/orders/latest']The converter made
/orders/latestfall through, and the OpenAPI key was cleaned back to/orders/{order_id}.I still keep literals first. The converter only protects the cases it can recognise: a
strid or a UUID string still matches the wordlatest. Ordering protects every case, so I use both and do not treat the converter as the fix. - "What about trailing slashes?"
-
They are different paths.
/ordersand/orders/do not match each other, so by default Starlette answers one with a 307 redirect to the other. That costs the client an extra round trip.The redirect is where production surprises hide. Behind a proxy that terminates TLS, the app sees plain HTTP. The redirect's
Locationcan then sayhttp://api.example.com/orders/instead ofhttps://. A browser calling from an HTTPS page blocks that as mixed content, and an API client may drop the Authorization header when it follows a redirect to another scheme.The fix is to run uvicorn with
--proxy-headersand a trusted proxy list (--forwarded-allow-ips), so the app knows the original scheme.More important is a policy. I choose one form, normally with no trailing slash, document it, and make sure the client libraries use it. A redirect for a POST also risks losing the body in some clients, so I do not rely on redirects for writes.
Q13. "How are status codes, response_model and extra responses documented in OpenAPI?"
Reveal answer
Strong answer Three decorator arguments feed the generated document. status_code=201 sets the default success code. response_model=OrderOut supplies the schema for that success response and also acts at runtime (Q16). responses={404: {...}} adds extra documented responses, each with a description and optionally a model.
FastAPI always adds a 422 entry with the standard validation-error schema when the route has parameters. It does not add 401, 404 or 409 for you: raising HTTPException(404) works at runtime but is invisible in the docs unless you list it in responses.
For an API contract, I define a Problem model (RFC 9457, Q94) and a shared dict COMMON = {401: ..., 403: ..., 404: ..., 409: ..., 429: ...} that routers pass as responses=COMMON. Generated clients then know every error shape.
summary, description, tags, operation_id and deprecated=True round out the documentation. The docstring of the function becomes the long description.
Picture it A route with a 200 model and two documented error models; we print the responses section of the spec.
The setup: GET /orders/{order_id} declares OrderOut, plus 404 and 409 with a Problem model.
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
class OrderOut(BaseModel):
id: int
class Problem(BaseModel):
title: str
status: int
app = FastAPI()
@app.get("/orders/{order_id}", response_model=OrderOut, status_code=status.HTTP_200_OK,
responses={404: {"model": Problem, "description": "No such order"},
409: {"model": Problem, "description": "Order already cancelled"}},
summary="Get one order")
def get_order(order_id: int):
raise HTTPException(404)
spec = app.openapi()
op = spec["paths"]["/orders/{order_id}"]["get"]
for code, r in op["responses"].items():
ref = r.get("content", {}).get("application/json", {}).get("schema", {}).get("$ref", "-")
print(code, "|", r["description"], "|", ref)
print("schemas:", sorted(spec["components"]["schemas"]))Make the invisible visible: Run it.
200 | Successful Response | #/components/schemas/OrderOut
404 | No such order | #/components/schemas/Problem
409 | Order already cancelled | #/components/schemas/Problem
422 | Validation Error | #/components/schemas/HTTPValidationError
schemas: ['HTTPValidationError', 'OrderOut', 'Problem', 'ValidationError']What you see: 200 uses the model; 404 and 409 point to Problem; 422 was added automatically with FastAPI's own error schema (HTTPValidationError).
Why: If you skip responses=, a generated client has no type for the error body, so every client author reads your source instead of your spec.
Spring · springdoc
Annotations document each code.
// illustrative
@ApiResponse(responseCode = "404",
content = @Content(schema =
@Schema(implementation = Problem.class)))
@GetMapping("/{id}") Order get(...) {...}FastAPI
A dict on the decorator.
@router.get("/{order_id}",
response_model=OrderOut,
responses={404: {"model": Problem}})
def get(order_id: int): ...The shift: Both document by declaration; neither checks that the code can really return what the documentation promises.
Land it I document every error the route can return through responses= with a shared Problem model, because the spec is the contract.
- "Does
responses=change runtime behaviour?" -
No. The
responses=argument changes the document only. It tells readers and generated clients what may come back, but it does not make any code run.Raising
HTTPException(404)still returns whatever body your exception handler produces. If the handler sends{"detail": "not found"}while the document promises aProblemshape, the contract is wrong and nothing warns you.That gap is why I test the contract. One parametrised test calls a route into each documented error state and validates the actual JSON against the declared model, for example
Problem.model_validate(response.json()). If a handler drifts, the test fails.I also keep one exception handler responsible for producing every
Problembody (Q94). Then the promise lives in one place and the sharedCOMMONdict of responses always refers to the same model.The rule I follow is simple: documentation that nothing checks will eventually lie, so I give each documented response a test that makes it tell the truth.
- "How do I document a response that is not JSON, like a CSV?"
-
I declare the media type in
responses=and return a realResponseorStreamingResponsewith that type. For a CSV it looks likeresponses={200: {"content": {"text/csv": {"schema": {"type": "string"}}}}}.Two things follow from returning a
Responseobject directly. FastAPI skipsresponse_modeland its serialisation entirely, so there is no filtering and no validation. And it skips the automatic documentation of the success schema, so the document and the runtime must be kept consistent by hand.For a download I also set
Content-Disposition: attachment; filename="orders.csv", so a browser saves it instead of displaying it.The trap is a mismatch between what is documented and what is sent. If the docs say
text/csvbut the handler returnsapplication/json, generated clients will try to parse the wrong thing. I write one test that asks for the route and checks theContent-Typeheader against the declared one. - "Where do success headers like
Locationget documented?" -
In the same
responsesentry, under aheaderskey. For a create, the entry looks like201: {"headers": {"Location": {"schema": {"type": "string"}}}}. A generated client then knows that aLocationheader is part of the answer.It is documentation only. The endpoint still has to set the header itself. The usual way is to take a
response: Responseparameter and writeresponse.headers["Location"] = f"/v1/orders/{order.id}", and FastAPI merges that into the final response (Q37).The same pattern fits other response headers that clients rely on:
Retry-Afteron 429,ETagon cacheable reads,Idempotent-Replayedon a replayed create. If a client is expected to read it, it belongs in the document, not only in the code.I like a small helper that returns the shared
responsesdict, so every create route documentsLocationthe same way. - "How do I stop
/docsshowing a huge noisy spec?" -
I shrink it by organising it, not by deleting content. A huge spec is usually a sign that nothing is grouped.
- Tags with descriptions: one tag per resource, with a sentence in
openapi_tags, so Swagger UI shows collapsible groups with an explanation. - Hide internal routes:
include_in_schema=Falseon health checks, admin and debugging routes. This hides them from the document, not from the server, so they still need authentication. - Split sub-apps: mount a public API and an internal API as separate FastAPI apps. Each has its own
/docs(Q18, Q35).
I also keep summaries short, since Swagger shows them in a list, and put the long explanation in the docstring.
The test is whether a new developer finds a route in under half a minute. If not, I regroup before adding more.
- Tags with descriptions: one tag per resource, with a sentence in
Q14. "APIRouter, prefixes, tags and include_router — how do you organise 60 endpoints?"
Reveal answer
Strong answer One APIRouter per resource or bounded area, in its own module: routers/orders.py, routers/menu.py, routers/restaurants.py, routers/health.py. Each router carries its own prefix, tags and shared dependencies, and main.py only calls include_router for each.
With 60 endpoints, I keep to three rules. A router file stays under about 300 lines and contains only HTTP concerns: parse, call a service, shape the response (Q76). Shared bits (error responses, auth dependencies) live in one place and are attached at the router, not repeated per route. Routers nest: an api router can include the resource routers and be included once with the /v1 prefix.
Tags drive grouping in /docs, so one tag per resource, plus a docstring describing it. Version prefixes (/v1) go on the outermost include, so a /v2 can reuse the same routers selectively.
The canonical QuickBite app follows this: APIRouter(prefix="/v1/orders", tags=["orders"]) in app/routers/orders.py.
Picture it Two resource routers nested into one api router and mounted once; the final OpenAPI paths and tags show the result.
The setup: orders and menu routers with prefixes, combined and included.
from fastapi import APIRouter, FastAPI
orders = APIRouter(prefix="/v1/orders", tags=["orders"])
menu = APIRouter(prefix="/v1/restaurants/{restaurant_id}/menu", tags=["menu"])
@orders.get("")
def list_orders(): ...
@orders.get("/{order_id}")
def get_order(order_id: int): ...
@menu.get("")
def list_menu(restaurant_id: int): ...
api = APIRouter()
api.include_router(orders)
api.include_router(menu)
app = FastAPI()
app.include_router(api)
spec = app.openapi()
for path, item in spec["paths"].items():
for method, op in item.items():
print(f"{method.upper():4} {path:42} tags={op['tags']}")
print("app.routes holds:", [type(r).__name__ for r in app.routes][-1], "(FastAPI 0.141 keeps included routers nested)")Make the invisible visible: Run it.
GET /v1/orders tags=['orders']
GET /v1/orders/{order_id} tags=['orders']
GET /v1/restaurants/{restaurant_id}/menu tags=['menu']
app.routes holds: _IncludedRouter (FastAPI 0.141 keeps included routers nested)What you see: Each path got its prefix and the right tag. The last line shows something new in FastAPI 0.141: app.routes now holds the included router as one nested object, so walking app.routes for paths is no longer reliable; use app.openapi()["paths"] to list what the app serves.
Why: Prefix and tags are declared once per router, so renaming /v1/orders is a one-line change.
Spring Boot
One controller class per resource.
// illustrative
@RestController
@RequestMapping("/v1/orders")
class OrdersController { ... }FastAPI
One router module per resource.
router = APIRouter(prefix="/v1/orders",
tags=["orders"])
app.include_router(router)The shift: A controller class maps to a router module, and component scanning maps to explicit include_router calls.
Land it I give every resource its own router with prefix, tags and shared dependencies, and I include them explicitly from create_app().
- "Why explicit
include_routerinstead of auto-discovery?" -
Because explicit is greppable, and the order is under my control. With auto-discovery, a loader scans a package and imports every router it finds. A new route can appear without anyone writing a line in
main.py, and I can no longer answer "which routes does this service expose?" by reading one file.Order matters because routes match first-come, first-served (Q12). If routers are included by file name order, adding
menu_search.pycould change which route shadows which, and the failure shows up far from the cause.There are also boring costs. Auto-discovery depends on import side effects, which makes start-up errors harder to read, and it makes tests that build a small app with only two routers harder to write.
The price of the explicit way is one extra line per router, and with ten routers that is ten lines in
create_app(). I accept that cost happily, since those ten lines are the table of contents of the whole API. - "Can a router depend on something without every route repeating it?"
-
Yes.
APIRouter(dependencies=[Depends(require_user)])runs that dependency for every route in the router, andinclude_router(r, dependencies=[...])adds more when the router is attached. Nobody repeats it on each route.A dependency listed this way runs before the route's own parameters and dependencies are used, and its return value is thrown away. So it is for guards, such as "the caller is authenticated" or "the caller has the orders scope", and not for data you need in the endpoint.
If the endpoint needs the user, it still declares
user: User = Depends(get_current_user). FastAPI caches the dependency per request, so the token is verified once, not twice. That is the point of the per-request cache.Putting the guard on the router has a safety benefit: a new route added to the orders router is protected by default (Q50). The mistake I am preventing is a forgotten decorator argument on route number 47.
- "How do I keep the layout clean as it grows?"
-
I organise by feature, not by technical type. For orders that means one folder,
orders/, containingrouter.py,schemas.py,service.pyandrepository.py. Everything you need to change an orders feature is in one place.The other layout puts all routers in
routers/, all schemas inschemas/and all services inservices/. For a small service that is fine and clear. At sixty endpoints, each of those folders holds sixty files, and one change touches three distant folders.My practice is that a small service, up to about 30 endpoints, can use the type-based layout. Past that I move to feature folders, and I write the decision in the README so the next developer follows the same layout (Q52).
I keep one rule in both layouts: dependencies point inward. A router may import a service, a service may import a repository, but never the other way round, so layers stay testable.
- "Does include order matter?"
-
Yes, for the same shadowing reason as Q12. Routes are matched in the order they were included, so the first router with a pattern that fits wins, even if a better match comes later.
The rule I follow is: routers with literal, specific prefixes first, anything with catch-all patterns last. A router with
/{slug}as a prefix included before/orderswould swallow orders traffic.I also keep
/healthzand/readyzoutside the versioned API and outside authentication. Deploy tooling, load balancers and Kubernetes probes call them, and they must keep working when the auth provider is down. If health lived under/v1with a security dependency, an identity-provider outage would make the platform think the app is dead and restart it, which makes things worse.A start-up test that lists
app.routesin order and compares it to an expected list takes five minutes and catches accidental reordering.
Q15. "How do you return files, streamed responses and server-sent events?"
Reveal answer
Strong answer Three Starlette response classes cover it. FileResponse(path) sends a file from disk with proper headers and range support, and streams it in chunks. StreamingResponse(generator) sends whatever an iterator yields, one chunk at a time, without holding the whole body in memory. For server-sent events (SSE), I use a streaming response with media type text/event-stream.
An SSE frame is text: data: ... followed by a blank line. The browser's EventSource reconnects by itself. I add Cache-Control: no-cache and, behind nginx, X-Accel-Buffering: no, because proxies love to buffer streams and the client then sees nothing for a minute.
The generator can be async (awaits between chunks) or a plain generator (FastAPI iterates it in the threadpool). Never read a large file into memory and return it: stream it, or redirect to a pre-signed object-storage URL (Q106).
Remember that a streaming response must stop when the client leaves; check await request.is_disconnected() inside long loops.
Picture it A real uvicorn server (httpx's in-process transport buffers the entire body, so it cannot show streaming) sending three SSE frames 0.2 s apart, plus a CSV stream.
The setup: Start uvicorn on a local port in a thread and read the stream chunk by chunk.
import asyncio, httpx, io, time
from fastapi import FastAPI
from fastapi.responses import StreamingResponse, FileResponse
app = FastAPI()
async def ticker():
for i in range(3):
yield f"data: order {i} confirmed\n\n" # SSE frame: "data: ...", blank line
await asyncio.sleep(0.2)
@app.get("/events")
async def events():
return StreamingResponse(ticker(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
@app.get("/export.csv")
def export(): # sync generator -> streamed from the threadpool
def rows():
yield "id,total_cents\n"
for i in range(3): yield f"{i},{i*100}\n"
return StreamingResponse(rows(), media_type="text/csv",
headers={"Content-Disposition": 'attachment; filename="orders.csv"'})
import threading, uvicorn
srv = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=8765, log_level="error"))
threading.Thread(target=srv.run, daemon=True).start(); time.sleep(1) # a real server: ASGITransport buffers whole responses
async def main():
async with httpx.AsyncClient(base_url="http://127.0.0.1:8765") as c:
t = time.perf_counter()
async with c.stream("GET", "/events") as r:
print(r.status_code, r.headers["content-type"])
async for chunk in r.aiter_text():
print(f" +{time.perf_counter()-t:.1f}s {chunk.strip()!r}")
r = await c.get("/export.csv"); print(r.headers["content-disposition"], r.text.split())
asyncio.run(main())Make the invisible visible: Run it.
200 text/event-stream; charset=utf-8
+0.0s 'data: order 0 confirmed'
+0.2s 'data: order 1 confirmed'
+0.4s 'data: order 2 confirmed'
attachment; filename="orders.csv" ['id,total_cents', '0,0', '1,100', '2,200']What you see: The three frames arrived at +0.0 s, +0.2 s and +0.4 s, one per read, while the response was still open. The CSV export came back with a download filename in Content-Disposition.
Why: Chunks leave the server as they are produced. If a proxy buffers, the client would instead see all three at once at +0.6 s, which is the typical "SSE works locally but not in production" bug (Q108).
Naive
Build the whole file in memory.
@app.get("/export.csv")
def export():
data = build_csv_text() # ❌ 500 MB string
return Response(data, media_type="text/csv")Correct
Stream rows as produced.
@app.get("/export.csv")
def export():
return StreamingResponse(rows(),
media_type="text/csv") # ✅ constant memoryThe shift: Memory use should depend on the chunk size, not on the size of the file.
Land it I stream files and exports with generators, set no-buffering headers for SSE, and stop the stream when the client disconnects.
- "Does
response_modelapply to a streaming response?" -
No. Returning a
Responseobject, of any subclass, bypassesresponse_model. FastAPI hands your response straight to the server, so there is no filtering and no validation. The allow-list protection I rely on elsewhere does not exist here.For a stream of JSON records I use newline-delimited JSON: one JSON object per line, media type
application/x-ndjson. Each line is serialised with a response model myself, for exampleOrderOut.model_validate(row).model_dump_json() + "\n".This gives the same guarantee record by record. A row with an extra column loses it, and a row that cannot be converted raises an error on that line. The client can parse lines as they arrive, so memory stays flat on both sides.
The one remaining problem is errors mid-stream. Once the first bytes are sent, the status code is already 200 and cannot change. I send a final error line, or close the connection so that clients see a truncated stream, and I document that behaviour.
- "When would I use WebSockets instead of SSE?"
-
I use WebSockets when the client must also send messages on the same connection. Chat, collaborative editing and live multiplayer are the classic cases, since both sides talk freely.
Server-sent events are one-way, from server to browser. They run over plain HTTP, the browser's
EventSourcereconnects by itself and can resume usingLast-Event-ID, and they pass through most proxies and load balancers without special configuration. A WebSocket needs an upgrade handshake, and some proxies and corporate firewalls handle it badly.For "push order status updates to the app", the client only listens. SSE is simpler and enough, and the REST calls that send commands stay ordinary HTTP with all their tools: retries, caching rules, logs, rate limits (Q107).
A cost to remember for both: each open connection pins a connection on a worker and counts towards file-descriptor limits, so I plan capacity per connection, not per request.
- "How do I handle a very large download behind a proxy?"
-
I let the proxy serve it. The Python process only decides who is allowed to download. It then returns an
X-Accel-Redirectheader (nginx) pointing at an internal path, or a signed object-storage URL, and the proxy or the storage service sends the bytes.The reason is worker time. A 500 MB file over a slow mobile connection might take five minutes. Streamed from Python, that holds a connection and, for a sync generator, a thread for all five minutes. Forty such downloads fill the whole 40-thread pool, and ordinary endpoints queue behind them.
With the redirect trick, the authorisation takes a few milliseconds and the worker is free again. A signed URL, valid for say 5 minutes, also removes the app from the data path completely (Q106).
For downloads that must pass through Python, because the content is generated on the fly, I stream in chunks of about 64 KB and also set a response timeout at the proxy, so a stuck client cannot hold a worker.
- "What does
FileResponsedo that a plain stream does not?" -
It does the work of serving a file correctly, which a plain stream does not. It sets
Content-Length,Last-Modifiedand anETag, so clients and caches can validate cheaply.It also understands
Rangerequests. A video player can jump to minute 40 without downloading the first 39, and a download manager can resume a broken transfer. That is the feature people miss when they roll their own stream.FileResponse reads the file in chunks and uses the threadpool for the disk reads, so the event loop stays free. It also sets the content type from the file name and can add a
Content-Dispositionheader when you passfilename=.For content with no file on disk, such as a CSV built from a query,
StreamingResponseis the correct tool. I choose by asking whether the bytes already exist as a file. If yes,FileResponse, and if I am producing them as I go, a streaming generator.
Q16. "What does response_model do at runtime — not just in the docs?"
Reveal answer
Strong answer At runtime FastAPI takes whatever your endpoint returned (a dict, an ORM object, a model) and validates it against the response model, then serialises only the model's fields. Extra keys are dropped, types are converted, and a value that cannot be converted raises ResponseValidationError, which becomes a 500.
So response_model is two things at once: an allow-list filter (nothing outside the model leaves the server) and a contract check (the server never sends a shape it did not promise). It also supplies the schema in OpenAPI.
The cost is real but small: the return value is validated once per response, and a large list is validated item by item. If you return a model instance the same class as the response model, FastAPI still revalidates unless you tune it, and for hot endpoints that double work shows up in profiles (Q137).
response_model_exclude_unset=True and friends tweak serialisation, and response_model=None turns the machinery off when you return a Response yourself.
Picture it One dict with four keys served three ways.
The setup: The data has id, name, a password_hash and a total_cents stored as the string "12.5".
import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class CustomerOut(BaseModel):
id: int
name: str
DB = {"id": 7, "name": "Asha", "password_hash": "$2b$12$abc", "total_cents": "12.5"}
@app.get("/raw")
def raw(): return DB
@app.get("/filtered", response_model=CustomerOut)
def filtered(): return DB
class Bad(BaseModel):
id: int
total_cents: int
@app.get("/bad-shape", response_model=Bad)
def bad(): return DB
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t", ) as c:
for p in ("/raw", "/filtered"):
print(p, (await c.get(p)).json())
try:
await c.get("/bad-shape")
except Exception as e:
print("/bad-shape raised on the server:", type(e).__name__)
asyncio.run(main())Make the invisible visible: Run it.
/raw {'id': 7, 'name': 'Asha', 'password_hash': '$2b$12$abc', 'total_cents': '12.5'}
/filtered {'id': 7, 'name': 'Asha'}
/bad-shape raised on the server: ResponseValidationErrorWhat you see: With no response model, everything including password_hash left the server. With CustomerOut only id and name did. With a model that wanted total_cents: int, the value "12.5" failed conversion and the server raised ResponseValidationError.
Why: The third case is a feature: a bug in your data layer becomes a loud 500 in testing rather than a silently wrong payload in a client's app.
Naive
Return whatever the ORM gave.
@router.get("/customers/{cid}")
def get(cid: int):
return db.get(Customer, cid) # ❌ all columnsCorrect
Declare the shape.
@router.get("/customers/{cid}",
response_model=CustomerOut)
def get(cid: int):
return db.get(Customer, cid) # ✅ filteredThe shift: The response model turns "everything I have" into "only what I promised".
Land it I treat the response model as a runtime allow-list and contract check, so a data-layer bug fails loudly and extra columns can never leak.
- "Can I use a return type annotation instead of
response_model=?" -
Yes, in modern FastAPI. A return annotation such as
def get() -> CustomerOut:is used as the response model when you do not passresponse_model=. It reads naturally and it keeps type checkers happy, because the function really is declared to return that type.When both are given,
response_model=wins. That is the escape hatch for the common case where the function returns an ORM object. The honest annotation would be-> Customer, the database class, but the client must receiveCustomerOut. Then I writeresponse_model=CustomerOutso the annotation and the real return value may differ.My rule: if the function builds and returns the model itself, annotate it and skip the argument. If it returns a row, a dict or any other type, use the argument.
In both cases the model is an allow-list at runtime, with the filtering and the 500 on an invalid value. The annotation only changes where I write the type, not what the framework does.
- "What does
from_attributes=Truedo?" -
It tells Pydantic that it may read values from object attributes, such as
order.id, and not only from dict keys. It is the bridge between ORM objects and response models.The setting is
model_config = ConfigDict(from_attributes=True)on the response model. Without it, handing a SQLAlchemy object to the model fails validation with an error saying it expected a dict, because an ORM object is not one.With it, Pydantic looks for each field name as an attribute. The model's field list is again the allow-list: attributes that the model does not declare, like
password_hash, are simply never read.One caution is lazy loading. Reading an attribute that is a relationship triggers a query if it was not loaded, so building a response from an ORM object can quietly run extra SQL, one query per row. That is the N+1 pattern. I load the relationships I need up front, then let the model read them (Q17, Q59).
The old v1 name for this setting was
orm_mode. - "Does the response model add much CPU?"
-
Some, and the size of the response decides whether it matters. For one order with 20 lines, validating and serialising is tens of microseconds, invisible beside a database call.
For a 5,000-item list it becomes visible, because the work scales with the item count. I act in this order.
- Return less: paginate, so a page holds 20 to 100 items (Q38).
- Return smaller items: a list view model with five fields, not the full detail model.
- Use the fast path: declare the response model and let FastAPI serialise it directly. In FastAPI 0.141 that is the fast path.
The measurement from the primer, for 5,000 items: 9.9 ms through the response model, 17.8 ms with
ORJSONResponse, which is now deprecated, and 22.5 ms formodel_dumpfollowed byJSONResponse. So the plain way was the quickest, and I would not add a custom response class. I still measure on my own payload before changing anything (Q137). - "What does
response_model_exclude_nonebuy me?" -
It drops keys whose value is
Nonefrom the JSON. That shrinks payloads when many optional fields are empty. A response with twenty optional fields where three are set could shrink by two thirds.I use it sparingly, because for a client a missing key and a
nullvalue are not always the same statement. "No discount applied" can be an absent key, while "the discount was cleared" is anull. A client that treats absence as "unknown" andnullas "none" will behave differently.It also interacts with generated types. A generated TypeScript type usually marks an optional field as
field?: string | nulleither way, so the saving is on the wire, not in the client code.The related option
response_model_exclude_unsetdrops fields the code never set, which suits partial updates. I decide per API, write the rule in the contract, and apply it consistently, because a mixed convention is the one clients cannot guess.
Q17 · Scenario. "An endpoint leaked password_hash in its JSON. How did it happen, and how do you make it impossible?"
Reveal answer
Strong answer It happened because the endpoint returned the ORM object (or model_dump() of a model that included every column) and nothing sat between the database row and the JSON. Whatever the object has goes out. Adding a column later leaks it automatically.
Making it impossible takes three layers. One: the three-model rule. A request model (CustomerCreate), a response model (CustomerOut, an explicit allow-list) and the ORM model (Customer, with the secret). Endpoints declare response_model=CustomerOut.
Two: a test per resource that creates a record with a sentinel secret and asserts it is absent from the JSON, so a new route cannot regress. Three: defence in depth in the data layer, such as deferred columns for secrets, or storing credentials in a separate table that no response model references.
I also scan the OpenAPI schema in CI for field names like password, secret, token, hash, which catches a leak the moment a model grows one.
Picture it The real bug, then the fix, against an in-memory SQLite database.
The setup: A Customer table holds a bcrypt hash. One endpoint returns the ORM row's attributes, the other uses a response model with from_attributes=True.
import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict
from sqlalchemy import create_engine, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase): pass
class Customer(Base):
__tablename__ = "customers"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))
password_hash: Mapped[str] = mapped_column(String(100))
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
with Session(engine) as s:
s.add(Customer(id=7, name="Asha", password_hash="$2b$12$abc")); s.commit()
class CustomerOut(BaseModel): # the allow-list of fields
model_config = ConfigDict(from_attributes=True)
id: int
name: str
app = FastAPI()
@app.get("/naive/{cid}")
def naive(cid: int):
with Session(engine) as s:
c = s.get(Customer, cid)
return {k: v for k, v in c.__dict__.items() if not k.startswith("_")} # ❌ stands in for "return the ORM object"
@app.get("/safe/{cid}", response_model=CustomerOut)
def safe(cid: int):
with Session(engine) as s:
return s.get(Customer, cid) # ✅ model filters to id and name
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for p in ("/naive/7", "/safe/7"):
print(p, (await c.get(p)).json())
asyncio.run(main())Make the invisible visible: Run it.
/naive/7 {'password_hash': '$2b$12$abc', 'id': 7, 'name': 'Asha'}
/safe/7 {'id': 7, 'name': 'Asha'}What you see: /naive/7 includes password_hash. /safe/7 returns only id and name, although the endpoint code returned the same row.
Why: The safe endpoint did not remove the secret; it never listed it. An allow-list fails closed, a deny-list (exclude={"password_hash"}) fails open when somebody adds mfa_secret next month.
Naive
Return the entity.
@app.get("/customers/{cid}")
def get(cid: int, db=Depends(session)):
return db.get(Customer, cid) # ❌ no filterCorrect
Three models, one allow-list.
class CustomerOut(BaseModel):
model_config = ConfigDict(
from_attributes=True)
id: int
name: str # ✅ only theseThe shift: Never describe what to hide; describe the only things allowed to leave.
Land it I make leaks impossible with an allow-list response model on every route plus a sentinel-secret test, rather than by remembering to exclude fields.
- "Why not exclude the field with
response_model_exclude?" -
Because
response_model_exclude={"password_hash"}is a deny-list. It works today, and it fails the first time someone adds another sensitive column, such asreset_tokenormfa_secret. Nothing breaks, the field simply starts leaving the server.The difference is who has to remember. A deny-list needs every developer, on every route, to remember every secret field forever. An allow-list needs nobody to remember anything: a new column is not in
CustomerOut, so it does not leave.A scenario shows it. On Monday the model has 6 columns and the route excludes 1. On Friday a colleague adds
last_login_ip, which is personal data. With the deny-list it ships in every response. With the allow-list it ships nowhere until someone deliberately adds it to the output model, and that deliberate step is a review point.I do use exclusion as an extra layer, for example hiding a field from one specific view. It is never the main protection, and the sentinel test still has to pass without it.
- "Could the leak also come from logs or error messages?"
-
Yes, and it is the same class of bug: sensitive data leaving the system through a side door. Two doors are worth checking.
The first is validation errors. A 422 body contains an
inputfield that echoes what the client sent. If a user types a password into the wrong field, the error returns it, and a logger that stores error bodies keeps it for months.The second is logging models directly. Printing a model prints all its fields, including secrets, unless the field type masks it.
My defences are plain. Declare secrets as
SecretStr, whose printed form is**********and whose value is read only withget_secret_value(). Stripinputfrom errors before logging them, or replace the 422 handler with one that does not echo values (Q29, Q97). Log structured fields I chose, not whole objects.Then the sentinel test extends naturally: after a failing request, assert that the sentinel is absent from the log output too.
- "How do I test it so it cannot come back?"
-
I make a record contain a recognisable fake secret, call every route that can return it, and assert the string appears nowhere in the response text. It is a short test with strong guarantees.
The steps are plain. Create a customer whose password hash is
"s3cr3t-sentinel". Request every route that returns a customer, including list routes, nested uses inside orders, and error cases. Assert that"s3cr3t-sentinel"is not inresponse.text. Testing the raw text, not just the parsed fields, also catches the secret under an unexpected key name.A parametrised test over a list of those routes is about ten lines. Its real value is future routes: add the new route's path to the list and the guarantee covers it. I make the list come from a helper that scans
app.routesfor response models mentioning the customer type, so a new route is covered without anyone remembering.It also runs in CI on every pull request, so the leak is caught before review, not after production.
- "What about nested objects, like an order that contains a customer?"
-
Nested response models apply recursively, and each level needs its own allow-list. That is the part people miss. If
OrderOutcontains a field typedCustomerOut, the nested customer is filtered byCustomerOut, which may still be too wide for an order.So
OrderOutshould hold a smallCustomerSummaryOutwith an id and a display name, not the full customer model and certainly never the ORM class. A restaurant looking at an order has no reason to see the customer's email address.A short scenario: order detail needs the customer's first name for the delivery note. A developer adds
customer: CustomerOutbecause it already exists. The response now carries the email, the phone and the address to a view that never needed them. Everything validates and nothing errors.My habit is to draw the tree of models whenever I add a nested field, and write one sentence per node: who sees it and why. I treat each nested model as a decision, not as a reuse opportunity.
Q18. "How does FastAPI generate OpenAPI, and how do you customise or hide parts of it?"
Reveal answer
Strong answer At the first call to app.openapi() FastAPI walks every route, reads its path, methods, parameters, request and response models and collects them into one OpenAPI 3.1 dict. Pydantic produces the JSON Schemas under components/schemas. The result is cached on app.openapi_schema and served at /openapi.json; /docs (Swagger UI) and /redoc read that URL.
To customise, I choose the smallest tool. Per route: summary, description, tags, operation_id, deprecated, responses, include_in_schema=False. Per app: title, version, openapi_tags, servers, docs_url=None to disable the UI in production. For anything else I override app.openapi with a function that calls the original, edits the dict and caches it.
Hiding is only hiding: include_in_schema=False removes a route from the document, not from the server. A hidden route still needs authentication.
I also set stable operation_ids, because generated clients name their methods from them (Q36).
Picture it A small app with a hidden route, a deprecated route, a custom operation id and a post-processed info block.
The setup: Uses include_in_schema=False, deprecated=True, operation_id and an app.openapi override.
from fastapi import FastAPI, APIRouter
from fastapi.routing import APIRoute
app = FastAPI(title="QuickBite", version="1.0.0", docs_url="/docs", openapi_tags=[{"name": "orders", "description": "Order lifecycle"}])
@app.get("/v1/orders", tags=["orders"], operation_id="listOrders")
def list_orders(): ...
@app.get("/internal/debug", include_in_schema=False) # hidden from the spec, still served
def debug(): ...
@app.get("/v1/old", deprecated=True, tags=["orders"])
def old(): ...
def custom_schema():
if app.openapi_schema: return app.openapi_schema
spec = FastAPI.openapi(app)
spec["info"]["x-logo"] = {"url": "https://example.test/logo.png"} # post-process the generated dict
app.openapi_schema = spec
return spec
app.openapi = custom_schema
spec = app.openapi()
print("paths:", list(spec["paths"]))
print("operationId:", spec["paths"]["/v1/orders"]["get"]["operationId"])
print("deprecated:", spec["paths"]["/v1/old"]["get"].get("deprecated"))
print("info keys:", list(spec["info"]))
print("debug route exists:", any(isinstance(r, APIRoute) and r.path == "/internal/debug" for r in app.routes))Make the invisible visible: Run it.
paths: ['/v1/orders', '/v1/old']
operationId: listOrders
deprecated: True
info keys: ['title', 'version', 'x-logo']
debug route exists: TrueWhat you see: Only the two public paths appear; the custom operation id is kept; the extra x-logo key I added is in info; and the debug route still exists in the router.
Why: The last line is the warning: documentation hiding is cosmetic. /internal/debug answers anyone who types the URL.
Spring · springdoc
Annotation hides it.
// illustrative
@Hidden
@GetMapping("/internal/debug")
String debug() { ... }FastAPI
A decorator flag hides it.
@app.get("/internal/debug",
include_in_schema=False)
def debug(): ...The shift: In both frameworks hiding removes the documentation only; the endpoint is still reachable.
Land it I treat OpenAPI as generated output I shape with tags, ids and responses, and I never rely on hiding a route to protect it.
- "Should I expose
/docsin production?" -
It is a decision, not a default, and the right answer depends on who the API is for. For a public API, the documentation is a product feature, so I expose
/docsor a more polished hosted version, read-only and perhaps rate limited.For an internal API that sits behind an authenticated gateway, I often turn it off with
docs_url=None, redoc_url=None, openapi_url=Noneand publish the spec as a CI artifact or on an internal developer portal. That removes an unauthenticated page that lists every route and parameter, which is useful to an attacker looking for hidden endpoints.The spec itself is not secret, since security should never depend on hiding a route, but exposing less is a reasonable default.
A middle path I like is to keep the docs enabled only in development and staging, with a settings flag, and have production serve the spec from the build output. The point is that someone made the choice on purpose and wrote it down.
- "How do I add security schemes to the spec?"
-
Mostly by using FastAPI's security classes, since declaring a security dependency adds the scheme to the document automatically. Using
HTTPBearer()adds a bearer scheme and the Authorize button in Swagger UI, and routes using it show a padlock.For OAuth2,
OAuth2AuthorizationCodeBearerorOAuth2PasswordBearerdocuments the authorisation and token URLs, so a developer can log in from the docs page and try routes.Scopes can be declared too, through
Security(dependency, scopes=["orders:write"]), and they are listed per operation in the document (Q84). That makes the permission model visible to anyone reading the spec.The alternative is hand-parsing the
Authorizationheader in a function. It works at runtime and says nothing in the document, so generated clients have no idea a token is needed. This is a place where the framework's own classes pay back: one declaration gives runtime enforcement and documentation together. - "Can the spec be generated without starting the server?"
-
Yes.
app.openapi()is an ordinary function call that builds the dictionary from the routes. It needs no server and no network, so it runs in a script or in CI.I export it with a few lines: import the app, call
app.openapi(), and write it withjson.dumptoopenapi.json. Then the file is committed and a CI step regenerates it and compares it with the committed copy.Any difference means the public contract changed. It becomes a line in the pull request that a reviewer reads: a new field, a removed route, a changed status code. A removed or renamed field is a breaking change, and now someone has to approve it knowingly (Q33).
The same exported file feeds the other tools: client generators, contract tests, and API linters.
One practical detail: the app factory must not need a live database at import time, or the export script fails in CI. This is another reason I build the app in
create_app()and keep connections in the lifespan. - "Why do model names sometimes get suffixes like
Body_create_...?" -
FastAPI builds an extra model when an endpoint has several body parameters or a form, and it names the model from the function name and path, which gives names like
Body_create_order_v1_orders_post. Generated clients then expose that ugly name.The remedy is to give the body one explicit model. Instead of three separate body parameters, I write one request model,
OrderCreate, with those fields, and the endpoint takes it as the only body. The schema is then namedOrderCreate, which makes a better client type.For forms and file uploads, the generated name is harder to avoid. I accept it.
Operation ids have the same problem. The default is built from the function name and path, so I set
operation_idexplicitly or generate it from the function name, since generated client methods are named after it (Q36).
Q19. "Form data and file uploads — what changes, and which limits must you set?"
Reveal answer
Strong answer Forms and files use the multipart/form-data or application/x-www-form-urlencoded content types instead of JSON, so the parameters must be declared with Form() and File() / UploadFile, and the python-multipart package must be installed (it is the parser). A single endpoint cannot accept both a JSON body and a file in the same request: the body parts become form fields.
UploadFile wraps a spooled temporary file: small uploads stay in memory, larger ones spill to disk. It offers await file.read(n), file.filename, file.content_type. Reading await file.read() with no size loads everything into memory, so read in chunks.
Limits to set, in layers: the reverse proxy body size (nginx client_max_body_size); a Content-Length check returning 413 early; a streaming byte counter because the header may be missing or wrong; a maximum number of parts and fields and a maximum part size for forms (recent FastAPI and Starlette versions expose form-parsing limits; I check the release notes for the exact names); and an allow-list of content types plus a content sniff, because the client-sent content_type is only a claim.
Picture it A 1 KiB limit enforced while reading in chunks, a small and a large upload, and the wrong content type.
The setup: The endpoint takes a form field and a file, reads 256-byte chunks and stops when the total passes the limit.
import asyncio, httpx, io
from typing import Annotated
from fastapi import FastAPI, File, Form, UploadFile, HTTPException
app = FastAPI()
MAX = 1024 # 1 KiB for the demo
@app.post("/menu-import")
async def menu_import(restaurant_id: Annotated[int, Form()], file: Annotated[UploadFile, File()]):
size = 0
while chunk := await file.read(256): # read in chunks; never file.read() the whole thing blindly
size += len(chunk)
if size > MAX:
raise HTTPException(413, f"file larger than {MAX} bytes")
return {"restaurant_id": restaurant_id, "filename": file.filename, "bytes": size, "type": file.content_type}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for n in (300, 5000):
r = await c.post("/menu-import", data={"restaurant_id": "3"}, files={"file": ("menu.csv", io.BytesIO(b"x" * n), "text/csv")})
print(n, "bytes ->", r.status_code, r.json())
r = await c.post("/menu-import", json={"restaurant_id": 3})
print("JSON instead of multipart ->", r.status_code, r.json()["detail"][0]["type"])
asyncio.run(main())Make the invisible visible: Run it.
300 bytes -> 200 {'restaurant_id': 3, 'filename': 'menu.csv', 'bytes': 300, 'type': 'text/csv'}
5000 bytes -> 413 {'detail': 'file larger than 1024 bytes'}
JSON instead of multipart -> 422 missingWhat you see: 300 bytes succeeded and returned the filename and claimed content type. 5,000 bytes got 413. A JSON body to the same route returned 422 with type: missing for the required form fields.
Why: The 413 was decided while reading, with no need to hold the file. The client-claimed text/csv was just echoed back; the server never verified it.
Naive
Read it all, trust the name.
data = await file.read() # ❌ any size
path = f"/data/{file.filename}" # ❌ ../../x
open(path, "wb").write(data)Correct
Chunked, capped, own name.
name = f"{uuid4()}.csv" # ✅ own name
while chunk := await file.read(65536):
size += len(chunk)
if size > MAX: raise HTTPException(413)The shift: Treat every part of an upload (size, name, type) as untrusted input from a stranger.
Land it I cap upload size at the proxy and in the app while streaming, generate my own file names, and never trust the client's content type.
- "How do I upload to S3 without passing through my server?"
-
I return a pre-signed URL, a time-limited address signed by the storage service, and let the browser or app send the file straight to object storage. My API never touches the bytes.
- Ask: the client calls
POST /v1/uploadswith the file name, size and content type. I check the limits and reply with a signed URL that is valid for about five minutes and an object key I generated. - Upload: the client sends the file to that URL. The storage service enforces the size limit written into the signature.
- Confirm: the client calls my API to say it is done, and I check that the object exists and record its key.
This removes the memory and worker-time problem completely. A 500 MB upload that would hold a connection for minutes costs my API two short requests (Q106). I still validate afterwards, because the client can upload anything, so content checks run on the stored object in a background worker.
- Ask: the client calls
- "Why is the filename dangerous?"
-
Because it is controlled by the client, so it is attacker input. A name such as
../../etc/cron.d/xjoined to a folder path writes outside the folder. Names with null bytes, very long names, reserved names on Windows, and unicode tricks cause further trouble.It can also deceive people. A name like
invoice.pdfwith a different real type is a common phishing trick, so the extension is a claim and not a fact.My rule is never to use the client's file name for storage. I generate an id, for example a UUID, and store the file as
uploads/9f3a.... The original name is kept as a database column for display, after stripping path separators and control characters and cutting it to a sensible length such as 100 characters.When the file is served back, I send it with a safe
Content-Dispositionheader, and for user content I prefer a separate domain, so that a malicious HTML upload cannot run on my main site. - "What about checking the file's real type?"
-
I read the first bytes of the file, called the magic number, and compare them with the formats I allow. A PDF starts with
%PDF-, a PNG with the eight bytes89 50 4E 47 0D 0A 1A 0A, a ZIP withPK.That check is cheap and catches the lazy attack, a script renamed to
.png. It is not enough alone, because a file can start with valid bytes and carry something else later.For images I go further and decode them with Pillow, then re-encode. That proves the file is a real image and also removes metadata, such as GPS coordinates in photos, which matters for privacy.
Parsing untrusted formats is where vulnerabilities live: image libraries, archive extractors and spreadsheet parsers have a long history of memory-safety bugs and decompression bombs, where a 1 MB file expands to several gigabytes. So I run that parsing in a separate worker with CPU and memory limits, away from the web workers, and a crash there harms nobody else.
- "Can I limit the number of form fields?"
-
Yes. A multipart request can contain thousands of tiny parts, each costing parsing time, and an attacker can use that to burn CPU with a small body. So parser limits exist and are worth setting.
Recent Starlette and FastAPI releases added configurable limits for multipart parsing: how many files, how many fields, and how large a single part may be. The argument names have changed across versions, so I read the current documentation for the version I pin rather than quoting names from memory.
The limits are the app's wall. The proxy is the other one, and I set both: for example the proxy at 10 MB per request, and the app refusing more than a handful of files per request.
Q20 · Design. "Design the URL and router structure for the QuickBite orders API."
Reveal answer
Strong answer I design around nouns and ownership, with a version prefix and one router per resource. The orders router owns POST /v1/orders (create, with an Idempotency-Key header), GET /v1/orders/{order_id}, GET /v1/orders (the caller's orders, cursor-paginated), and PATCH /v1/orders/{order_id} (status transitions). Health lives outside the version: GET /healthz and GET /readyz.
Conventions: plural nouns; ids opaque and never sequential in public APIs when guessing matters (UUID or prefixed ids); filters as query parameters (?status=preparing&limit=20&cursor=...); lines as a nested part of the order body rather than their own top-level resource, because they are never read alone; a restaurant's incoming orders under GET /v1/restaurants/{id}/orders with its own router and its own role check.
Cross-cutting design: every route behind a security dependency with a scope (orders:read, orders:write), ownership enforced in the repository (Q91), one Problem error model on every route (Q94), /v1 prefix applied at the outermost include so a /v2 can coexist (Q35), and request ids in every response (Q129).
Actions that are not CRUD get a sub-resource verb: POST /v1/orders/{id}/cancellation, not POST /cancelOrder. It remains a noun and can carry its own result.
Picture it The route table I would put on the whiteboard, with who may call each route and what comes back.
The setup: Customers, restaurants and admins use the same domain but different routers.
# illustrative
POST /v1/orders 201 + Location orders:write Idempotency-Key header
GET /v1/orders/{order_id} 200 | 404 orders:read owner only (404 for others)
GET /v1/orders?cursor=&limit= 200 OrderPage orders:read caller's orders, newest first
PATCH /v1/orders/{order_id} 200 | 409 orders:write status change, partial update
POST /v1/orders/{order_id}/cancellation 202 | 409 orders:write async refund starts
GET /v1/restaurants/{rid}/orders 200 OrderPage restaurant:read the restaurant's queue
GET /healthz 200 always | GET /readyz 200 if DB reachable, else 503What you see: Every row has a verb, a success and failure code, a scope and an ownership rule. Nothing returns a bare list: OrderPage carries items and next_cursor.
Why: A reviewer can check the design by reading one table: is the create safe to retry, is the list bounded, can a customer read someone else's data, and what happens on every error.
Naive
Verbs in URLs, one router.
@app.post("/createOrder")
@app.get("/getOrders") # no paging
@app.post("/cancelOrder") # which id?Correct
Resources, versions, routers.
router = APIRouter(prefix="/v1/orders")
@router.post("", status_code=201)
@router.get("") # cursor paged
@router.get("/{order_id}")The shift: Put the noun in the URL and the action in the HTTP method; everything else is a sub-resource.
Land it I design nouns with versioned routers, safe retries on create, bounded lists, ownership in the data layer and one error format everywhere.
- "Why return 201 with a
Locationheader for creates?" -
Because 201 says that a resource now exists, and the
Locationheader says where to find it. A client or generated SDK can follow the link, so it never has to build URLs by itself.Take
POST /v1/orders. The response is201 CreatedwithLocation: /v1/orders/9f3a...and the order in the body. A 200 would only say "it worked", and the client would have to guess the next step. Clients that followLocationkeep working if I change the URL layout.It combines well with idempotency. If the client retries with the same
Idempotency-Key, I return the same 201 and the sameLocation, so the retry cannot be told apart from the first try (Q72). In the course app the replay also adds a header,Idempotent-Replayed: true, for debugging.I document the header in
responses=and set it with theResponseparameter. A create returning 200 without a link is the pattern I flag in review. - "Where do I put the restaurant's view of the same orders?"
-
In a separate router with its own prefix, scope, and response model, for example
GET /v1/restaurants/{id}/orderswith a role check for restaurant staff. It looks like a copy of the customer's route, but it answers a different question.The restaurant sees different fields: kitchen notes and item preparation status, but no payment details and perhaps only the customer's first name. It has different access rules too, since staff may see only orders for their own restaurant. And it has different sorting and filters, such as "orders to prepare now".
Sharing one endpoint with
if role == "restaurant":branches is how mistakes start. The response model has to be the union of all views, so one field is easy to leak to the wrong role, and the authorisation logic becomes a thicket of conditions (Q92).With separate routers, each route has one response model and one scope, and the tests are simple. Shared code goes in the service layer and not in the route.
- "Should ids be integers or UUIDs?"
-
Both, in different places. Internally, integers are compact and index well, which matters for large tables, so the database often uses them as primary keys.
Externally, a sequential id reveals volume and invites guessing. Someone who sees order id 10412 today and 10520 tomorrow can estimate your orders per day, and can try 10413 to look for a missing ownership check. So for public ids I either expose a random identifier, a UUID or a prefixed ULID such as
ord_01J..., or I rely strictly on ownership checks and accept visible counts.Random ids are not a replacement for access control. They only make guessing impractical, and the ownership check (someone else's order returns 404) is still required.
UUIDv7 is a good choice when index performance matters: it is random enough to be unguessable but time-ordered, so new rows land near each other in the index, unlike UUIDv4, which scatters inserts across the whole index.
- "How would this change for a public developer API?"
-
A public API makes promises, and the design must keep them for years. The checklist for the public version is longer than for an internal one.
- Versioning and deprecation: stricter versioning with a written policy, deprecation headers and a long notice period (Q35, Q40).
- Protection: rate limits per key, answered with 429 and
Retry-After(Q90), plus idempotency on every unsafe method. - Efficiency: ETags for conditional requests (Q104), and webhooks for status changes instead of clients polling.
I would also publish a changelog and a status page, issue API keys with scopes, and keep error bodies stable, since external developers write code against them.
An internal API can move faster, because I can find and update every caller. With a public one I cannot, so I add, never remove or rename, and every change goes through review of the exported OpenAPI diff.
These questions test whether you understand validation as parsing at the boundary, can predict what lax mode does to real client input, and know the model-shaping tools (aliases, dumps, validators) well enough to design request and response models.
Q21. "What changed from Pydantic v1 to v2, and why is v2 faster?"
Reveal answer
Strong answer The big change: the validation engine, pydantic-core, is rewritten in Rust, and the Python layer became a thin wrapper that builds a validator once when the class is defined. In v1 every validation walked Python code on every call. In v2 the class compiles a schema into a Rust validator, and Model(**data) or model_validate_json just runs it.
API changes you meet daily. .dict() became model_dump(), .json() became model_dump_json(), parse_obj became model_validate, Config class became model_config = ConfigDict(...). @validator became @field_validator and @root_validator became @model_validator. orm_mode became from_attributes. Settings moved to the separate pydantic-settings package.
Behaviour changes: stricter handling of some conversions, Optional[int] no longer implies a default of None (a field with no default is required even if it can be None), and the JSON Schema output follows modern standards. FastAPI 0.141 on this machine runs on Pydantic 2.13.
model_validate_json is the fastest path: it parses JSON and validates in one pass in Rust, without creating Python dicts first.
Picture it The renamed methods (with the deprecation warning v1 style produces) and a timing for validating 1,000 lines two ways.
The setup: A two-field Line model. This is a small timing, not the primer's 1,000-line order; absolute numbers will differ on your machine.
import warnings, timeit
from pydantic import BaseModel, field_validator
class Line(BaseModel):
item_id: int
qty: int
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
l = Line(item_id=1, qty=2)
print(".dict() ->", l.dict()); print(" warning:", w[0].category.__name__)
print("model_dump() ->", l.model_dump())
print("v1 @validator was renamed: field_validator exists:", field_validator.__name__)
raw = '[' + ','.join('{"item_id": %d, "qty": 2}' % i for i in range(1000)) + ']'
import json
from pydantic import TypeAdapter
ta = TypeAdapter(list[Line])
t1 = timeit.timeit(lambda: ta.validate_json(raw), number=200) / 200
t2 = timeit.timeit(lambda: [Line(**d) for d in json.loads(raw)], number=200) / 200
print(f"1,000 lines: validate_json {t1*1000:.2f} ms | json.loads + Line(**d) {t2*1000:.2f} ms (this machine)")Make the invisible visible: Run it.
.dict() -> {'item_id': 1, 'qty': 2}
warning: PydanticDeprecatedSince20
model_dump() -> {'item_id': 1, 'qty': 2}
v1 @validator was renamed: field_validator exists: field_validator
1,000 lines: validate_json 0.91 ms | json.loads + Line(**d) 1.23 ms (this machine)What you see: .dict() still works but raises PydanticDeprecatedSince20; model_dump() is the new name. Validating 1,000 lines straight from the JSON string took 0.91 ms, while decoding with json.loads and building each model from a dict took 1.23 ms.
Why: The JSON path is faster because the Rust code reads the bytes directly. Both are fast; at API scale validation is rarely the bottleneck, but this is why handing FastAPI the raw JSON is already efficient.
Pydantic v1
Python-level validation, old names.
class Line(BaseModel):
qty: int
class Config:
orm_mode = True
x = Line.parse_obj(d).dict()Pydantic v2
Rust core, new names.
class Line(BaseModel):
model_config = ConfigDict(
from_attributes=True)
qty: int
x = Line.model_validate(d).model_dump()The shift: The model class is compiled once into a Rust validator, so each request pays for running it, not for building it.
Land it I say v2 moved validation into a Rust core compiled at class-definition time, renamed the API around model_*, and made required-versus-optional explicit.
- "Is the migration from v1 mostly mechanical?"
-
Mostly, yes. The
bump-pydantictool rewrites the common renames:.dict()tomodel_dump(),parse_objtomodel_validate,Configclasses tomodel_config. For a typical API that handles most of the diff.The manual part is about three things.
- Validators:
@validatorbecame@field_validatorwith a different signature and explicit modes, and root validators became model validators. - Implicit defaults: a field typed
Optional[int]with no default used to default toNoneand is now required. - Looser coercions: v1 accepted some conversions that v2 rejects, so code that leaned on them fails at runtime, not at import.
To find leftovers I run the full test suite with deprecation warnings turned into errors (
-W error::DeprecationWarning). The remaining v1 spellings still work in v2 with a warning, so that flag lists them all.The third item is the dangerous one, because it shows up as a 422 for a real client. So I replay recorded real request bodies against the new models before releasing.
- Validators:
- "Does
Optional[int]mean "may be omitted" now?" -
No, and the difference catches people during migration.
int | Nonesays the value may beNone. Whether the key may be left out depends on whether the field has a default.I checked both forms on Pydantic 2.13.5.
q21_optional.py · Pydantic 2.13.5runs offlineA(): missing B(): qty=NoneClass
Adeclaresqty: int | Nonewith no default, and building it with noqtyraised an error of typemissing. ClassBdeclaresqty: int | None = Noneand built fine.So
Ais required but nullable: the client must send the key, possibly asnull. For an API that is a useful distinction, but surprising if you came from v1, where both would have been optional.My habit is to write the default every time I mean "optional", and leave it out only when I mean "required, but the value may be null".
- "Where is v2 not faster?"
-
It is not faster in every case, and I say so to avoid overselling. There are three situations where the gain shrinks.
For tiny models with one or two fields, the fixed cost of calling into the validator dominates, so the Rust speed-up is small in absolute terms. Both versions finish in microseconds.
For models with custom Python validators, those validators run in Python in both versions, and they dominate the time. A single
@field_validatorthat runs a regex or a lookup can cost more than all the Rust validation of the other fields combined.And once a request includes a database or network call, validation speed stops mattering. If validating takes 40 microseconds in v2 and 400 in v1, and the query takes 5 ms, the difference is under 8% of the request.
So the real wins are large payloads, such as lists of hundreds of items, and heavy parsing load. I measure on my own models before quoting a ratio, because the ratio depends on the shape of the data.
- "How do I check which Pydantic version I am running?"
-
I read
pydantic.VERSIONfor the Python layer andpydantic_core.__version__for the Rust engine underneath. They are versioned separately, and a bug report needs both. On the course machine, Pydantic is 2.13.5.Two other places answer the same question without opening a shell:
pip show pydantic, and the lock file, which records the exact resolved version.I log the version at startup, together with the versions of FastAPI, Starlette and SQLAlchemy, in one structured line. During an incident review, that line settles an argument quickly: the behaviour of a validator or an error message may have changed between 2.11 and 2.13, and you need to know which one applied.
I also pin versions in the lock file and upgrade on purpose, one dependency at a time, with the test suite green. Pydantic's minor releases occasionally change error text or edge-case conversions, and a pinned version means a deploy never changes behaviour without a pull request.
Q22. "Lax versus strict mode — what does "42" become for an int field?"
Reveal answer
Strong answer In the default lax mode Pydantic tries to convert reasonable values, so "42" becomes the integer 42. In strict mode it refuses: only a real int is accepted and "42" raises an error of type int_type.
Lax mode is the right default for JSON APIs: it accepts the harmless variants that real clients send ("42", 42.0, whitespace around a number, booleans where numbers are expected). Its dangers are subtle: True becomes 1, which is rarely what a client meant, and a float with a fraction (42.5) is rejected rather than rounded, which is correct.
Strict mode can be set per model (ConfigDict(strict=True)), per field (Field(strict=True)), or per call (model_validate(data, strict=True)). I use strict for money, ids and flags where silent conversion hides client bugs, and lax elsewhere.
Note that JSON has no distinction between int and float for 42.0; strict-mode handling of that follows the JSON-versus-Python input rules, so I test the exact values rather than assume.
Picture it Seven inputs against one int field, lax on the left, strict on the right.
The setup: Lax is a plain model; Strict has strict=True.
from pydantic import BaseModel, ValidationError, ConfigDict
class Lax(BaseModel):
qty: int
class Strict(BaseModel):
model_config = ConfigDict(strict=True)
qty: int
for v in ("42", 42.0, 42.5, True, " 7 ", "4e1", None):
row = [repr(v).ljust(7)]
for M in (Lax, Strict):
try: row.append(f"{M.__name__}: {M(qty=v).qty!r}".ljust(14))
except ValidationError as e: row.append(f"{M.__name__}: ERR {e.errors()[0]['type']}".ljust(34))
print(" | ".join(row))Make the invisible visible: Run it.
'42' | Lax: 42 | Strict: ERR int_type
42.0 | Lax: 42 | Strict: ERR int_type
42.5 | Lax: ERR int_from_float | Strict: ERR int_type
True | Lax: 1 | Strict: ERR int_type
' 7 ' | Lax: 7 | Strict: ERR int_type
'4e1' | Lax: ERR int_parsing | Strict: ERR int_type
None | Lax: ERR int_type | Strict: ERR int_type What you see: Lax accepts '42', 42.0, True (as 1) and ' 7 ' (as 7); it rejects 42.5 (int_from_float), '4e1' (int_parsing) and None. Strict rejects every non-int, including the bool True.
Why: The row to remember is True becoming 1 in lax mode. A client that sends "qty": true is almost certainly confused, and strict mode would tell it so.
Lax (default)
Converts what it can.
class Line(BaseModel):
qty: int
Line(qty="2").qty # 2
Line(qty=True).qty # 1 (!)Strict
Accepts only the exact type.
class Line(BaseModel):
qty: Annotated[int, Field(strict=True)]
Line(qty="2") # ❌ int_type
Line(qty=2) # ✅The shift: Lax asks "can I make sense of this?"; strict asks "is this exactly what I specified?".
Land it I keep lax mode for ordinary fields and use strict on money, flags and ids where a silently converted value would hide a client bug.
- "Does strictness apply to JSON bodies the same as Python dicts?"
-
Not always, and the reason is that JSON has fewer types than Python. Inputs from
model_validate_json, which is what FastAPI uses for request bodies, follow the JSON-mode rules, which are slightly different from Python-mode rules.The classic example is dates and UUIDs. JSON has no datetime type, so a datetime arrives as a string. In Python strict mode a string is not accepted for a
datetimefield, but in JSON mode a JSON string is accepted, because it is the only way to send one.The consequence is about testing. If I check a strict field only by calling
Model.model_validate({...})with Python values, I am testing a different set of rules than the ones real clients meet. So I test strict fields with real HTTP requests through the client, including the awkward values, and I assert the status codes I actually get. - "What happens with
"qty": 2.7and why not round it?" -
Lax mode rejects it, with the error type
int_from_float. I ran the neighbouring cases on Pydantic 2.13.5 to see them together.q22_strict.py · Pydantic 2.13.5runs offlineLax '42' -> 42 Lax True -> 1 Lax 2.7 -> error int_from_float Strict '42' -> error int_type Strict True -> error int_type Strict 2.7 -> error int_typeThe point of the lax rule is that conversions must not lose information.
"42"becomes 42 with nothing lost, while 2.7 would become 2 or 3, and a guess hides a real client bug.Rounding silently turns an unclear order into a wrong order: a customer who typed 2.7 portions gets 2 or 3, and nobody notices. A 422 naming the field is more useful, because the client developer fixes the bug once.
Note the surprise in line two: lax mode turns
Trueinto 1, which is why I use strict for quantities. - "Should the whole API be strict?"
-
Usually no. A fully strict API rejects clients that send numbers as strings, which happens often with form fields, spreadsheets exported to JSON, and some older SDKs. The result is support tickets and workarounds, and little benefit.
My approach is to choose strictness where a wrong conversion costs money or data. Three places qualify: money amounts, ids, and flags.
For money, I use integer cents and
Field(strict=True), so"10.50"ortruenever becomes a price. For ids, strictness stops a client from sending1e3orTruewhere an id should be. For boolean flags, it stops"yes"silently meaning true in a place where I want a clear contract.Everything else stays lax: names, free text, page sizes, dates.
Whichever way I go, the type is written in the OpenAPI schema, so a client developer can see "integer" and not guess. I also record the decision in the contract, so the next person adding a field knows which rule applies where.
- "How do query parameters behave?"
-
Query values always arrive as text, because a URL has no types. So FastAPI validates them in lax mode regardless of your model settings:
?limit=20is the string"20"that becomes the integer 20.If you applied strict mode to an integer query parameter, it would reject every request, since a string is never accepted as a real int in strict Python mode. So strict mode is for bodies, where JSON carries real numbers and booleans.
The same holds for path parameters, headers and cookies: all text, all lax.
For query parameters I get precision a different way, through constraints and closed sets.
Query(ge=1, le=100)bounds a number,Literal["asc", "desc"]closes a choice, and apatternchecks a format. These reject bad input clearly without needing strict mode.A habit worth keeping: write one test per list endpoint that sends
?limit=abc,?limit=0and?limit=101and asserts three 422s.
Q23. "field_validator versus model_validator — before, after and wrap."
Reveal answer
Strong answer A field_validator checks or transforms one field. A model_validator sees the whole model, so it is the place for rules that compare fields ("end must be after start", "an order needs at least one line").
Each has modes. before runs on the raw input, before Pydantic's own type conversion, so the value can be anything (use it to normalise: blank string to None, one item to a list). after runs on the converted, typed value, so you can rely on the type (use it for business checks). wrap receives a handler function; you call it to run the normal validation and can catch its error, retry, or change the result.
Prefer built-in constraints (Field(gt=0), Annotated types) when they express the rule, because they are faster, appear in the OpenAPI schema and need no code (Q24). Use validators for rules that need logic. Never put database lookups in a validator: they hide I/O in construction. Rules that need the database (restaurant is open) belong in the service.
Raise ValueError (or AssertionError) for a failed check; Pydantic wraps it into a structured error with the field location.
Picture it One model using all four kinds.
The setup: coupon is normalised before and upper-cased after; lines accepts one id as a list through a wrap validator; a model validator requires at least one line.
from typing import Any
from pydantic import BaseModel, field_validator, model_validator, ValidationError, ValidatorFunctionWrapHandler
class OrderIn(BaseModel):
coupon: str | None = None
lines: list[int]
@field_validator("coupon", mode="before") # before: raw input, any type
@classmethod
def blank_to_none(cls, v: Any):
return None if isinstance(v, str) and not v.strip() else v
@field_validator("coupon", mode="after") # after: already a str here
@classmethod
def upper(cls, v):
return v.upper() if v else v
@field_validator("lines", mode="wrap") # wrap: run the normal validation yourself
@classmethod
def wrap(cls, v: Any, handler: ValidatorFunctionWrapHandler):
try: return handler(v)
except ValidationError: return handler([v]) # accept a single id as [id]
@model_validator(mode="after") # cross-field rule
def need_lines(self):
if not self.lines: raise ValueError("an order needs at least one line")
return self
print(OrderIn(coupon=" ", lines=[1]).model_dump())
print(OrderIn(coupon="eid10", lines=5).model_dump())
try: OrderIn(lines=[])
except ValidationError as e: print(e.errors()[0]["type"], "|", e.errors()[0]["msg"], "| loc:", e.errors()[0]["loc"])Make the invisible visible: Run it.
{'coupon': None, 'lines': [1]}
{'coupon': 'EID10', 'lines': [5]}
value_error | Value error, an order needs at least one line | loc: ()What you see: A blank coupon became None (before), eid10 became EID10 (after), the bare 5 became [5] (wrap), and an empty lines list produced a value_error with an empty location because it belongs to the model, not a field.
Why: The empty loc: () is the clue to the validator kind: errors from a model_validator point at the whole body, so a client cannot highlight a single input. If you want a field-located error, use a field validator or PydanticCustomError with a location.
Bean Validation
Class-level constraint.
// illustrative
@AssertTrue(message = "at least one line")
boolean hasLines() {
return !lines.isEmpty();
}Pydantic
Model validator.
@model_validator(mode="after")
def need_lines(self):
if not self.lines:
raise ValueError("at least one line")
return selfThe shift: In both worlds, cross-field rules need custom code; single-field rules should be declarative constraints.
Land it I use declarative constraints first, field validators to normalise or check one field, model validators for cross-field rules, and I keep I/O out of all of them.
- "Why not call the database in a validator to check the restaurant is open?"
-
Because a validator runs while the object is being built, and building happens in more places than the request handler. It happens in tests, in
model_validatecalls on stored data, in OpenAPI example generation, and wherever someone constructs the model by hand.A query inside it makes construction slow and impossible to run in async code, since validators are synchronous. It makes tests need a database for something that looks like a pure data class. And it hides the cost: a developer reading
OrderCreate(...)does not expect I/O.It also mixes two kinds of errors. "The quantity is negative" is a validation error and a 422. "The restaurant is closed" is a state problem, which should be a 409 with its own message.
The check belongs in the service, which owns the session and the transaction and can return the right status. The model validates shape and simple rules, and the service checks the world. If I ever see
Sessionimported into a schema file, I flag it in review. - "When is
wrapthe right choice?" -
When I need to run the normal validation and then decide what to do with its result or its failure. The wrap validator receives the input and a handler. I call the handler to do the usual work, and I can catch its error, change the value, or try something else.
A concrete case is a legacy client that sends a date as
"25/11/2026"while new clients send ISO dates. A wrap validator tries the normal parse first, and if that raises, tries the old format.It is the least common mode, and I use it only when the other two cannot do the job.
beforeplusafterhandle most needs:beforenormalises raw input, such as blank string toNone, andafterchecks the typed value.The cost of wrap is readability. The control flow runs around the handler call, and a reader has to follow two paths.
- "Does a validator run on assignment?"
-
Only if you ask. By default, validators run when the model is built, and an assignment afterwards, such as
order.qty = 0, is not checked. The invalid value just sits in the object.Setting
validate_assignment=Truein the model config makes Pydantic re-validate on every assignment, and run the field's validators again. A model validator also runs again, after the change.For request models this seldom matters, because they are built once from the request and read afterwards. But for mutable domain objects that change during processing, an unchecked assignment is a place where bad data enters quietly.
I have two answers. One is to turn on
validate_assignmentfor those models, accepting a small cost per assignment. The other is to make the model frozen withfrozen=True, so changes needmodel_copy(update=...), and note thatmodel_copydoes not validate by default either. For anything where the rules matter, I rebuild throughmodel_validateto re-run them. - "How do I return several errors at once?"
-
Pydantic does most of this for me. It validates every field and gathers all the errors before it fails, so one 422 lists every invalid field. A client fixes everything in one round trip.
The rule I follow in my own code is not to undo that. Inside one validator I raise one error for the field, and I do not stop at the first problem across fields, because each field has its own validator.
For a model validator, a rule that compares fields, such as "end must be after start", fails with one error. If it must report several problems at once, I check each one first, collect them into a message, then raise once, and never return early on the first.
One limit: a model validator in
aftermode only runs if the field validation succeeded. So cross-field errors appear after the field errors are fixed.
Q24. "How do you express constraints with Annotated and Field, and reuse them?"
Reveal answer
Strong answer Annotated[int, Field(gt=0, le=50)] attaches metadata to a type. Pydantic reads it and builds the check into the compiled validator. Give it a name once and reuse it: Qty = Annotated[int, Field(gt=0, le=50)], then write qty: Qty in every model.
Constraint options are the same for every field: numbers (gt, ge, lt, le, multiple_of), strings (min_length, max_length, pattern), collections (min_length, max_length). StringConstraints bundles string rules including stripping whitespace and lower-casing.
Why this style wins. The constraint lives in one named place; error messages carry the limits (ctx: {"gt": 0}); and the limits appear in the OpenAPI schema (exclusiveMinimum, maximum), so generated clients can validate too. A validator function would do none of those things automatically.
I define a small types.py of domain types: Qty, Cents, PinCode, Money. A reviewer reads one file to know what the API accepts.
Picture it Two reusable types, three invalid values, and the JSON Schema that results.
The setup: Qty, Cents and a six-digit Pin type used in two models.
from typing import Annotated
from pydantic import BaseModel, Field, ValidationError, StringConstraints
Qty = Annotated[int, Field(gt=0, le=50)]
Cents = Annotated[int, Field(ge=0)]
Pin = Annotated[str, StringConstraints(pattern=r"^\d{6}$")]
class Line(BaseModel):
item_id: int
qty: Qty
price_cents: Cents
class Address(BaseModel):
pin: Pin
for data, M in ((dict(item_id=1, qty=0, price_cents=-5), Line), (dict(pin="56001"), Address)):
try: M(**data)
except ValidationError as e:
for x in e.errors(): print(M.__name__, x["loc"], x["type"], x["ctx"])
print("schema keeps the limits:", Line.model_json_schema()["properties"]["qty"])Make the invisible visible: Run it.
Line ('qty',) greater_than {'gt': 0}
Line ('price_cents',) greater_than_equal {'ge': 0}
Address ('pin',) string_pattern_mismatch {'pattern': '^\\d{6}$'}
schema keeps the limits: {'exclusiveMinimum': 0, 'maximum': 50, 'title': 'Qty', 'type': 'integer'}What you see: Each error names its field, its type (greater_than, greater_than_equal, string_pattern_mismatch) and the limit that failed. The generated schema for qty contains exclusiveMinimum: 0 and maximum: 50.
Why: Declared once, enforced at the border, documented automatically. A hand-written if qty <= 0 would do only the first.
Bean Validation
Annotations on each field.
// illustrative
record LineIn(
@Min(1) @Max(50) int qty,
@Min(0) long priceCents) {}Pydantic
A named, reusable type.
Qty = Annotated[int, Field(gt=0, le=50)]
Cents = Annotated[int, Field(ge=0)]
class LineIn(BaseModel):
qty: Qty
price_cents: CentsThe shift: Bean Validation repeats the annotation on each field; Annotated types let you name the rule once and reuse it.
Land it I define domain types once with Annotated and Field, so limits are enforced, reported and documented from one definition.
- "What is the difference between
Field(default=...)and= valuein the signature?" -
For a plain model they are equivalent:
qty: int = Field(default=1, gt=0)andqty: int = 1with a constraint both give a default of 1. The difference is where things sit once you useAnnotated.Inside
Annotated, I put the constraints and keep the default after the equals sign:qty: Annotated[int, Field(gt=0)] = 1. The type stays reusable, sinceAnnotated[int, Field(gt=0)]carries no default and can be named once and used in many models.If the default lived inside
Field(default=...), reusing the alias would bring that default along everywhere. A named alias should describe a type, not a particular field's default.FastAPI's documentation recommends the
= valueform withAnnotated, and it has one more benefit. The default stays visible in the function signature, so a reader sees it without opening the metadata.For parameters, I follow the same pattern with
Query,HeaderandPath: metadata inAnnotated, default after the=. - "Can constraints depend on settings, like a configurable max quantity?"
-
Not through
Fielddirectly, becauseField(le=50)is evaluated once, when the module is imported. A limit read from a setting at request time cannot be in it.I have two options for a configurable limit.
- Policy in the service: the model enforces a hard outer limit, such as 1 to 500, and the service compares with
settings.max_qtyand returns a 422 or 409 with a clear message. - Build at start-up: create the model with
create_modelfrom the settings once during start-up. It works, but it makes the code harder to read.
I prefer the first. The principle I follow is that the contract has static limits and the policy has dynamic ones. The OpenAPI document can only show static limits, and a limit that changes per deploy should not be promised in the published schema.
If the limit differs per customer or per restaurant, it is definitely policy, since it needs a database lookup that must not live in a validator (Q23).
- Policy in the service: the model enforces a hard outer limit, such as 1 to 500, and the service compares with
- "How do I constrain a string to a set of values?"
-
I use
Literal["placed", "preparing", "ready"]or anEnum. Both reject any other value with a clear error that lists the allowed ones, and both appear in the OpenAPI document as anenum, so generated clients get a closed set.The choice between them depends on how the set is used. A
Literalis quick and local, good for a value used in one or two places. AnEnum, particularlyStrEnum, is better when the same set appears in several models, the database column and the service logic. It also gives me a place to attach behaviour, likecan_move_to(next_status)for status transitions.A
StrEnummember compares equal to its string, sostatus == "ready"works, and JSON output is the plain string.One evolution caution is that adding a value is safe for the server, but a client with a closed enum may fail on an unknown value. So I document that clients must tolerate new values in responses.
- "Do these checks cost much?"
-
Very little. The constraints are compiled into the Rust validator when the class is defined, so a check such as
gt=0ormax_length=100is a comparison inside native code, a few nanoseconds per field.The one exception is the
patternconstraint, which uses a regular expression. A badly written one can take exponential time on crafted input, known as catastrophic backtracking. A pattern such as(a+)+$against a long string ofafollowed by one wrong character can hang a worker for a long time. Since the input comes from clients, this is a denial-of-service risk.My guidance is to prefer length checks plus simple patterns. A
max_length=64first limits the worst case, since a regex on 64 characters cannot run for long. And I avoid nested repetition in patterns.I also avoid doing complicated format validation in a regex at all when a parser exists. For emails, UUIDs and URLs, the matching Pydantic types do it better than a handwritten pattern.
Q25. "Discriminated unions — when do you need them, and how do they work?"
Reveal answer
Strong answer A union such as Card | Upi | Cash means "one of these shapes". Without help, Pydantic tries each member in turn and reports the errors from all of them if none fits, which is noisy and slow. A discriminated union names one field (the discriminator, here type) whose value says which member to use. Pydantic reads that field first and validates only the matching model.
You need one whenever a payload's shape depends on a type field: payment methods, event types, notification channels. Each member declares the discriminator as a Literal (type: Literal["upi"]), and the field is declared with Field(discriminator="type").
Benefits: faster (one branch), precise errors (only the chosen member's field errors, or one clear "unknown tag" error), and the OpenAPI schema gets a discriminator mapping so generated clients produce proper tagged unions.
Caveat for evolution: a new member is an additive change for the server but older clients will reject payloads with an unknown tag. I document that clients must ignore unknown event types when the server sends unions.
Picture it A payment union with a valid payload, a wrong field inside the right member, and an unknown type, then the same wrong payload without a discriminator.
The setup: Card, Upi, Cash models with type literals.
from typing import Annotated, Literal
from pydantic import BaseModel, Field, ValidationError, TypeAdapter
class Card(BaseModel):
type: Literal["card"]
last4: str
class Upi(BaseModel):
type: Literal["upi"]
vpa: str
class Cash(BaseModel):
type: Literal["cash"]
Payment = Annotated[Card | Upi | Cash, Field(discriminator="type")]
ta = TypeAdapter(Payment)
print(type(ta.validate_python({"type": "upi", "vpa": "asha@bank"})).__name__)
for bad in ({"type": "upi", "vpa": 5}, {"type": "crypto"}):
try: ta.validate_python(bad)
except ValidationError as e:
print(len(e.errors()), "error(s):", e.errors()[0]["type"], e.errors()[0]["loc"], "|", e.errors()[0]["msg"][:62])
plain = TypeAdapter(Card | Upi | Cash)
try: plain.validate_python({"type": "upi", "vpa": 5})
except ValidationError as e: print("without discriminator:", len(e.errors()), "errors, one per union member")Make the invisible visible: Run it.
Upi
1 error(s): string_type ('upi', 'vpa') | Input should be a valid string
1 error(s): union_tag_invalid () | Input tag 'crypto' found using 'type' does not match any of th
without discriminator: 4 errors, one per union memberWhat you see: The valid UPI payload became a Upi object. The bad vpa gave one error located at ('upi', 'vpa'). The unknown type gave union_tag_invalid. Without the discriminator the same bad payload produced four errors, one for each union member.
Why: Four errors for one mistake is what a client sees without a discriminator. One precise error is what you can show on a form.
Plain union
Tries every member.
Payment = Card | Upi | Cash
# bad vpa -> 4 errors, one per member
# slower: tries each model in orderDiscriminated
Reads the tag first.
Payment = Annotated[Card | Upi | Cash,
Field(discriminator="type")]
# bad vpa -> 1 error at ('upi', 'vpa')The shift: A type tag in the data lets the parser choose the shape instead of guessing it.
Land it I use a discriminated union whenever the payload carries a type tag, for speed, one precise error, and a tagged union in the generated client.
- "Can the discriminator be nested or computed?"
-
The discriminator must be a field that exists on each member of the union, usually a
Literalor an enum. It is a plain field that Pydantic reads first, so it cannot be computed in the same way, and cannot be buried inside another object in the simple form.For cases where the tag is not a simple field, Pydantic offers callable discriminators:
Discriminator(func)together withTag("name")on each member.I use callable discriminators only for legacy payloads that cannot be changed, because they push logic into code that the OpenAPI document cannot describe as clearly.
For new APIs I design the payload with an explicit tag field at the top level of each variant, since the contract is then obvious to readers and to generated clients.
- "How does this appear in OpenAPI and generated clients?"
-
It appears as a
oneOflist of the member schemas plus adiscriminatorobject naming the tag field, with amappingfrom each tag value to its schema. Pydantic generates this automatically from the discriminated union.Client generators for TypeScript, Kotlin, Java and others read that and produce a tagged union type. In TypeScript,
switch (payment.type)then narrows the type: insidecase "upi"the compiler knows there is avpafield and nocard_number.Without a discriminator, the schema is a plain
anyOf. The generated client then has to guess which variant it has, which usually means a union with no narrowing and a lot of runtime checks.So the discriminator pays off twice: the server validates faster and gives precise errors, and every client gets safe types for free. I check this by generating a client once from the exported spec, and reading the generated type, before telling client teams it is ready.
- "What happens when I add a payment method later?"
-
It depends on who consumes the union. The server side is easy: add a new member, such as
Wallet, with its owntypeliteral. Old servers reject the new tag, but old clients never send it, so request bodies are fine.The risk is the other direction, when the server sends unions, as with event payloads. An old client may crash or drop a message when it meets a tag it does not know. That is a breaking change in disguise.
So I take three steps. I tell client developers, in the documentation, to handle unknown types gracefully: ignore or log them and not fail. I add new tags in a minor version, never as a replacement of an existing one. And for important cases I let clients opt in, for example with a header or a version, before they receive new event types.
The additive rule is the same one I use for adding fields. Adding is safe if the readers are tolerant, so I make tolerance a written requirement of the contract.
- "Is
Literalthe only way to tag?" -
No. An
Enummember works as the tag too, and it is better when the same set of values is used in other places, such as a database column, a service switch or another model. Then there is a single definition of the allowed tags.A
Literalis simpler when the tag is specific to one variant. Each member declarestype: Literal["upi"], which doubles as its identity, and a type checker can narrow on it.For storage, I keep the tag as a normal column, say
method_type, and the member's data in a JSON column. When reading it back, I validate the pair with the same union, using aTypeAdapterover the union type, so the stored data goes through the same rules as new data.That last step matters over time. Stored rows can be years old, and a validation on read is where an incompatible change shows up as an error with a field path, not as a crash somewhere deep in business code.
Q26 · Scenario. "The frontend wants camelCase and the Python code wants snake_case. Configure it."
Reveal answer
Strong answer Keep snake_case inside Python and translate at the boundary with an alias generator. In the model config set alias_generator=to_camel (from pydantic.alias_generators) and populate_by_name=True. Pydantic then reads menuItemId from incoming JSON, exposes it as menu_item_id in Python, and (with by_alias=True) writes camelCase on the way out.
FastAPI serialises responses by alias by default (response_model_by_alias=True), so once the model has an alias generator, the JSON that leaves your server is camelCase without extra work. For request bodies, aliases apply automatically too.
Put this in a shared base class (class CamelModel(BaseModel)) that all request and response models inherit, so nobody forgets it. Nested models need the same config, which a shared base gives them for free (a trap: configuring only the top-level model leaves nested keys snake_case).
OpenAPI then documents the camelCase names, so generated clients are consistent. Query parameters and headers are not covered by model config; give those explicit alias= values if needed.
Picture it A model with an alias generator, validated from camelCase, accepted by Python name too, and served through FastAPI.
The setup: OrderLineOut with to_camel, populate_by_name=True.
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel
class OrderLineOut(BaseModel):
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True)
menu_item_id: int
price_cents: int
l = OrderLineOut.model_validate({"menuItemId": 7, "priceCents": 450}) # camelCase in
print("python attrs:", l.menu_item_id, l.price_cents)
print("snake in too:", OrderLineOut(menu_item_id=7, price_cents=450).model_dump())
print("dump default:", l.model_dump())
print("by_alias :", l.model_dump(by_alias=True))
import asyncio, httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/line", response_model=OrderLineOut, response_model_by_alias=True)
def line(): return {"menu_item_id": 7, "price_cents": 450}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
print("FastAPI JSON:", (await c.get("/line")).json())
asyncio.run(main())Make the invisible visible: Run it.
python attrs: 7 450
snake in too: {'menu_item_id': 7, 'price_cents': 450}
dump default: {'menu_item_id': 7, 'price_cents': 450}
by_alias : {'menuItemId': 7, 'priceCents': 450}
FastAPI JSON: {'menuItemId': 7, 'priceCents': 450}What you see: camelCase input worked; snake_case kwargs also worked (populate_by_name); a plain model_dump() stays snake_case; by_alias=True gives camelCase; and the FastAPI response was camelCase automatically.
Why: There are two worlds, and the alias is the border crossing: Python code never sees camelCase and clients never see snake_case.
Naive
Rename fields in Python.
class LineOut(BaseModel):
menuItemId: int # ❌ camelCase in Python
priceCents: intCorrect
Alias at the boundary.
class CamelModel(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel,
populate_by_name=True)The shift: Convert names once at the edge so the inside of the program follows one convention.
Land it I keep snake_case in Python and use a shared CamelModel base with an alias generator, so the JSON contract and the code style never conflict.
- "Why
populate_by_name=True?" Short answer: it lets the model be built with Python names as well as with the wire names. Without it, only the alias is accepted when you construct the model.
Here is the mechanism. When
alias_generator=to_camelis set, Pydantic registersmenuItemIdas the one name for input. A call likeOrderLineOut(menu_item_id=1)then fails with a "field required" error, because the field "menuItemId" was not given. Settingpopulate_by_name=Truetells Pydantic to accept either name.The effect shows up in three places. Unit tests can write natural Python. Service code that builds response objects from ORM rows (for example with
from_attributes) does not have to speak camelCase. And clients still send and receive the alias, because output followsby_alias, not this setting.One thing to be aware of: in recent Pydantic versions there is a finer switch,
validate_by_namewithvalidate_by_alias, andpopulate_by_nameis kept for compatibility. I check the docs for my installed version. My rule is simple: if the code base has an alias generator, it also haspopulate_by_name=Trueon the same shared base.- "Does the alias apply to
model_dump()?" Not by default.
model_dump()returns Python field names unless you passby_alias=True. That is the opposite of what FastAPI does for responses, where the serialiser is told to use aliases for you.The trap is a hand-made response. If I write
json.dumps(model.model_dump())inside a customResponse, the client getsmenu_item_idand the contract breaks, even though the same model returned from a normal route would be camelCase. Here is a run on a small model with an alias generator.q27_dump_options.py (output)runs offlinemodel_dump() {'menu_item_id': 7, 'note': None, ...} model_dump(by_alias=True, mode="json") {'menuItemId': 7, 'note': None, 'tip': '0.50'}The second line is what a client should see: camelCase keys and JSON-safe values. When I serialise by hand I always write
model_dump(by_alias=True, mode="json"), or better,model_dump_json(by_alias=True). I also add a test that compares a hand-built response with the one FastAPI builds from the same model (Q27).- "What about errors, do they show alias or field name?"
The error
locuses the alias, because it names where the client put the bad value. If the client sentmenuItemIdand it was wrong, the path says["body", "lines", 0, "menuItemId"]. That is the name the client can search for in its own code, so it is the right one to show.This has one cost for you. Your own code and logs talk in snake_case, so a developer reading the log has to map the name by eye. I accept that for responses, and I do two things for operations.
- Log the raw path: record the full
loclist exactly as Pydantic gives it, with no translation, so search in the logs matches what the client saw. - Keep the stable code: record the error
type(such asmissingorgreater_than) next to the path, because that code does not change with naming style. - Test it once: one test posts a bad camelCase body and asserts the alias in
loc, so a change to the generator cannot silently change the error contract.
Clients parse these paths, so treat the format as part of the API.
- Log the raw path: record the full
- "Should I add this to every model, even internal ones?"
No. Only models that cross the HTTP boundary need it. Request bodies and response bodies are the public contract, so they inherit from
CamelModel. Everything behind the service layer stays in plain Python style.Think of three kinds of model. First, HTTP models: they carry the alias generator and, usually,
extra="forbid"on requests. Second, service-level objects (dataclasses or plain models passed between functions): no aliases, because nobody outside the process sees them. Third, ORM models: they follow the database column names, and aliases there would only confuse queries.Why this matters in practice: an alias on an internal model costs nothing at runtime, but it blurs the line. A developer sees camelCase keys in a log and cannot tell whether the data came from the wire or from inside. Using the base class only at the edge turns it into a signal: "if it inherits CamelModel, changing it is changing the public API, so get a review".
The trap to avoid is the reverse: a nested model that is part of a response but forgot the base. Its keys stay snake_case inside an otherwise camelCase body. A contract test that scans the response JSON for underscores catches this in one line.
Q27. "model_dump options: exclude_unset, exclude_none, by_alias, mode="json"."
Reveal answer
Strong answer model_dump() turns a model into a dict. The four options answer four different questions.
mode="json" asks: "give me only JSON-safe values". Without it you get Python objects (Decimal, datetime, UUID); with it they become strings and numbers, so the dict can go straight into json.dumps or a JSON column. by_alias=True asks: "use the wire names" (camelCase or custom aliases) rather than Python attribute names.
exclude_unset=True asks: "leave out fields the caller did not set". This is the PATCH tool (Q28): a field set to None by the caller is kept; a field left at its default is dropped. exclude_none=True asks: "leave out anything that is None", which cannot tell "client sent null" from "client sent nothing", so it is wrong for PATCH but handy for trimming responses.
exclude_defaults drops values equal to the default. include/exclude select fields by name. model_dump_json() is the direct route to a JSON string, faster than json.dumps(model_dump(mode="json")).
Picture it One order model dumped five ways.
The setup: A model with an optional note, a Decimal, a UTC datetime and an aliased field.
from datetime import datetime, timezone
from decimal import Decimal
from pydantic import BaseModel, Field
class Order(BaseModel):
id: int
note: str | None = None
total: Decimal = Decimal("0")
placed_at: datetime = datetime(2026, 11, 24, 9, 30, tzinfo=timezone.utc)
cust_id: int = Field(default=7, alias="customerId")
o = Order(id=1, customerId=7)
print("python :", o.model_dump())
print('mode="json" :', o.model_dump(mode="json"))
print("exclude_none:", o.model_dump(exclude_none=True).keys())
print("exclude_unset:", o.model_dump(exclude_unset=True), "(only what the caller set)")
print("by_alias :", o.model_dump(by_alias=True, mode="json")["customerId"])
print("json string :", o.model_dump_json(exclude={"note"}))Make the invisible visible: Run it.
python : {'id': 1, 'note': None, 'total': Decimal('0'), 'placed_at': datetime.datetime(2026, 11, 24, 9, 30, tzinfo=datetime.timezone.utc), 'cust_id': 7}
mode="json" : {'id': 1, 'note': None, 'total': '0', 'placed_at': '2026-11-24T09:30:00Z', 'cust_id': 7}
exclude_none: dict_keys(['id', 'total', 'placed_at', 'cust_id'])
exclude_unset: {'id': 1, 'cust_id': 7} (only what the caller set)
by_alias : 7
json string : {"id":1,"total":"0","placed_at":"2026-11-24T09:30:00Z","cust_id":7}What you see: Plain model_dump() keeps Decimal('0') and a datetime object. mode="json" turns the decimal into the string '0' and the datetime into '2026-11-24T09:30:00Z'. exclude_unset kept only id and cust_id, the two fields that were actually passed.
Why: Decimal becomes a string on purpose: a JSON number is a binary float in most clients, and money must not pass through one (Q113). ISO 8601 with an offset is the datetime form every client can parse.
Naive
Dump and hope.
body = json.dumps(order.model_dump())
# ❌ TypeError: Decimal is not JSONCorrect
Say what you want.
body = order.model_dump_json(by_alias=True)
# or
d = order.model_dump(mode="json")The shift: Choose the dump mode by destination: Python code gets objects, the wire gets JSON-safe values.
Land it I pick mode, by_alias, exclude_unset and exclude_none by what the output is for, and I never use exclude_none for PATCH.
- "Why is
exclude_nonewrong for a PATCH?" Because the client's meaning of
nullis lost. In a PATCH,{"note": null}says "clear the note".exclude_noneremoves every field whose value isNone, so that instruction disappears from the dict and the note stays as it was. The client can never clear a field.The reverse problem also exists:
exclude_nonecannot tell "client sent null" from "client sent nothing", because both giveNonein the model. The model does remember which is which, inmodel_fields_set, and onlyexclude_unsetuses that memory. Here is the real output for a model with a note set to null.q27_dump_options.py (output)runs offlinemodel_dump(exclude_unset=True) {'menu_item_id': 7, 'note': None} model_dump(exclude_none=True) {'menu_item_id': 7, 'tip': Decimal('0.50')}With
exclude_unsetthe explicit null stays (and the unsenttipgoes). Withexclude_nonethe null is gone and a default sneaks in. I useexclude_noneonly to trim optional fields from responses (Q28).- "What does
exclude_unsettrack?" It tracks the field names that the caller passed in when the model was built or validated. Pydantic keeps that set on the object as
model_fields_set.exclude_unset=Truesimply asks the dump to keep only the names in that set.Three details are worth knowing, and each one is a likely follow-up in itself.
- Defaults do not count: a field the caller left out is not in the set, even though the model has a value for it. In the run above,
tiphas a value, yet it is not in the set{'menu_item_id', 'note'}. - Naming counts, not value: if the caller sends a field with exactly its default value, it is still in the set, because the caller named it. For a PATCH that is right: "set qty to 1" is an instruction.
- Assignment adds to the set: setting
model.note = "x"after construction addsnoteto the set, so later dumps include it.
Because of this, a model built in code (not parsed from a request) may have a surprising set. I use
exclude_unsetonly on models that came from a request body.- Defaults do not count: a field the caller left out is not in the set, even though the model has a value for it. In the run above,
- "Why does
Decimalserialise as a string?" Because a JSON number is not safe for exact decimals. Many readers parse JSON numbers as binary floats, and
0.1 + 0.2style errors follow. Pydantic therefore writes aDecimalas a string,"0.50", which keeps every digit. In the run above, the dump withmode="json"shows'tip': '0.50'.That is safe, but it surprises clients that expect a number, and every client then has to parse the string with a decimal type. If one client forgets and uses a float, you are back to the original problem.
For money I avoid the question entirely and use integer cents:
total_cents: int. A whole number of paise or cents is exact in JSON, in every language, and in the database, and adding or comparing two amounts is plain integer arithmetic. The cost is that the name must say the unit, and display code divides by 100 at the very last step.When a decimal really is needed (a tax rate, a weight), I keep
Decimalwith a string on the wire and document it in OpenAPI so generated clients use a decimal type (Q113).- "Is
model_dump_jsonreally faster thanjson.dumps?" Yes, for the reason you would expect.
model_dump_json()goes from model to JSON text in one step inside Pydantic's Rust core. The other route,json.dumps(model.model_dump(mode="json")), first builds a full dict of Python objects and then lets Python'sjsonmodule walk it again. That is two passes and many temporary objects.I would not quote a ratio without measuring on my own models, because the gain depends on the shape: big lists of small objects gain most. The point I can state safely is the mechanism, not a number.
In a FastAPI route I rarely call it myself. When a route declares
response_model(or a return annotation), FastAPI validates the returned object against that model and serialises it with the same fast path. That is also why it is not worth swapping in a different JSON response class: the model path is already the quick one (andORJSONResponseis deprecated in 0.141).I call
model_dump_json()directly for things outside HTTP, such as writing a message to a queue or a JSON column, withby_aliaschosen deliberately.
Q28 · Scenario. "A PATCH endpoint sets every omitted field to null. Fix it."
Reveal answer
Strong answer The endpoint turns the body model into a dict and applies it with model_dump(). A model with optional fields fills the missing ones with their defaults (None), and the update then overwrites the stored values with None. The client only meant to change status; it deleted the note and the tip.
The fix is model_dump(exclude_unset=True): only the fields the client actually sent are in the dict. A field the client sent as null is still there, so explicit clearing works. Then apply those changes to the stored object, inside one transaction.
Design rules around it. PATCH is partial (merge), PUT replaces the whole resource; both need a clear contract (Q103). Fields that must never become null should not be nullable in the patch model, or a validator should reject explicit nulls for them. Some fields (status) need transition rules checked in the service, not by blindly copying values.
A second subtle bug: a model with a default other than None (for example qty: int = 1) would silently reset to 1 on every PATCH using the naive version. exclude_unset fixes that too.
Picture it The same PATCH {"status": "ready"} against two endpoints, and then an explicit null.
The setup: A dict stands in for the database row; the body model has three optional fields.
import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
DB = {1: {"status": "preparing", "note": "no onions", "tip_cents": 50}}
class OrderPatch(BaseModel):
status: str | None = None
note: str | None = None
tip_cents: int | None = None
@app.patch("/naive/{oid}")
def naive(oid: int, body: OrderPatch):
DB[oid].update(body.model_dump()) # ❌ TRAP: omitted fields become None
return DB[oid]
@app.patch("/fixed/{oid}")
def fixed(oid: int, body: OrderPatch):
DB[oid].update(body.model_dump(exclude_unset=True)) # ✅ only fields the client sent
return DB[oid]
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for path in ("naive", "fixed"):
DB[1] = {"status": "preparing", "note": "no onions", "tip_cents": 50}
print(path, (await c.patch(f"/{path}/1", json={"status": "ready"})).json())
DB[1] = {"status": "preparing", "note": "no onions", "tip_cents": 50}
print("fixed, explicit null clears the note:", (await c.patch("/fixed/1", json={"note": None})).json())
asyncio.run(main())Make the invisible visible: Run it.
naive {'status': 'ready', 'note': None, 'tip_cents': None}
fixed {'status': 'ready', 'note': 'no onions', 'tip_cents': 50}
fixed, explicit null clears the note: {'status': 'preparing', 'note': None, 'tip_cents': 50}What you see: The naive endpoint replied with note: None and tip_cents: None, wiping data. The fixed endpoint changed only status. The last line shows an explicit {"note": null} clearing just the note.
Why: exclude_unset separates three client intents that None alone confuses: "do not touch" (key absent), "clear" (key present with null), "set" (key with a value).
Naive
Applies defaults too.
changes = body.model_dump()
row.update(changes) # ❌ omitted -> NoneCorrect
Applies only what was sent.
changes = body.model_dump(exclude_unset=True)
row.update(changes) # ✅ omitted untouchedThe shift: "Missing" and "null" are different messages; the model remembers which fields the client named.
Land it I apply PATCH bodies with exclude_unset=True so absent means untouched and explicit null means clear.
- "How do I stop a client from clearing a required field?"
I make "null" mean different things for different fields, and I reject it where it is wrong. The tempting fix, writing
status: str = None, is a trap: it silently allows null and also hides the type.The clean way is to keep the patch field optional (so it can be omitted) but to refuse an explicit null with a validator. The validator sees the value only when the field was sent, because a missing field never reaches it unless you ask for defaults to be validated.
patch modelclass OrderPatch(BaseModel): status: str | None = None note: str | None = None @field_validator("status") @classmethod def status_not_null(cls, v): if v is None: raise ValueError("status cannot be null") return vNow
{"status": null}returns 422,{"note": null}clears the note, and{}changes nothing. For larger models I keep the list of non-clearable names in one place, so the rule is visible and tested rather than scattered.- "Should status changes be a plain PATCH?"
No. A status is a state machine, so a PATCH should not be a free write. The order moves along
placed,preparing,ready,delivered, and not every jump is allowed. Settingdeliveredon an order that is stillplacedmeans a rider never picked it up, and the data is wrong from then on.My design has three parts.
- Allowed moves in one table: a dictionary from current status to the set of next statuses, kept in the service.
- The check inside the transaction: read the order with a lock (or use a version column), look the move up, and refuse with 409 and a problem body naming both states if it is not allowed.
- Side effects with the move: notify the customer or write an event in the same transaction, so a status never changes without its record.
For a real transition I often prefer a named action, such as
POST /orders/{id}/cancel, because the name carries rules and permissions (only the customer, only before preparing). The endpoint stays thin: it forwards the change and the service decides. The trap is blindly copying a client value into the column.- "How do I handle concurrent PATCHes?"
Two clients patching the same order can overwrite each other: both read version 3, both write, and the second write silently wipes the first one's change. The fix is optimistic concurrency, which means "assume no conflict, but detect one".
The mechanism is a
versioncolumn (or an ETag derived from it). The client sends the version it saw, usually in anIf-Matchheader, and the update only matches if nobody moved it on.guarded updateUPDATE orders SET note = :note, version = version + 1 WHERE id = :id AND version = :v; -- 0 rows changed: someone else got there firstIf the row count is zero, the service returns 412 Precondition Failed (when the client used
If-Match) or 409 Conflict, and the client re-reads and retries. MissingIf-Matchon an endpoint that requires it gets 428 Precondition Required.I choose this over row locks for user-facing edits because nothing is held while a person thinks. Locks (
SELECT ... FOR UPDATE) are better for short, internal read-modify-write steps (Q74, Q104).- "What about JSON Merge Patch or JSON Patch (RFC 7386 / 6902)?"
They are two different standards, and the names are easy to mix up. JSON Merge Patch (RFC 7386) sends a partial document: fields present are set, fields with
nullare deleted, absent fields are untouched. That is exactly whatexclude_unset=Truegives you for a flat object.JSON Patch (RFC 6902) sends a list of operations, such as
{"op": "replace", "path": "/note", "value": "x"}. It is more expressive and can address array elements, move values and test a value before changing it, but clients need a library to build it and the server needs one to apply it safely.Merge Patch has two weaknesses. It cannot set a field to a literal
nullwhen null is a real value, because null means delete. And it replaces whole arrays: you cannot add one order line without resending all of them.For a normal product API I choose merge-style PATCH, use a separate sub-resource for lists (
POST /orders/{id}/lines), and keep the contract short and easy for clients. I reach for JSON Patch only for generic editing tools.
Q29. "What does a 422 response contain, and how do you change its format?"
Reveal answer
Strong answer FastAPI returns 422 Unprocessable Content when the request is syntactically valid HTTP but the data fails validation. The body is {"detail": [ ... ]} and each item has type (a machine code such as missing or greater_than), loc (where: ["body","lines",0,"qty"]), msg (human text), input (the offending value) and sometimes ctx (limits). All errors are reported together.
To change it, register an exception handler for RequestValidationError (from fastapi.exceptions) and return your own response, for example RFC 9457 application/problem+json (Q94). Map each error to a stable shape: field path, error code, message.
Two cautions. The default body includes input, the value the client sent. If a password was typed into the wrong field, you now echo it in the response and perhaps log it; strip input for sensitive routes. And decide whether the format is part of the contract: once clients parse detail[0].loc, changing it is a breaking change.
Also remember that 400 vs 422 is a style choice: many teams use 422 for validation of a well-formed JSON body and 400 for malformed JSON; being consistent matters more than which.
Picture it The default body for a request with two mistakes, then the same request against an app built with a custom handler, then malformed JSON.
The setup: POST /orders with no restaurant_id and qty: 0. The custom handler is registered while the app is built.
import asyncio, httpx, json
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
class Line(BaseModel):
qty: int = Field(gt=0)
class Order(BaseModel):
restaurant_id: int
lines: list[Line]
def make(custom: bool):
app = FastAPI()
@app.post("/orders")
def create(o: Order): ...
if custom: # register handlers while building the app
@app.exception_handler(RequestValidationError)
async def problem(request: Request, exc: RequestValidationError):
errs = [{"field": ".".join(map(str, e["loc"][1:])), "code": e["type"]} for e in exc.errors()]
return JSONResponse({"type": "https://api.quickbite.test/problems/validation", "title": "Invalid request",
"status": 422, "errors": errs}, status_code=422, media_type="application/problem+json")
return app
async def main():
bad = {"lines": [{"qty": 0}]}
for custom in (False, True):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=make(custom)), base_url="http://t") as c:
r = await c.post("/orders", json=bad)
print("custom" if custom else "default", r.status_code, r.headers["content-type"])
print(json.dumps(r.json()))
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=make(False)), base_url="http://t") as c:
r = await c.post("/orders", content=b'{"lines": [', headers={"content-type": "application/json"})
print("malformed JSON ->", r.status_code, r.json()["detail"][0]["type"])
asyncio.run(main())Make the invisible visible: Run it.
default 422 application/json
{"detail": [{"type": "missing", "loc": ["body", "restaurant_id"], "msg": "Field required", "input": {"lines": [{"qty": 0}]}}, {"type": "greater_than", "loc": ["body", "lines", 0, "qty"], "msg": "Input should be greater than 0", "input": 0, "ctx": {"gt": 0}}]}
custom 422 application/problem+json
{"type": "https://api.quickbite.test/problems/validation", "title": "Invalid request", "status": 422, "errors": [{"field": "restaurant_id", "code": "missing"}, {"field": "lines.0.qty", "code": "greater_than"}]}
malformed JSON -> 422 json_invalidWhat you see: The default response lists two errors, each with type, loc, msg, input and (for the limit) ctx. The custom app answers the same mistakes as application/problem+json with a flat errors list of field paths and codes, and no echoed input. Even malformed JSON is a 422 here, with type json_invalid.
Why: Both bodies carry the same facts; only the custom one is a shape you can promise to clients for years. Note that I registered the handler before serving: handlers added after the first request are captured too late.
Default
FastAPI's own body.
{"detail": [{"type": "missing",
"loc": ["body", "restaurant_id"],
"msg": "Field required",
"input": {"lines": []}}]}Custom
A stable error contract.
{"type": ".../problems/validation",
"title": "Request validation failed",
"status": 422,
"errors": [{"field": "restaurant_id",
"code": "missing"}]}The shift: The default body is a debugging aid; a public API should answer with a documented error shape.
Land it I replace the default 422 body with a documented Problem Details shape, and I strip echoed inputs from sensitive routes.
- "Where must I register the handler?"
In
create_app(), before the app takes its first request. The reason is how Starlette works: on the first request (or at start-up) it builds its middleware stack once, and that build reads the table of exception handlers. A handler added to the table after that point is not in the stack, so it never runs and the default 422 comes back.This is a classic "my handler does nothing" bug in tests. A fixture imports the app, then adds a handler, then calls it, and the answer is the old format. The fix is always the same: register before the app is used.
In the canonical app,
app/errors.pyhas one function that registers every handler (validation errors, HTTP exceptions, the catch-all for 500, and the business errors).create_app()calls it once, right after building theFastAPIobject. One place means a new engineer can answer "what happens when X fails?" by reading one file.A second rule: handlers are matched by exception class, most specific first. Registering for
RequestValidationErrordoes not catch Starlette'sHTTPException, so I register each family on purpose and keep a test for each response shape.- "How do I map the
locto a client-friendly field name?" I translate it in the handler, in three small steps, and I keep the original pieces so nothing is lost.
- Split the kind: the first element of
locsays where the value came from:body,query,path,headerorcookie. I move it into its own key,in. - Join the rest: the remaining items become a dotted path.
["body","lines",0,"qty"]turns intolines.0.qty. Numbers are list positions, and clients can map them back to the row they sent. - Keep the code:
type(for examplegreater_thanormissing) becomes the machine-readablecode. Themsgtext becomesmessage, and I tell clients it may change wording between releases.
The handler returns something like
{"errors": [{"field": "lines.0.qty", "in": "body", "code": "greater_than", "message": "..."}]}inside a Problem Details body.I never build client logic on the message text, and I document the code list. If a model uses aliases,
localready holds the alias, so the dotted path matches the JSON the client wrote.- Split the kind: the first element of
- "Does 422 appear in my OpenAPI automatically?"
Yes, for any route that has parameters or a body. FastAPI adds a 422 response to the operation, pointing at a schema called
HTTPValidationError, which has adetaillist ofValidationErroritems.Once I replace the body shape in a handler, that documented schema is wrong. Generated clients would build a type for the old shape and fail to parse the new one at runtime. The fix is to tell OpenAPI what is really sent.
documenting the real 422router = APIRouter( responses={422: {"model": Problem, "description": "Validation failed"}}, )Setting it once on the router, or on the app, covers every route under it. Other errors should be listed the same way (401, 403, 404, 409, 429), so generated clients get a type for each failure (Q36).
The check I add to CI: export
app.openapi(), search forHTTPValidationError, and fail if it is still referenced after I changed the format. A stale documented error is a quiet contract bug, because nothing in the server fails.- "400 or 422 for a bad JSON syntax?"
In this FastAPI version, malformed JSON is a 422 too, not a 400. The same
RequestValidationErrorcomes back withtype: "json_invalid". I ran it, with a broken body and a valid body with a bad value.q29_422.py (output)runs offline422 ['body', 'qty'] greater_than 422 json_invalidStrict HTTP reading says a syntax error is a 400 Bad Request, and some teams remap
json_invalidto 400 in the handler. Others leave it. Both are fine if the policy is written down.My choice: keep one family of codes so clients have one rule, "4xx with a Problem body means fix the request". If I do remap, I do it by the
typecode in the validation handler, never by guessing from the message text. And I test both cases, because the first line shows a typical value error while the second shows a syntax error, and each takes a different path through Pydantic. Clients should treat both as "do not retry unchanged".
Q30. "Bean Validation versus Pydantic."
Reveal answer
Strong answer Both check data at the boundary, but they differ in when and what they return. Bean Validation (Jakarta) validates an already-constructed Java object when you ask (@Valid), using annotations like @NotNull, @Min, @Size. Pydantic parses: it takes raw input (dict or JSON), converts types, and either returns a valid, typed object or raises. You never hold an invalid Pydantic model.
Differences that matter. Pydantic converts ("42" to 42), Bean Validation does not (Jackson does the conversion earlier). Pydantic reports all errors with exact locations. Nulls: in Java every field can be null unless annotated; in Pydantic a field with no default is required and None is only allowed if the type says so. Custom rules: Java uses custom constraint annotations plus validator classes; Pydantic uses field_validator and model_validator functions.
Both integrate with the web layer: Spring returns 400 with MethodArgumentNotValidException handled by a @ControllerAdvice; FastAPI returns 422 with RequestValidationError handled by an exception handler.
The shift is to parse, don't validate: after the boundary, code can trust the types, and Pydantic makes that cheap.
Picture it One DTO with three constraints, and the exact errors Pydantic reports.
The setup: item_id >= 1, qty between 1 and 50, note at most 140 characters; the input breaks all three.
from typing import Annotated
from pydantic import BaseModel, Field, EmailStr, ValidationError
class OrderLineIn(BaseModel):
item_id: Annotated[int, Field(ge=1)] # @Min(1) @NotNull is implicit: no default = required
qty: Annotated[int, Field(ge=1, le=50)] # @Min(1) @Max(50)
note: Annotated[str, Field(max_length=140)] = "" # @Size(max=140), optional
try: OrderLineIn(qty=99, note="x" * 200)
except ValidationError as e:
for x in e.errors(): print(".".join(map(str, x["loc"])), "|", x["type"], "|", x["msg"])Make the invisible visible: Run it.
item_id | missing | Field required
qty | less_than_equal | Input should be less than or equal to 50
note | string_too_long | String should have at most 140 charactersWhat you see: Three errors came back together, each with the field, a stable type and a message. The missing item_id is reported as missing, because a field without a default is required (Bean Validation's @NotNull is implicit).
Why: You get a complete list from one call, and the same model that validated the input is the typed object you pass to the service.
Bean Validation
Annotations, checked on @Valid.
// illustrative
record LineIn(
@NotNull Long itemId,
@Min(1) @Max(50) int qty,
@Size(max = 140) String note) {}Pydantic
Types are the constraints.
class LineIn(BaseModel):
item_id: int
qty: Annotated[int, Field(ge=1, le=50)]
note: Annotated[str,
Field(max_length=140)] = ""The shift: Bean Validation checks an object you built; Pydantic refuses to build an invalid one.
Land it I describe Pydantic as parsing into valid typed objects at the boundary, where Bean Validation checks objects after construction.
- "Where do nulls differ in practice?"
The difference is what the language does with a missing value, and it removes a whole group of bugs. In Java, a JSON object with no
notebecomes an object whose field isnull. It passes unless someone remembered@NotNull. Later, some code calls a method on it and you get a NullPointerException far from the cause.In Pydantic the rules are stricter by default.
- No default means required: a field
name: strthat is missing gives a "field required" error at the boundary. - Null needs permission:
Noneis accepted only when the type says so, as instr | None. Anullsent for a plainstris rejected. - Optional is not the same as nullable:
note: str | Nonewith no default is still required, but may be null.note: str | None = Nonemay be omitted.
This last case is a common interview trap. After parsing, the type tells the truth: if the annotation is
str, the value is a real string, and code can use it without a defensive check. I read a model's annotations as its null contract.- No default means required: a field
- "Can I express groups, like "create versus update" rules?"
Bean Validation has validation groups: you mark constraints as belonging to
CreateorUpdateand tell@Validatedwhich group to run. It works, but the rules for one endpoint end up scattered across one class with many annotations and group markers.In Pydantic I do not use groups. I write one model per use:
OrderCreate,OrderPatch,OrderOut. Each carries exactly the rules of its endpoint.Here is why I prefer that. First, the contract is visible: reading
OrderPatchtells you which fields can change and which are optional, with no cross-reference to group names. Second, OpenAPI is accurate, because each endpoint has its own schema, so generated clients get separate types and do not see a field as optional that is required on create. Third, a change to the update rules cannot break create by accident.The cost is some repetition. I reduce it with small shared field types, such as
Annotated[str, Field(max_length=200)], or with a common base for the fields that really are identical. I never share by making Patch inherit from Create and loosening it, since that tends to leak rules (Q32).- "How do custom constraints compare?"
The Python version is usually shorter. Here are the two side by side.
In Java you write an annotation type (with
@Constraint(validatedBy=...)), then a class that implementsConstraintValidator, then apply the annotation to a field. Three parts, in two files, for something like "pin code is six digits".In Pydantic there are two common routes. A method on the model,
@field_validator("pin"), is best for a rule used once. For a rule used in many places, I define a reusable type.reusable constraintdef six_digits(v: str) -> str: if not (v.isdigit() and len(v) == 6): raise ValueError("must be 6 digits") return v Pin = Annotated[str, AfterValidator(six_digits)]Any model can now write
pin: Pin, and OpenAPI still shows a string. The function runs inside the validation pipeline after the type check, so it receives a realstr.Keep these functions pure. A rule that needs the database (is this restaurant open?) does not belong in a validator, because validators cannot await and should not do I/O (Q23).
- "Does Pydantic validate on every attribute access?"
No. Validation happens when the object is created, from a dict or JSON. After that, an instance is an ordinary Python object, and reading an attribute is a plain lookup with no checks. So it costs nothing to pass validated models around.
That has two consequences worth stating in an interview.
First, assignment is not checked by default. If you write
order.qty = "banana", Pydantic stores it without complaint, and the object is now invalid. If you want checks on assignment, setvalidate_assignment=Truein the model config. That makes every write run the field's validators again, at some cost, so I turn it on for objects that code mutates and leave it off for request models that are only read.Second, the guarantee "you never hold an invalid model" is about construction. It stays true in practice because request and response models are not modified. The mutable thing in the service is the ORM object, which has its own constraints in the database.
My habit: treat request models as read-only, copy with
model_copy(update=...)when a changed version is needed, and validate again if the update came from outside.
Q31. "How do you load configuration with pydantic-settings, and how do you handle secrets?"
Reveal answer
Strong answer pydantic-settings gives you a BaseSettings class. Each attribute is read from an environment variable (with an optional prefix like QB_), then from a .env file for development, then from its default, and is validated like any Pydantic model. A bad value stops the process at start-up with a clear error, not at 3 a.m. on the first request that needs it.
Secrets use SecretStr (or SecretBytes): repr() and logs show **********, and you call .get_secret_value() only where the value is really used. Secrets are injected by the platform (Kubernetes secrets, a cloud secret manager, Docker secrets) as environment variables or files; they never live in the repository or the image. A .env file is for laptops and is git-ignored.
Expose settings through one cached function, get_settings() with @lru_cache, and inject it with Depends(get_settings). One instance per process means the environment is parsed once, and tests override it with app.dependency_overrides or by clearing the cache.
The canonical app has Settings with database_url, jwt_issuer, jwt_audience, jwt_public_key and db_pool_size.
Picture it Settings read from environment variables set inline, a masked secret, a cached instance, and a rejected value.
The setup: Prefix QB_; db_pool_size limited to 1–50; jwt_secret is a SecretStr.
import os
from functools import lru_cache
from pydantic import SecretStr, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="QB_", env_file=".env", extra="ignore")
database_url: str = "sqlite:///./dev.db"
jwt_issuer: str = "https://id.quickbite.test"
db_pool_size: int = Field(default=5, ge=1, le=50)
jwt_secret: SecretStr
@lru_cache
def get_settings() -> Settings: return Settings()
os.environ["QB_JWT_SECRET"] = "s3cr3t-value"
os.environ["QB_DB_POOL_SIZE"] = "3"
s = get_settings()
print(s.database_url, s.db_pool_size, repr(s.jwt_secret), "->", s.jwt_secret.get_secret_value()[:3] + "...")
print("same object on second call:", get_settings() is s)
os.environ["QB_DB_POOL_SIZE"] = "500"; get_settings.cache_clear()
try: get_settings()
except Exception as e: print(type(e).__name__, "|", str(e).splitlines()[1:3])Make the invisible visible: Run it.
sqlite:///./dev.db 3 SecretStr('**********') -> s3c...
same object on second call: True
ValidationError | ['db_pool_size', " Input should be less than or equal to 50 [type=less_than_equal, input_value='500', input_type=str]"]What you see: The pool size came from QB_DB_POOL_SIZE=3. Printing the secret shows SecretStr('**********'). The second get_settings() returned the very same object. Setting the pool to 500 and clearing the cache gave a ValidationError naming db_pool_size.
Why: Configuration errors become start-up failures with a field name. A cached instance means one parse, and the cache_clear() call is the hook tests use.
Spring Boot
application.yml and properties class.
// illustrative
@ConfigurationProperties("quickbite")
record Settings(String jwtIssuer,
@Min(1) @Max(50) int poolSize) {}FastAPI
Settings class from the environment.
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="QB_")
jwt_issuer: str
db_pool_size: int = Field(5, ge=1, le=50)The shift: Both bind typed, validated properties from the environment; Python defaults to environment variables, Spring to files.
Land it I load config from the environment through a validated, cached Settings object, keep secrets as SecretStr injected by the platform, and fail fast on bad values.
- "How do I handle different environments?"
One image, many environments: only the environment variables change. The code has no
if ENV == "prod"branches, because every such branch is a path that is tested in one place and run in another.Concretely, the same
Settingsclass readsQB_DATABASE_URL,QB_DB_POOL_SIZEand the rest. Dev points at a local database, staging at a small shared one, production at the real one, and the platform (Kubernetes config maps and secrets) injects the values.Behaviour that really differs is turned into an explicit setting with a safe default. For example
docs_enableddefaults to false in production,debugdefaults to false, and a developer turns them on in.envon their laptop. The setting name says what it does, so a reader never needs to know which environment they are in.I add one guard: a validator that refuses a dangerous combination, such as
debug=Truewith a production-looking database host. That fails at start-up, which is the cheapest place to find a mistake (Q142).- "Why
lru_cacheonget_settings?" Without the cache, every request that depends on settings would build a new
Settingsobject. That re-reads the environment, parses the.envfile from disk and runs all validators, for values that do not change while the process lives. The cost is small per call but real, and the file read is the part that hurts.@lru_cacheonget_settings()makes the first call build the object and every later call return the same one. Think of it as a lazy singleton with no class around it.Testing is the thing to get right, because the cache also remembers the old value.
- Override the dependency:
app.dependency_overrides[get_settings] = lambda: Settings(database_url="sqlite://"). This is my default, since it touches only the app. - Or clear the cache: after
monkeypatch.setenv(...), callget_settings.cache_clear(), and clear again in teardown so the next test starts clean.
The trap is a test that sets an environment variable and sees no effect, because an earlier test filled the cache.
- Override the dependency:
- "How do I handle rotating secrets?"
Environment variables are read once, when the process starts. So rotating a secret held in settings means starting new processes with the new value. On Kubernetes that is a rolling deploy: new pods start with the new secret while old pods drain, so users see no gap, as long as the old and new secrets are both valid for a short overlap.
That overlap is the key design point. A good rotation has three steps: add the new secret next to the old one, switch the application, then remove the old one.
Some secrets rotate too often for that. Signing keys are the usual case. A token service publishes its public keys at a JWKS URL, and the key set changes on a schedule. For those I do not put the key in settings. The app fetches the key set at runtime, caches it for a few minutes, and refetches when it sees a key id it does not know. That way a new key works without a restart (Q82).
Database passwords need a plan too: the pool holds open connections, so new connections pick up the change only after the engine is rebuilt or the process restarts.
- "What if a secret leaks into a log?"
Assume it will, and design so that one slip does not expose it.
SecretStrhides the value inrepr()andstr(), so printing the settings object shows**********. That protects the most common accident, a log line likelogger.info(settings).It does not protect everything.
- Dumps:
model_dump_json()keeps secrets masked, butget_secret_value()calls and some custom serialisers write them in clear text. Exclude secret fields from anything that is logged. - Exceptions: a driver error that includes the connection string will include the password, as plain text from the raw value. I strip or mask the URL before it is logged.
- Request echo: the default 422 body repeats the client's input, so a password typed in the wrong field comes back in the response and may be logged (Q29).
Two process rules help: scan logs in CI for key-like prefixes, and when a leak is confirmed, rotate the secret at once instead of arguing about who saw it.
- Dumps:
Q32 · Design. "Design the request and response models for creating an order with lines, a delivery address and a payment method."
Reveal answer
Strong answer I apply the three-model rule: a request model (what the client may send), a response model (what the server promises to return) and the ORM model (what the database stores). They share nothing by inheritance, so a new database column never appears in the contract by accident.
Request, OrderCreate: restaurant_id, lines (1 to 50 items of OrderLineIn(menu_item_id, qty)), delivery_address (line1, six-digit pin), and payment as a discriminated union (card with a gateway token, upi with a vpa, cash). No prices and no total: the server looks up prices and computes total_cents. extra="forbid" rejects unknown keys so a client typo ("quanity") fails loudly. camelCase aliases come from a shared base.
Response, OrderOut: id, status, total_cents, lines (each with the captured price_cents), timestamps. Never a card token, never internal ids. Money is integer cents everywhere.
Rules I state out loud: never trust client-sent prices; never accept card numbers (tokens only); limits on every list and string; an Idempotency-Key header on the create (Q72); and each model is documented by an example in json_schema_extra.
Picture it The full request model validated with a good body, then a body with an empty lines, a bad pin and an extra price key.
The setup: OrderCreate with camelCase aliases, extra="forbid", an Annotated quantity, a discriminated payment union, and a six-digit pin pattern.
from typing import Annotated, Literal
from pydantic import BaseModel, Field, model_validator, ConfigDict, ValidationError
from pydantic.alias_generators import to_camel
Qty = Annotated[int, Field(gt=0, le=50)]
class Card(BaseModel):
type: Literal["card"]; token: str # a gateway token, never a card number
class Upi(BaseModel):
type: Literal["upi"]; vpa: str
class Cash(BaseModel):
type: Literal["cash"]
Payment = Annotated[Card | Upi | Cash, Field(discriminator="type")]
class Address(BaseModel):
line1: Annotated[str, Field(min_length=3, max_length=120)]
pin: Annotated[str, Field(pattern=r"^\d{6}$")]
class CamelIn(BaseModel): # shared config: camelCase on the wire, strict shape
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra="forbid")
class OrderLineIn(CamelIn):
menu_item_id: int; qty: Qty # no price: the server looks it up
class OrderCreate(CamelIn):
restaurant_id: int
lines: Annotated[list[OrderLineIn], Field(min_length=1, max_length=50)]
delivery_address: Address
payment: Payment
class OrderLineOut(BaseModel):
menu_item_id: int; qty: int; price_cents: int
class OrderOut(BaseModel):
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True)
id: int; status: str; total_cents: int; lines: list[OrderLineOut]
ok = OrderCreate.model_validate({"restaurantId": 3, "lines": [{"menuItemId": 9, "qty": 2}],
"deliveryAddress": {"line1": "12 MG Road", "pin": "560001"}, "payment": {"type": "upi", "vpa": "asha@bank"}})
print("accepted:", type(ok.payment).__name__, ok.lines[0].qty)
for bad in ({"restaurantId": 3, "lines": [], "deliveryAddress": {"line1": "x", "pin": "1"}, "payment": {"type": "cash"}, "price": 1},):
try: OrderCreate.model_validate(bad)
except ValidationError as e:
for x in e.errors(): print(".".join(map(str, x["loc"])), "|", x["type"])Make the invisible visible: Run it.
accepted: Upi 2
lines | too_short
deliveryAddress.line1 | string_too_short
deliveryAddress.pin | string_pattern_mismatch
price | extra_forbiddenWhat you see: The good body became typed objects (the payment is a Upi). The bad body returned four errors in one response: lines too short, deliveryAddress.line1 too short, deliveryAddress.pin not matching the pattern, and price as an unexpected key.
Why: One call tells the client everything that is wrong, with camelCase paths that match what it sent. The server never had a field for price, so a client cannot choose its own price.
Naive
One model for everything.
class Order(BaseModel): # used for in, out, DB
id: int | None = None
price_cents: int # ❌ client sets price
card_number: str # ❌ stored and echoedCorrect
Three models, narrow edges.
class OrderCreate(CamelIn): # in
lines: list[OrderLineIn]
payment: Payment
class OrderOut(BaseModel): # out
id: int; total_cents: intThe shift: The contract is what each side may say; the database table is only what the server remembers.
Land it I use separate request, response and ORM models, forbid unknown fields, take no prices or card numbers from the client, and make payment a discriminated union.
- "Why should the server compute the total?"
Because anything the client sends can be edited. A mobile app is just a program on a stranger's phone, and a tool like curl can send any value. If the server trusted a client-sent
total_cents, a customer could post1for a 500-rupee order.So the client may show a preview, but the server recomputes. The steps are fixed.
- Look up: read each menu item's current price from the database, not from the request.
- Calculate: multiply by quantity, add delivery fee and tax by the server's rules, in integer cents.
- Capture: store each line's
price_centson the order line, so a menu change tomorrow does not rewrite yesterday's order.
The response returns the total. If the client's preview differs because a price changed meanwhile, the app can show "prices updated, please confirm" instead of charging a number the user never saw.
The same logic covers discounts, stock and delivery distance: the client sends facts about intent (items, quantities, address), never the results of business rules.
- "Why
extra="forbid"on requests but not responses?" Because the two directions have different risks. On a request, the data comes from a stranger. An unknown key usually means a client bug (a typo such as
"quanity", which would otherwise be dropped and the default used) or someone probing the API. Failing with 422 shows the problem on day one, rather than as a wrong order in production.On a response, the data comes from you, and the reader is a client you do not control. If clients reject unknown keys, you can never add a field without breaking someone. So the rule for clients is: ignore what you do not recognise. Then the server can add fields freely, which is the main way an API grows without a new version.
This is the robustness principle, applied with care: be strict in what you accept from untrusted callers, be tolerant in what you read from a trusted server.
One caution:
extra="forbid"also blocks a client that sends a field you just removed. During a deprecation period I keep the old field in the model as ignored, so old clients keep working (Q34).- "Where does "restaurant is open" get checked?"
In the service, using the database, after the model has validated the shape. "Is the restaurant open right now?" depends on stored hours, a manual "closed today" switch and the current time. None of that is a property of the request body.
The flow is short. The route receives a valid
OrderCreate. The service loads the restaurant, checks the rule, and if it fails raises a business error. The error handler turns that into a 409 Conflict with a Problem body whosetypeisrestaurant-closed, plus the opening time as an extension member so the app can show it.Why 409 and not 422? The request is well-formed and the fields are fine, but it conflicts with the current state of the resource. A client can send the very same body later and succeed, which is the sign of a state conflict.
Validators in the model stay pure: they check shape, ranges and formats without any I/O. A validator that queries a database cannot await, hides a slow call inside parsing, and is hard to test (Q23).
- "How do I document examples?"
I put a full example in the model config, and I treat it as test data so that it cannot go stale.
example in the schemaclass OrderCreate(CamelModel): model_config = ConfigDict(json_schema_extra={"examples": [{ "restaurantId": 12, "lines": [{"menuItemId": 7, "qty": 2}], "payment": {"type": "cash"}, }]})FastAPI copies this into the OpenAPI document, so
/docsshows a realistic body in "Try it out", and mock servers and generated documentation use it too.The weakness of an example is drift. Someone adds a required field, the example no longer validates, and the docs now show a request that returns 422. My guard is one test that loads each example from the schema and runs
OrderCreate.model_validate(example). If a model changes and the example does not, CI fails.I write examples for the common success case and one for the tricky variant, such as a UPI payment, since the payment union is where clients most often get the shape wrong.
These questions test whether you treat the generated schema as a contract that clients depend on, and can change it without breaking anyone.
Q33. "Code-first versus spec-first OpenAPI with FastAPI."
Reveal answer
Strong answer Code-first means the Python models and routes are the source of truth, and FastAPI generates the OpenAPI document from them. Spec-first means a human-written OpenAPI file is the source, and code is generated or checked against it.
FastAPI is naturally code-first: the spec cannot drift from the code because it is the code's reflection. That removes the usual "docs are out of date" problem for a single team. Its weakness is that the contract changes whenever the code does, so a harmless refactor can alter the schema.
I make code-first safe with a contract snapshot in CI: export app.openapi() to a committed JSON file, and fail the build when the generated spec differs, forcing a reviewer to read the API change. A breaking-change checker (field removed, type changed, required added) classifies the diff.
Choose spec-first when several teams agree on a contract before anyone writes code, when public SDKs are generated from a spec owned by an API team, or when the contract must be reviewed by non-Python people. Then I implement it with FastAPI and test conformance with a tool like Schemathesis (Q121).
Picture it A snapshot check that classifies two changes: adding an optional field and changing a type.
The setup: The snapshot is the spec of version one; two candidate versions are compared against it.
import json, pathlib, tempfile
from fastapi import FastAPI
from pydantic import BaseModel
def build(extra_field: bool, qty_type=int):
class OrderOut(BaseModel):
id: int
qty: qty_type
if extra_field: note: str | None = None
app = FastAPI()
@app.get("/v1/orders/{order_id}", response_model=OrderOut)
def get(order_id: int): ...
return app.openapi()
snap = pathlib.Path(tempfile.mkdtemp()) / "openapi.snapshot.json"
snap.write_text(json.dumps(build(False), indent=1, sort_keys=True)) # committed in git
def breaking(old, new):
problems = []
o = old["components"]["schemas"]["OrderOut"]["properties"]; n = new["components"]["schemas"]["OrderOut"]["properties"]
for k in o:
if k not in n: problems.append(f"field removed: {k}")
elif o[k].get("type") != n[k].get("type"): problems.append(f"type changed: {k} {o[k].get('type')} -> {n[k].get('type')}")
return problems or ["no breaking change"]
old = json.loads(snap.read_text())
print("add optional field :", breaking(old, build(True)))
print("change qty to str :", breaking(old, build(False, str)))Make the invisible visible: Run it.
add optional field : ['no breaking change']
change qty to str : ['type changed: qty integer -> string']What you see: Adding an optional note is reported as non-breaking. Changing qty from integer to string is flagged as a type change.
Why: A real checker covers more (removed paths, new required fields, narrowed enums), but even this 15-line rule turns "someone renamed a field" into a failed build, not a customer incident.
Spring · springdoc
Spec generated from controllers.
<!-- illustrative -->
springdoc-openapi-starter-webmvc-ui
GET /v3/api-docs -> generated JSONFastAPI
Spec generated from routes.
spec = app.openapi() # also at /openapi.json
json.dump(spec, open("openapi.json", "w"),
indent=1, sort_keys=True)The shift: Both are code-first by default; the discipline is to commit the generated spec and review its diff.
Land it I stay code-first for speed, commit a generated OpenAPI snapshot and fail CI on breaking diffs, and go spec-first only when a contract must be agreed across teams.
- "How do I export the spec in CI without starting a server?"
Import the app factory, call
.openapi(), and write the JSON to a file. No server starts, no port opens, and no request is made. FastAPI builds the document from the route table in memory.export_openapi.pyimport json from app.main import create_app spec = create_app().openapi() with open("openapi.json", "w") as f: json.dump(spec, f, indent=2, sort_keys=True)Sorted keys matter, because they make the file stable, and a stable file gives a clean diff in review. CI runs the script, then
git diff --exit-code openapi.json, and fails if the committed snapshot differs. The developer then regenerates it and a reviewer reads the change.This only works if importing the app is side-effect free. If
create_app()connects to the database or reads secrets at import time, CI needs those, and the build breaks for a confusing reason. The fix is to keep connections in lifespan, which does not run for.openapi()(Q45). Settings should have safe defaults so the factory runs on a bare CI machine.- "What changes count as breaking?"
A change is breaking if a client written against the old spec can fail without any change by its developer. I sort changes into two lists, and the direction matters: requests and responses behave in opposite ways.
Breaking:
- removing or renaming a path, a method or a field;
- changing a field's type, or a status code clients check;
- making an optional request field required, or narrowing what a request accepts (a shorter maximum, fewer enum values);
- adding a new value to a response enum that clients switch on, since an old client may hit its default branch.
Safe:
- adding a new endpoint;
- adding an optional request field;
- adding a field to a response, if the contract tells clients to ignore unknown keys.
The enum case is the subtle one: adding to a request enum is safe, adding to a response enum is not. Tools such as
oasdiffautomate these rules on two spec files, which is better than a human memory. I treat the tool's output as a gate in CI, with a written exception route for an intended break.- "How do I implement a spec-first contract in FastAPI?"
I turn the spec into models, write the routes, and then check in a test that FastAPI's generated document still matches the original. The contract stays the master, and the test is the guard.
- Generate models: a tool such as
datamodel-code-generatorreads the OpenAPI file and writes Pydantic classes. I commit them, and regenerate when the spec changes. - Write the routes: each route uses the generated models for body and
response_model, with the exact path, method and status codes from the spec. - Compare: a test calls
app.openapi()and checks the paths, operations, parameters and schemas against the original. Differences mean drift.
The comparison is rarely byte equal, because FastAPI adds its own details, such as the 422 response and generated operation ids. So I compare the parts that matter to a client, or run a conformance tool such as Schemathesis, which sends real requests based on the spec (Q121).
I only pay this cost when several teams really need an agreed contract before code exists.
- Generate models: a tool such as
- "Which is better for a small team?"
Code-first, without hesitation. There is less ceremony, no second file to keep in step, and the document is always true because it is produced from the code that runs. For a team of five that owns both the server and the client, that is the cheapest way to have an accurate API description.
The weak point shows when someone outside the team depends on the contract. Then a harmless refactor, such as renaming a Pydantic class or changing a type annotation, can change the published schema, and nobody notices because no test failed.
The trigger for extra process is the first external consumer: a partner, a public SDK, or a mobile app that cannot be force-updated. At that moment I add a snapshot of the spec to the repository, a CI step that fails on any difference, and a breaking-change check (Q33).
That keeps the speed of code-first and adds the safety of spec-first at about an afternoon of work. Moving fully to spec-first is a larger step, and I only take it if the contract must be approved before implementation by people who do not write Python.
Q34 · Scenario. "Clients broke after you renamed a field. How do you evolve models safely?"
Reveal answer
Strong answer The rename was a breaking change delivered as a refactor. Old clients still send and expect qty; the server now only understands quantity. The safe path is expand, migrate, contract, the same idea as database migrations.
Expand: the server accepts both names (validation_alias=AliasChoices("quantity", "qty")) and, for responses, returns both for a while (or the old one only when requested). Migrate: publish the new name in OpenAPI, mark the old one deprecated, tell clients, and measure the traffic that still uses the old name (log which alias arrived). Contract: remove the old name only when the measured use is zero, or move to a new API version.
Rules I follow: never rename or remove in place; adding optional fields is safe; changing types is breaking; keep a CI check (Q33) so no one repeats this by accident; and for external APIs announce a deprecation period with Deprecation and Sunset headers.
For mobile apps the contract tail is long: users do not update immediately, so old fields may need to live for months.
Picture it The renamed model accepting both names, and what OpenAPI now documents.
The setup: quantity renamed from qty, with AliasChoices on the request model.
import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field, AliasChoices
class OrderCreateV1(BaseModel): # old clients send "qty"
qty: int
class OrderCreate(BaseModel): # we renamed it to "quantity" but still accept "qty"
model_config = ConfigDict(populate_by_name=True)
quantity: int = Field(validation_alias=AliasChoices("quantity", "qty"))
app = FastAPI()
@app.post("/orders")
def create(o: OrderCreate): return {"quantity": o.quantity}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for body in ({"qty": 2}, {"quantity": 3}):
print(body, "->", (await c.post("/orders", json=body)).json())
print("OpenAPI request properties:", list(app.openapi()["components"]["schemas"]["OrderCreate"]["properties"]))
asyncio.run(main())Make the invisible visible: Run it.
{'qty': 2} -> {'quantity': 2}
{'quantity': 3} -> {'quantity': 3}
OpenAPI request properties: ['quantity']What you see: Both {"qty": 2} and {"quantity": 3} were accepted and produced the same internal field. The documented request schema lists only quantity, so the old name is a compatibility shim, not part of the new contract.
Why: The shim keeps old clients alive while the spec nudges new clients to the new name. The honest cost is that the schema no longer shows the old name, so documentation of the deprecation must be written by hand.
Naive
Rename in place.
class OrderCreate(BaseModel):
- qty: int
+ quantity: int # ❌ old clients get 422Correct
Accept both, then retire.
class OrderCreate(BaseModel):
quantity: int = Field(
validation_alias=AliasChoices(
"quantity", "qty")) # ✅The shift: A contract change ships in two steps, so every client has a version of the server it can talk to.
Land it I never rename in place: I accept both names, measure old-name traffic, deprecate publicly, and remove only when use reaches zero.
- "How do I know when it is safe to remove the old name?"
By measuring it, because a removal date chosen without data is a guess. The server can see which name each request used, so it can count.
The mechanism is small. In the model, accept both names with
validation_alias=AliasChoices("quantity", "qty"). Then record which one arrived: a validator or a thin middleware increments a counter such asdeprecated_field_used_total{field="qty", client="android-4.2"}.Now the question has an answer. Watch the counter by client and version. If
qtystill arrives fromandroid-4.2, the fix is a message to that team, or a force-update prompt, not a removal.My rule for removal has three conditions:
- Zero hits: the counter has been zero for at least one full release cycle of the slowest client.
- Announced date passed: the Sunset date in the headers and changelog has gone by.
- Rollback ready: the old alias can be put back with a one-line change if something unexpected breaks.
Mobile apps need the longest window, because users update slowly.
- "How do I signal deprecation to clients?"
With both machine-readable signals and a human message, because neither works alone. Machines can be ignored by a busy developer, and emails are ignored by a script.
- In the schema: mark the field with
Field(deprecated=True). OpenAPI then shows it as deprecated, and generated clients can show a warning in their IDE. - In the response: add a
Deprecation: trueheader and aSunset: Sun, 01 Aug 2027 00:00:00 GMTheader (the date format is an HTTP date) on responses from deprecated endpoints. Good HTTP clients and gateways can log these automatically. - In people's inboxes: email the registered owner of each client key that was seen using the old field, with the date and the replacement. The usage counter gives you that list (Q34).
- In the changelog: a dated entry on the public page.
The Sunset header is an HTTP standard (RFC 8594) and the Deprecation header is also standardised, so tools understand them. I repeat the message over the whole window instead of once.
- In the schema: mark the field with
- "What if I must change a type, like float price to integer cents?"
Add a new field next to the old one, run both for a while, and migrate. Do not change the meaning or type of an existing name, because clients cannot detect it.
Here is a worked case. The old response has
"total": 249.5, a float in rupees. Floats are inexact and the unit is not in the name. The new field is"total_cents": 24950.expand step{ "total": 249.5, "total_cents": 24950 }The old field stays and is marked deprecated. New clients read
total_cents. When the usage counter shows nobody readstotal, I remove it.The wrong move is to keep
totaland switch it to paise. An old client would then display "24950" rupees and nothing would fail: no error, no 422, just a wrong amount. Silent meaning changes are worse than loud breaks.When many things must change together, a new version prefix such as
/v2is cleaner than a pile of paired fields (Q35).- "How do response changes break clients?"
It depends on how tolerant the reader is, so the contract has to say so. Adding a field is safe for a tolerant reader, one that ignores keys it does not know. It breaks a strict reader, such as a typed client built with "fail on unknown properties" or a schema validator on the receiving side.
The other kinds of response change:
- removing a field breaks every client that reads it;
- changing a field's type or unit breaks everyone, sometimes silently;
- adding a value to an enum can break a client whose code has no default branch;
- changing the order of a list, or making a nullable field start returning null, can break code that assumed otherwise.
The defence has two parts. First, write the rule in the public docs: "clients must ignore unknown fields and unknown enum values". That gives you the right to add things. Second, test with at least one real strict client in CI, such as the generated TypeScript client (Q36).
A response schema is a promise. Anything you add is cheap, and anything you take away or reinterpret costs a migration for every consumer.
Q35. "How do you version a FastAPI API?"
Reveal answer
Strong answer The simplest durable choice is a path prefix: /v1/orders, /v2/orders. Each version is an APIRouter with its own prefix and models, included in the same app. Path versions are visible in logs and caches, easy to route at a gateway, and easy for clients to understand.
Alternatives: a header (Accept: application/vnd.quickbite.v2+json or API-Version: 2) keeps URLs clean but hides the version from caches, curl examples and logs; a query parameter is simple but easy to forget. Date-based versions (Stripe's style) pin each client to a date and apply transformation layers: powerful and expensive to build.
Policy matters more than mechanism: how long old versions live, what counts as a breaking change (Q33), and how deprecation is announced. Most changes should be additive within a version; a new major version should be rare.
Technically I share the service layer across versions and give each version its own schema models and a thin mapper. A mounted sub-application (app.mount("/v3", sub)) gets a fully separate OpenAPI and /docs, which is useful for a preview version.
Picture it Two versions of the same resource, one marked deprecated, plus a mounted sub-app with its own docs.
The setup: v1 returns a float total; v2 returns integer cents; a sub-app is mounted at /v3.
import asyncio, httpx
from fastapi import FastAPI, APIRouter
v1 = APIRouter(prefix="/v1/orders")
v2 = APIRouter(prefix="/v2/orders")
@v1.get("/{order_id}")
def get_v1(order_id: int): return {"id": order_id, "total": 12.5} # old: float rupees
@v2.get("/{order_id}")
def get_v2(order_id: int): return {"id": order_id, "total_cents": 1250} # new: integer cents
app = FastAPI()
app.include_router(v1, deprecated=True)
app.include_router(v2)
sub = FastAPI(title="QuickBite v3 preview") # a separately documented sub-app
@sub.get("/ping")
def ping(): return {"ok": True}
app.mount("/v3", sub)
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for p in ("/v1/orders/1", "/v2/orders/1", "/v3/ping"):
print(p, (await c.get(p)).json())
ps = app.openapi()["paths"]
print("main spec:", {p: ps[p]["get"].get("deprecated", False) for p in ps})
print("sub-app has its own spec:", list(sub.openapi()["paths"]), "and title", sub.openapi()["info"]["title"])
asyncio.run(main())Make the invisible visible: Run it.
/v1/orders/1 {'id': 1, 'total': 12.5}
/v2/orders/1 {'id': 1, 'total_cents': 1250}
/v3/ping {'ok': True}
main spec: {'/v1/orders/{order_id}': True, '/v2/orders/{order_id}': False}
sub-app has its own spec: ['/ping'] and title QuickBite v3 previewWhat you see: All three paths answer. In the main spec /v1 is flagged deprecated: True and /v2 is not. The mounted sub-app is not in the main spec at all; it has its own spec and title.
Why: Versioning by router keeps each contract separate while the business logic stays in one service. The sub-app's separate spec is the double-edged part: great for isolation, but the main /docs will not show it.
Spring Boot
Version in the mapping.
// illustrative
@RestController
@RequestMapping("/v2/orders")
class OrdersV2 { ... }FastAPI
Version in the router prefix.
app.include_router(v1, deprecated=True)
app.include_router(v2) # prefix /v2/ordersThe shift: The mechanics are the same in both; the work is in the policy about lifetime and compatibility.
Land it I version by path prefix with separate schemas per version over one shared service layer, and I write down the deprecation policy before the first release.
- "When should I create a v2 instead of evolving v1?"
When the change cannot be made additive. Most changes can: a new optional field, a new endpoint, a new filter. Those stay in v1, and that is why a healthy API ships a v2 rarely.
Three situations really need a new version.
- A different resource model: for example, an order used to have one delivery and now has several parcels, so the whole shape of the order changes.
- Changed meaning under the same name: money moving from float rupees to integer cents on the same field. A paired new field can sometimes avoid this (Q34), but when dozens of fields change, a clean v2 is simpler.
- Removed behaviour: an endpoint or rule that existed for years and must go.
Before I create v2, I ask what it will cost. Every version doubles tests, documentation and support, and each one needs a retirement date. So v2 starts only with a written deprecation plan for v1 and usage metrics by version.
A bad reason to create v2 is a wish to clean up names. That belongs in an additive change with the old field deprecated.
- "How long do I keep old versions?"
For public APIs I commit to a fixed window in writing, and a common choice is 12 months after the successor is generally available. The window is a number a client can plan around, and it is enforced by data, not by hope.
Enforcement has three parts: a usage metric by version and by client key, a
Sunsetheader with the date on every v1 response once the date is set, and direct emails to clients still on the old version at 90, 30 and 7 days before the end.For internal APIs the rule is different. Old versions live until the last consumer has migrated, and a registry or the usage metric tells you who that is. There is no point in a calendar date if the one team still on v1 is the checkout flow.
One more rule: the window covers security fixes too. Even in the last month, a vulnerability in v1 is fixed in v1, or the version is turned off earlier with notice.
When the date arrives I do not switch it off silently. I return 410 Gone with a Problem body that links to the migration guide.
- "How do I avoid duplicating code across versions?"
By sharing the parts that hold business rules and duplicating only the thin HTTP layer. The usual structure is three layers.
- Domain and services: one copy.
OrderService.create_order()knows the rules about stock, pricing and state, and has no idea what version called it. - Schemas per version:
v1/schemas.pyandv2/schemas.pyeach have their own request and response models. - Mappers: small functions turn a v1 or v2 request into the service's input, and turn the service's result into the version's response.
Each version is an
APIRouterwith its own prefix, included in the same app. A bug fix to a business rule is then made once and both versions get it.The trap is copying a whole route file and editing it. Within a quarter the two copies disagree, and a fix applied to v2 is missing from v1. If I see business logic inside a route function, I move it to the service before adding a version.
The mappers are where the old behaviour lives, such as turning cents back into float rupees for v1, and I test them directly.
- Domain and services: one copy.
- "Header versioning versus path versioning?"
I choose the path prefix unless a platform standard says otherwise. Header versioning is attractive in theory: the URL names the resource, and the version is metadata. The cost shows up in daily work.
These are the practical differences.
- Visibility: a path version appears in logs, metrics, dashboards and error messages for free. A header version needs extra logging, or your graphs cannot split traffic by version.
- Caching: responses vary by header, so caches need a
Varyheader and a correct config, and a mistake serves the wrong version to a client. - Testing and support: a path is a link you can paste in a browser or a ticket. A header needs a tool and a longer curl command.
- Routing: gateways route by path easily. Routing by header works, but it is less common to get right.
Header versioning is acceptable when clients are all generated or controlled by you and the gateway handles it. For a public API, the plain URL is easier to explain and to support.
Q36. "How do you generate typed clients from the OpenAPI schema?"
Reveal answer
Strong answer Export the OpenAPI JSON (from /openapi.json or by calling app.openapi() in CI) and feed it to a generator: openapi-typescript and openapi-generator or orval for TypeScript, openapi-python-client for Python, and others for Java and Kotlin. The generator reads each operation and creates a typed function and a type for every schema.
The quality of the client depends on the quality of the spec. Three FastAPI settings matter most. Stable operation ids: by default FastAPI builds ids like get_order_v1_orders__order_id__get, which produce ugly method names; give routes tags and a generate_unique_id_function that returns tag_function. Documented errors through responses= so the client has types for 4xx bodies (Q13). Explicit request models instead of many loose body parameters, so the generated types have sensible names.
I publish the generated client from CI on every spec change, versioned with the API, and use the committed snapshot (Q33) as the trigger. Frontend teams then get compile-time errors when the backend changes a field.
Generators are not magic: unions, nullable fields and file uploads often need a custom template or a tweak, so I look at the generated output of one real endpoint before committing to a tool.
Picture it Default operation ids versus ones generated from tag and function name.
The setup: Two routes in an orders router.
from fastapi import FastAPI, APIRouter
from fastapi.routing import APIRoute
orders = APIRouter(prefix="/v1/orders", tags=["orders"])
@orders.get("/{order_id}")
def get_order(order_id: int): ...
@orders.post("")
def create_order(): ...
default = FastAPI(); default.include_router(orders)
print("default ids :", [op["operationId"] for p in default.openapi()["paths"].values() for op in p.values()])
def make_id(route: APIRoute) -> str: # tag + function name -> clean method names in generated clients
return f"{route.tags[0]}_{route.name}"
custom = FastAPI(generate_unique_id_function=make_id); custom.include_router(orders)
print("custom ids :", [op["operationId"] for p in custom.openapi()["paths"].values() for op in p.values()])
print("a generator would emit: client.orders.get_order(order_id=5) # name comes from operationId")Make the invisible visible: Run it.
default ids : ['get_order_v1_orders__order_id__get', 'create_order_v1_orders_post']
custom ids : ['orders_get_order', 'orders_create_order']
a generator would emit: client.orders.get_order(order_id=5) # name comes from operationIdWhat you see: The default ids contain the whole path (get_order_v1_orders__order_id__get). With the custom function they are orders_get_order and orders_create_order, which a generator turns into client.orders.get_order(...).
Why: The client's method name is a public API of the SDK. Renaming a Python function would otherwise rename a method in every frontend that uses it, which is one more reason to commit the spec snapshot.
Naive
Default ids, handwritten client.
// hand-written fetch wrappers
const r = await fetch("/v1/orders/" + id);
const o = await r.json(); // anyCorrect
Generated typed client.
const o = await client.orders.getOrder({
orderId: 5 }); // typed OrderOutThe shift: Types flow from the Pydantic model to the OpenAPI document to the frontend compiler.
Land it I generate clients from a committed OpenAPI snapshot with stable operation ids and documented error models, and I regenerate them in CI.
- "Should the frontend team hand-write fetch calls instead?"
For three endpoints, maybe. For anything past a dozen, no, because hand-written types are a second copy of the contract, and copies drift.
Here is how the drift happens. A backend developer renames
delivery_feetodelivery_fee_cents. The frontend still has its own hand-writtenOrderOuttype with the old name. TypeScript is happy, because it trusts the type it was told. The screen shows "undefined" in production, and someone finds out from a customer.With a generated client the story changes. The backend publishes a new spec, CI regenerates the client, and the frontend build fails at every line that uses the old field. The error appears on a developer's machine on the same day, not on a customer's phone a week later.
Generated code also removes dull work: URL building, query encoding, request and response types, and the error types if the spec documents them.
My honest limit: a generated client is only as good as the spec, so the first week costs some effort cleaning operation ids and error models. After that it pays back on every API change.
- "What do I do when the generator produces poor types?"
Fix it at the source first, in the FastAPI code, and only then in the generator. Most bad output comes from a vague spec.
- Make types explicit: use
Literal["placed", "ready"]or anEnuminstead of a barestrwhen only some values are valid, so the client gets a union type. - Name schemas: avoid anonymous inline models. A named
OrderLineInbecomes a named type, and a nested anonymous object becomesBody_create_order_.... - Clean operation ids: a custom
generate_unique_id_functionreturningtag_functiongivesorders_createinstead of a long path-derived name. - Change the tool: if the output is still poor, try another generator or write a custom template for the odd case.
The trap to avoid is editing the generated files by hand. The next regeneration overwrites the edit, and the bug returns with no warning. If a manual patch is truly unavoidable, I keep it as a script that runs after generation, so it is reproducible and visible in review.
- Make types explicit: use
- "How do Python services call each other?"
In two ways, and which one I use depends on the traffic and how tightly the teams are tied.
For ordinary HTTP calls between FastAPI services I use a typed client. It can be generated from the other service's spec like a frontend client, or be a thin shared wrapper around
httpxthat validates each response with the other service's Pydantic model. The point is the same: a field change in the callee should fail in the caller's tests, not in production. Thehttpxclient is created once in lifespan, with timeouts and limits (Q46).For heavy internal traffic, such as many small calls per second or streaming, I consider gRPC (Q114). A
.protofile produces typed stubs for Python and other languages, uses a compact binary format, and its rules for compatible changes are stricter than JSON conventions: you can add fields but never reuse a field number.The cost of gRPC is tooling and harder debugging with plain curl. I do not move to it just for speed; I move when the contract discipline and the streaming are worth the extra build step.
- "Does FastAPI help with WebSocket or SSE typing?"
Not through OpenAPI. The specification describes request and response pairs. A WebSocket is a long-lived two-way channel with many messages in each direction, and Server-Sent Events are one request that stays open and keeps streaming. OpenAPI can mention the endpoint, but it cannot describe the message types. FastAPI's WebSocket routes do not appear in the spec at all.
So I document those separately.
- Define messages as Pydantic models: a
RiderLocationmodel, say, used for both validation and as the written contract. - Describe the channel: AsyncAPI is the sibling standard for message-driven APIs and can list channels and messages. A page in the docs with an example per message type is acceptable for a small team.
- Share types: export the JSON Schema from the models (
RiderLocation.model_json_schema()) and turn it into frontend types in CI.
The same rule as for HTTP applies: one source of truth for the message shape, and a test that fails if the producer and consumer disagree. A text note in a wiki does not count.
- Define messages as Pydantic models: a
Q37. "What belongs in response headers versus the body (ETag, Location, Retry-After)?"
Reveal answer
Strong answer The body carries the resource or the error details. Headers carry metadata about the response or the transport: where the new resource is, how long to wait, whether the cached copy is current, which request this was. Clients and intermediaries (caches, gateways, SDKs) read headers without parsing the body.
The ones I set deliberately: Location on 201 (the URL of the created resource) and on 202 (the status resource); ETag on resources that support conditional requests, with If-None-Match returning 304 and no body, and If-Match for safe updates (Q104); Retry-After on 429 and 503 (seconds or a date) so clients back off correctly; Cache-Control for caching policy; X-Request-ID (or traceparent) for correlation; Idempotent-Replayed: true when a stored response is replayed; Deprecation and Sunset for retiring endpoints; and Content-Type including application/problem+json for errors.
Do not put business data in headers because tools hide them and logs drop them. Pagination is the grey area: a Link header is standard, but I put next_cursor in the body because clients read it directly.
In FastAPI, an endpoint receives a Response parameter and sets response.headers[...]; returning a full Response skips response_model.
Picture it Create returning Location, a conditional GET that returns 304, and a 429 with Retry-After.
The setup: A tiny order resource with a hash-based ETag.
import asyncio, httpx, hashlib, json
from fastapi import FastAPI, Response, Request, status
app = FastAPI()
ORDER = {"id": 42, "status": "preparing"}
@app.post("/orders", status_code=201)
def create(response: Response):
response.headers["Location"] = "/v1/orders/42"
return ORDER
@app.get("/orders/42")
def get(request: Request, response: Response):
etag = '"' + hashlib.sha256(json.dumps(ORDER, sort_keys=True).encode()).hexdigest()[:12] + '"'
if request.headers.get("if-none-match") == etag:
return Response(status_code=304, headers={"ETag": etag})
response.headers["ETag"] = etag
return ORDER
@app.get("/limited")
def limited():
return Response(status_code=429, headers={"Retry-After": "30"}, content=b"")
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
r = await c.post("/orders"); print(r.status_code, "Location:", r.headers["location"])
r = await c.get("/orders/42"); tag = r.headers["etag"]; print(r.status_code, "ETag:", tag, "| body bytes:", len(r.content))
r = await c.get("/orders/42", headers={"If-None-Match": tag}); print(r.status_code, "| body bytes:", len(r.content))
r = await c.get("/limited"); print(r.status_code, "Retry-After:", r.headers["retry-after"])
asyncio.run(main())Make the invisible visible: Run it.
201 Location: /v1/orders/42
200 ETag: "eb171322b1d0" | body bytes: 30
304 | body bytes: 0
429 Retry-After: 30What you see: The POST returned 201 and a Location. The first GET returned 200 with an ETag and 30 bytes of body. Sending the same ETag in If-None-Match returned 304 with 0 bytes of body. The limited route returned 429 with Retry-After: 30.
Why: The 304 saved the whole payload and cost one hash computation. A client that honours Retry-After stops hammering a limited server without any custom code.
Naive
Metadata in the body.
{"created_url": "/v1/orders/42",
"retry_in": 30,
"version": "a1b2"}Correct
Standard headers.
201 Created
Location: /v1/orders/42
ETag: "a1b2"
Retry-After: 30 (on 429)The shift: Use the standard header when one exists, so every client, cache and gateway already understands it.
Land it I put resource data in the body and transport or cache metadata in standard headers: Location, ETag, Retry-After, request id.
- "How do I compute an ETag cheaply?"
Use something that is already stored, so you can answer "did it change?" without building the whole response. Two good choices are an
updated_attimestamp and an integerversioncolumn.The version is better. A timestamp can have one-second resolution, so two updates in the same second give the same tag. A version number goes up on every write, so the tag changes every time. Formatting is a small step.
etag from versionetag = f'"order-{order.id}-v{order.version}"' if request.headers.get("if-none-match") == etag: return Response(status_code=304) response.headers["ETag"] = etagA 304 is returned before any serialisation, so the saving is real: no JSON building and no bytes on the wire.
Hashing the serialised body, as in the demo, is the simplest to write and needs no schema change. Its cost is that the full response must be built before you can compare, so you save bandwidth but not server work. The same version column can later drive
If-Matchfor safe updates (Q74).- "What is a weak ETag?"
A weak ETag starts with
W/, likeW/"order-12-v3". It means "the content is semantically the same", not "byte for byte identical". A strong tag promises identical bytes.The difference matters because bytes can change without meaning changing: a proxy may compress the body, or the JSON key order may differ. A weak tag lets a cache keep reusing the copy through such harmless changes.
Which comparison applies to which header is in the HTTP rules.
- If-None-Match (reading): uses weak comparison. A weak tag is fine here, since a cached copy that means the same is acceptable.
- If-Match (writing): needs strong comparison. If two different versions could carry the same weak tag, a stale client could overwrite someone's update.
So for conditional GETs and caching, either is acceptable. For updates I use a strong tag, or the plain version number from a column, because the goal there is to detect any change at all.
The trap: servers and proxies that compress responses may turn strong tags into weak ones, so test the real deployment path.
- "Where does
Linkpagination fit?" The
Linkheader carries page URLs as metadata. A response hasLink: </orders?cursor=abc>; rel="next". It is a real standard (RFC 8288) and GitHub's API uses it, so many HTTP libraries can followrel="next"automatically.The alternative is a
next_cursorfield in the JSON body, which is what I prefer for a JSON-first API, and what the canonical app does. The reasons are practical: a body field appears in generated types and in OpenAPI, so a client developer sees it. A header is easy to miss, and some tools hide headers or drop them in logs.Either design works if it is consistent across every list endpoint. What matters more is the contract behind it: the client treats the cursor or the link as opaque, and never builds page URLs itself. Then the server can change its ordering, add a signature or switch from offset to cursor without a client update (Q39).
If a public API serves both generic HTTP clients and browsers, supplying both is possible, but I would not do it unless a real client needs it.
- "How do I set headers on error responses?"
In the exception handler, because that is where the error response is built. A route cannot set headers on a response that never gets returned.
The pattern is a custom exception that carries the data, and a handler that uses it.
429 with Retry-Afterclass RateLimited(Exception): def __init__(self, wait_seconds: int): self.wait_seconds = wait_seconds @app.exception_handler(RateLimited) async def on_limited(request, exc): return JSONResponse({"type": "rate-limited"}, status_code=429, headers={"Retry-After": str(exc.wait_seconds)})The rate limiter raises
RateLimited(30)from a dependency, and every route behind it gets the same behaviour.The simpler form works too:
HTTPException(status_code=429, headers={"Retry-After": "30"})accepts a headers dictionary. I use the custom exception when the body must be a Problem Details document and the same logic is reused across many routes.The same approach covers
WWW-Authenticateon 401 andAllowon 405. Headers on errors are part of the contract, so I test them.
Q38 · Scenario. "A list endpoint returns 50,000 items and times out. Fix it."
Reveal answer
Strong answer The endpoint returns every row, so response size, serialisation time and memory all grow with the table. Nothing fails until the table is big, then everything fails at once. The fix is to make the list bounded by design: pagination with a hard maximum, a stable order, and an index that supports that order.
Steps. One: add limit with Query(ge=1, le=100) and a sensible default (20). Two: use cursor (keyset) pagination (Q39) ordered by (created_at, id), returning items plus next_cursor, and an index on those columns. Three: select only needed columns for list views (a summary model, not the full order with all lines).
Four: add filters (status, date range) as indexed query parameters, validated with an allow-list (Q111). Five: if clients truly need everything, offer an export endpoint that streams (Q15) or an async job that writes a file and returns 202 plus a status URL (Q105).
Also protect the server: a response size alarm, a statement timeout in the database, and a test that fails when a list route lacks a limit.
Picture it The unbounded route against the paginated one, with the same 50,000 rows in memory and a request for an absurd limit.
The setup: /orders-all returns everything; /orders takes limit (1–100) and a cursor.
import asyncio, httpx, time
from typing import Annotated
from fastapi import FastAPI, Query
from pydantic import BaseModel
app = FastAPI()
ROWS = [{"id": i, "total_cents": 100 + i} for i in range(1, 50_001)] # 50,000 orders, newest id last
class Page(BaseModel):
items: list[dict]
next_cursor: int | None
@app.get("/orders-all")
def all_orders(): return ROWS # ❌ the 50,000-item endpoint
@app.get("/orders", response_model=Page)
def page(limit: Annotated[int, Query(ge=1, le=100)] = 20, after_id: int = 0):
chunk = ROWS[after_id: after_id + limit]
return {"items": chunk, "next_cursor": chunk[-1]["id"] if len(chunk) == limit else None}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for p in ("/orders-all", "/orders?limit=20"):
t = time.perf_counter(); r = await c.get(p)
print(f"{p:18} {len(r.content):>9,} bytes {(time.perf_counter()-t)*1000:7.1f} ms")
print("limit=100000 ->", (await c.get("/orders?limit=100000")).status_code)
asyncio.run(main())Make the invisible visible: Run it.
/orders-all 1,628,097 bytes 232.8 ms
/orders?limit=20 579 bytes 1.3 ms
limit=100000 -> 422What you see: The unbounded call produced a 1.6 MB response and took 233 ms with no database in the loop; a real query adds time on top. The first page was 579 bytes and took about a millisecond. limit=100000 was refused with 422.
Why: The limit is enforced by the type annotation, so no one can forget it. In production the difference is much larger because the unbounded version also reads 50,000 rows from the database and builds 50,000 Python objects.
Naive
Return the table.
@router.get("/orders")
def list_orders(db=Depends(session)):
return db.scalars(select(Order)).all() # ❌Correct
Bounded, ordered, indexed.
@router.get("/orders", response_model=Page)
def list_orders(limit: Limit = 20,
cursor: str | None = None): ...The shift: Every list endpoint needs a maximum size written into its signature.
Land it I make every list bounded with a validated limit and cursor pagination, return summaries, and offer streaming or a job for bulk export.
- "Why not just raise the timeout?"
Because a longer timeout hides the symptom and makes the cause worse. The cause is that the work grows with the table. A slow request does not go away because the limit is higher; it just occupies resources for longer.
Think about what a slow request holds: a worker slot (or a thread from the pool of 40), a database connection, memory for 50,000 objects, and the client's patience. If each request now takes 30 seconds instead of 10, the same traffic needs three times as many connections and threads. The pool runs out sooner, other, healthy endpoints queue behind it, and the whole service looks down.
A timeout is a safety net that protects the rest of the system from one bad call. Raising it removes that protection without improving anything.
What I would do instead is: bound the work (limit, cursor, index), measure the new latency, and keep timeouts tight, with the database
statement_timeoutset below the HTTP timeout so the query stops first. A timeout I may raise only after I understand why a legitimate request needs longer.- "What about clients that need a total count?"
Be careful with the total, because an exact count is expensive.
SELECT COUNT(*)on a large table has to visit many rows, and on PostgreSQL it cannot simply read a stored number. On a busy table with a filter, it can cost more than the page query itself.Options, from cheapest to exact:
- No count: return only
next_cursor. Most scrolling lists need no total. - Capped count: count at most the first 1,000 rows (
SELECT COUNT(*) FROM (SELECT 1 ... LIMIT 1001)) and show "1,000+". Large products often show "100+" this way. - Approximate: use the planner's estimate or a periodically updated counter. It is cheap and slightly stale.
- Separate request: a
/orders/countendpoint the client calls only when it truly needs a number, cached for a short time.
I ask the client developer what the number is for. A progress bar needs an estimate, an export needs exactness, and a plain list needs neither. That answer picks the option.
- No count: return only
- "How do I prevent this class of bug in future endpoints?"
By making the safe way the easy way, then adding a test that checks every route. A rule that depends on remembering does not survive the tenth developer.
Two pieces do the work.
- Shared building blocks: a generic
Page[T]response model withitemsandnext_cursor, and aLimittype alias,Annotated[int, Query(ge=1, le=100)]with a default of 20. A developer writing a list route reaches for these because they are shorter than inventing their own. - A guard test: walk
app.openapi()["paths"], and for every GET whose success response is an array, or aPage, assert that the operation has alimitparameter with amaximum.
guard test ideafor path, ops in spec["paths"].items(): op = ops.get("get") if op and returns_list(op): assert has_max_limit(op), f"{path} has no bounded limit"The test takes about ten lines. A future list route without a limit fails in CI, not in production at 3 a.m. I add a response-size alarm as the second net.
- Shared building blocks: a generic
- "Could compression solve it?"
It reduces bytes on the wire, but it does not remove the main cost. The server still queries 50,000 rows, builds 50,000 Python objects, validates and serialises them, and then also spends CPU to compress the result. On a busy service that CPU can be the new bottleneck.
Think of where the time goes for a big list:
- the database reads and sorts the rows;
- the driver turns them into Python objects (memory grows with the row count);
- Pydantic validates them and writes JSON;
- compression squeezes the text and sends it.
Only the last step gets cheaper, and only the network part of it. The first three stay the same, and the memory use is unchanged.
Compression is still a good idea for normal responses. JSON compresses very well, and GZip middleware or the proxy in front can cut a 100 KB page a lot. So I enable it at the proxy and, separately, bound the lists. They solve different problems: compression helps a reasonable response travel, and bounds keep a response reasonable in the first place.
Q39. "Cursor versus offset pagination in FastAPI."
Reveal answer
Strong answer Offset pagination uses LIMIT 20 OFFSET 40. It is simple and lets a client jump to page 7. It has two problems. It gets slower for deep pages, because the database must read and throw away the first N rows. And it is unstable when rows are inserted or deleted between requests: the page boundaries shift, so a row can appear twice or be skipped.
Cursor (keyset) pagination remembers the last row seen and asks for rows after it: WHERE (created_at, id) < (:ts, :id) ORDER BY created_at DESC, id DESC LIMIT 20. With an index on (created_at, id) each page costs the same, however deep. The response contains an opaque next_cursor, usually base64 of [created_at, id]; the client returns it unchanged. The id is the tie-breaker so rows with the same timestamp are never skipped.
Trade-offs: no random page jumps and no cheap total count. For feeds, order histories and any list that changes while being read, cursor is the right default; offset is acceptable for small, stable admin tables.
In the canonical QuickBite app the cursor is base64 of [isoformat, id] and limits are capped at 100.
Picture it A newest-first list over 1,000 rows; a new order arrives between the client's page 0 and page 1.
The setup: SQLite in memory; page size 5; row 1001 is inserted between the two requests.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("create table orders (id integer primary key, created text)")
db.executemany("insert into orders values (?, ?)", [(i, f"2026-11-24T10:{i//60:02d}:{i%60:02d}") for i in range(1, 1001)])
def offset_page(n, size=5): # newest first
return [r[0] for r in db.execute("select id from orders order by created desc, id desc limit ? offset ?", (size, n * size))]
def cursor_page(cur, size=5):
q = "select id, created from orders where (created, id) < (?, ?) order by created desc, id desc limit ?"
return [r for r in db.execute(q, (*cur, size))]
p0 = offset_page(0); print("offset page 0:", p0)
db.execute("insert into orders values (1001, '2026-11-24T11:00:00')") # a new order arrives between page requests
print("offset page 1:", offset_page(1), " <- 996 shown AGAIN (a duplicate)")
last = db.execute("select id, created from orders where id = 996").fetchone()
print("cursor page 1:", [r[0] for r in cursor_page((last[1], last[0]))], "(continues from 995, no duplicates)")
import time
t=time.perf_counter(); db.execute("select id from orders order by created desc limit 5 offset 990").fetchall(); a=time.perf_counter()-t
print("note: offset 990 must read and discard 990 rows; cursor seeks. Create an index on (created, id) to make the seek cheap.")Make the invisible visible: Run it.
offset page 0: [1000, 999, 998, 997, 996]
offset page 1: [996, 995, 994, 993, 992] <- 996 shown AGAIN (a duplicate)
cursor page 1: [995, 994, 993, 992, 991] (continues from 995, no duplicates)
note: offset 990 must read and discard 990 rows; cursor seeks. Create an index on (created, id) to make the seek cheap.What you see: With offset, page 1 started with 996, which page 0 had already shown: a duplicate. With the cursor (anchored on the last row seen, 996) the next page began at 995, with nothing repeated.
Why: Offset counts positions, and positions shift when data changes. A cursor names a row, and a row does not move. (A delete would make offset skip a row instead.)
Offset
Counts rows to skip.
SELECT id FROM orders
ORDER BY created DESC
LIMIT 5 OFFSET 5; -- reads and drops 5 rowsCursor
Seeks past the last row seen.
SELECT id FROM orders
WHERE (created, id) < (:ts, :id)
ORDER BY created DESC, id DESC LIMIT 5;The shift: Offset says "skip N rows"; a cursor says "continue after this row", which stays true when data changes.
Land it I default to cursor pagination with a created_at plus id tie-breaker and an index behind it, and use offset only for small, stable tables.
- "Why must the cursor be opaque?"
So the server stays free to change it. If a client can read and build cursors, some will, and then the format is a contract you cannot change. With an opaque cursor, the client's only job is to copy it back unchanged.
What "opaque" means in practice is that the content is not meant to be understood. In the canonical app the cursor is base64 of a small JSON list,
[created_at, id]. Base64 is not secret, but nobody reads it by accident, and clients are told not to.That freedom is useful later. You can add a third sort key, switch the order, change the time format, or add a filter hash, and old clients are unaffected as long as they send the string they were given.
If tampering matters, sign the cursor with an HMAC. A forged cursor could otherwise point the query at a different sort position, or carry a value that shifts the filter. With a signature, the server rejects any cursor it did not issue, with a 400 or 422 and a clear problem type.
For safety I also decode defensively: a bad cursor is a client error, never a 500.
- "Why is
idneeded in the cursor as well as the timestamp?" Because the timestamp alone is not unique, and a page boundary can fall between two rows that share it. The id is the tie-breaker that makes the order total, meaning every row has exactly one place in the sequence.
Here is a small example. Rows are ordered newest first: A and B were both created at 10:00:00, and the page size is 1. Page one returns A. The cursor holds only the timestamp 10:00:00. The next query says
WHERE created_at < '10:00:00', which skips B, because B's time is not strictly less. B is lost, with no error.Using
<=instead would return A again. The fix is a pair comparison.keyset conditionWHERE (created_at, id) < (:ts, :id) ORDER BY created_at DESC, id DESCNow A (10:00:00, id 5) and B (10:00:00, id 4) are ordered by id, and the cursor
(10:00:00, 5)returns B next. The index must be on(created_at, id)in the same order, so each page is an index range scan.- "How do I sort by something other than time?"
The cursor must carry every sort key plus the tie-breaker, and the index must match the order. That is the whole rule, and it has costs.
Say the client wants orders sorted by total, highest first. The cursor then holds
[total_cents, id], and the query isWHERE (total_cents, id) < (:t, :id) ORDER BY total_cents DESC, id DESC. For that to be fast, an index on(total_cents, id)must exist.That is why I do not let clients sort by any column they like.
- Allow-list the sorts: a short enum, such as
newestandhighest_total. Anything else is a 422. - One index per allowed sort: each costs write time and disk, so the list stays short.
- Handle nulls: a nullable sort column complicates the comparison, so I avoid sorting on nullable columns or give them a default.
A sort without a matching index falls back to reading and sorting the whole table for every page, which is the problem we left offset pagination to avoid.
- Allow-list the sorts: a short enum, such as
- "What does the response look like?"
An object with the page of items, the cursor for the next page, and the limit that was applied. On the last page the cursor is null.
page response{ "items": [ { "id": 41, "status": "placed" } ], "next_cursor": "W1si...", "limit": 20 }The trick is how the server knows whether another page exists without a count query. It asks the database for
limit + 1rows. If 21 rows come back, there is a next page: it returns the first 20 and builds the cursor from the 20th row. If 20 or fewer come back, this is the last page andnext_cursoris null.That one extra row costs almost nothing, because the index scan simply reads one more entry. A separate
COUNT(*)would cost far more on a big table.I keep the field name the same for every list endpoint, put the models in a generic
Page[T], and caplimitat 100. Clients then loop on one rule: "whilenext_cursoris not null, send it back".
Q40 · Design. "Design a public API's error format and versioning policy."
Reveal answer
Strong answer Error format. One shape for every error on every route: RFC 9457 Problem Details, application/problem+json, with type (a stable URI that names the problem class and links to documentation), title (short, constant for that type), status, detail (specific, for humans), instance (this occurrence), plus extension members such as errors for field problems and request_id for support.
Clients branch on type and status, never on the text. Validation (422), business conflict (409), auth (401/403), not found (404), limits (429 with Retry-After) and server error (500 with no internals) are all documented in OpenAPI through responses=.
Versioning policy. Path major versions (/v1). Within a version only additive changes. A written definition of "breaking". Every endpoint and field marked deprecated gets Deprecation and Sunset headers and a changelog entry. A published support window (for example 12 months after a successor is released). Usage metrics per version and per client, so removal is a decision backed by data. A contract snapshot and breaking-change check in CI (Q33).
Governance. An owner for the API contract, review of every spec diff, a public status page and changelog, and sandbox keys so clients can test.
The point of writing it down: clients make business decisions on your promises, and promises must be cheap to keep.
Picture it The four problem responses the app returns for a conflict, a validation failure and two HTTP errors, as real output.
The setup: A handler per error family, all returning application/problem+json with a documented type URI.
import asyncio, httpx, json
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
class OutOfStock(Exception):
def __init__(self, item): self.item = item
def problem(status, title, type_, detail=None, **ext):
body = {"type": f"https://api.quickbite.test/problems/{type_}", "title": title, "status": status, **({"detail": detail} if detail else {}), **ext}
return JSONResponse(body, status_code=status, media_type="application/problem+json")
app = FastAPI()
@app.exception_handler(OutOfStock)
async def oos(request: Request, exc: OutOfStock):
return problem(409, "Item out of stock", "out-of-stock", f"Item {exc.item} has no stock left", instance=request.url.path, item_id=exc.item)
@app.exception_handler(RequestValidationError)
async def invalid(request: Request, exc: RequestValidationError):
return problem(422, "Request validation failed", "validation", errors=[{"field": ".".join(map(str, e["loc"][1:])), "code": e["type"]} for e in exc.errors()])
@app.exception_handler(StarletteHTTPException)
async def http(request: Request, exc: StarletteHTTPException):
return problem(exc.status_code, "HTTP error", "http", str(exc.detail))
@app.post("/v1/orders")
def create(qty: int):
if qty > 5: raise OutOfStock(9)
@app.get("/v1/orders/{oid}")
def get(oid: int): from fastapi import HTTPException; raise HTTPException(404, "no such order")
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for r in (await c.post("/v1/orders?qty=9"), await c.post("/v1/orders?qty=x"), await c.get("/v1/orders/1"), await c.get("/nope")):
print(r.status_code, r.headers["content-type"], json.dumps(r.json())[:150])
asyncio.run(main())Make the invisible visible: Run it.
409 application/problem+json {"type": "https://api.quickbite.test/problems/out-of-stock", "title": "Item out of stock", "status": 409, "detail": "Item 9 has no stock left", "insta
422 application/problem+json {"type": "https://api.quickbite.test/problems/validation", "title": "Request validation failed", "status": 422, "errors": [{"field": "qty", "code": "i
404 application/problem+json {"type": "https://api.quickbite.test/problems/http", "title": "HTTP error", "status": 404, "detail": "no such order"}
404 application/problem+json {"type": "https://api.quickbite.test/problems/http", "title": "HTTP error", "status": 404, "detail": "Not Found"}What you see: Every response, whether from a domain exception (409), validation (422) or an HTTP error (404 twice, one from a route and one from the router for an unknown URL), shares the same top-level keys and content type.
Why: The unknown URL /nope also came back as Problem Details, because the handler is registered for Starlette's HTTPException, the base class FastAPI's own errors derive from.
Naive
Every error looks different.
{"detail": "no such order"}
{"error": "OOS", "item": 9}
{"message": "bad", "code": 3}Correct
One documented shape.
{"type": ".../out-of-stock",
"title": "Item out of stock",
"status": 409,
"detail": "Item 9 has no stock left"}The shift: Clients should write one error parser per API, not one per endpoint.
Land it I would give the public API one Problem Details shape with stable type URIs, additive-only changes within a major version, and a published deprecation window backed by usage metrics.
- "How do I decide the
typeURIs?" I decide them once, as stable addresses under the API's own domain, one per kind of error, for example
https://api.quickbite.example/problems/out-of-stock. The URL does not have to be a working web page, but it should be, because that is the whole idea: a client developer who gets the error can open the URL and read what it means and how to react.The rules I keep:
- Never rename: clients match on the string, so it is a compatibility promise. A rename is a breaking change.
- One per class, not per message:
out-of-stockcovers every item, and the item id goes in an extension member. If every message had its own type, clients could not branch. - Add, never reuse: a new error class gets a new URI. An old URI never changes meaning.
- Document each one: the page lists when it happens, the status code and what the client should do.
A short, stable list of 20 to 40 types is usually enough for a whole API. A growing list is a hint that business conditions are leaking into the contract.
- "Should error bodies include stack traces or exception names?"
Never. A stack trace or an exception class name is information for the attacker and noise for the client. It can reveal file paths, library versions, SQL text, table names or the shape of internal code, and each is a hint for the next attack. A client developer also cannot act on it: they cannot fix a
NullPointerException-style detail in your server.The right split is simple.
- To the client: a generic Problem with
typeending ininternal-error, status 500, a short fixed title, and arequest_id. - To the logs: the full exception with the stack trace, the request id, user id, route and timing.
- Bridge between them: the id. A client reports "request id abc123", and an engineer finds the exact trace in one search (Q95).
The same rule covers 4xx messages: say "payment declined", not the gateway's raw error text, which may expose account details.
The catch-all handler for
Exceptionis what guarantees this for errors nobody planned. Without it, some server setups print an HTML error page or a debug trace instead of your Problem body.- To the client: a generic Problem with
- "How do I handle rate limits in the policy?"
I make them part of the written policy, with numbers per plan, and I make the signals machine-readable so a client can slow down without guessing.
- Document the limits: for example 60 requests per minute for a free key and 600 for a paid one, and say what is counted (per key, per IP, per endpoint).
- Reject with 429: a Problem body of type
rate-limitedand aRetry-Afterheader in seconds. Clients that honour it back off exactly as long as needed. - Show the budget: headers such as
RateLimit-RemainingandRateLimit-Reseton normal responses. These follow an IETF draft that many APIs use, and the exact names have varied, so I document mine.
The limiter should live in a shared store such as Redis, not in process memory, because each worker would otherwise count on its own and the real limit becomes the number of workers times the setting (Q6).
Finally I tell clients to add jitter to their retries. If a thousand clients all retry at exactly the Retry-After second, they create a second spike.
- "What happens to old versions when a security fix is needed?"
Security fixes go to every supported version, even if that means a small behaviour change. The policy says so in writing, because without a rule the team will argue about it during an incident.
The principle is that the support window is a promise about stability of features, not about leaving holes open. A client on v1 has a right to rely on the contract, and no right to a known vulnerability.
In practice, I would act in this order.
- Fix in the shared layer: if the bug is in a service or a dependency used by all versions, one change fixes everything. This is a strong reason to share the service layer (Q35).
- Keep the contract, change behaviour: for example reject a malformed input that used to be accepted. That is a compatible choice if it was never valid.
- If the contract itself is unsafe: announce a short, early retirement of that behaviour with a notice, a Sunset date and a clear migration, and accept that this is the one case where the normal window shrinks.
The policy sentence is short: security overrides the deprecation schedule.
09 · DrillDependencies, Data and Transactions — Q41–Q80
The second forty questions follow the path of a request into your own code and then into the database: how Depends builds and runs a graph of functions, how SQLAlchemy 2.0 sessions, pools and transactions behave under concurrency, and how migrations, caching and idempotency keep the service correct when clients retry and deploys happen.
These are the questions where incidents live, so most answers show the failing case first. Every program output was produced on the course machine (FastAPI 0.141.1, SQLAlchemy 2.0.54, Python 3.12), and scripts are in code/e20-python-api/D/. Where Part B measured the same experiment I quote its numbers; where I ran a different workload I say so.
These questions test whether you can explain how FastAPI resolves dependencies per request, what a yield dependency does around the response, and which resources belong to the process rather than to a request.
Q41. "How does Depends work, and what is the dependency graph?"
Reveal answer
Strong answer Depends(fn) tells FastAPI: "before you call this endpoint, call fn and pass its result in as this parameter". fn is an ordinary function with its own parameters, and those parameters can also be Depends(...), so you get a tree of functions.
At start-up, for each route, FastAPI inspects the endpoint signature and recursively inspects each dependency's signature, building a dependency graph (an object it calls the Dependant). It does this once, not per request.
At request time the solver walks the graph from the leaves: it resolves settings before the session that needs them, validates every path, query, header and body parameter on the way, calls each function (in a thread if it is a plain def, on the loop if async def), and finally calls the endpoint.
Anything can be a dependency: a settings getter, a database session, the current user, pagination parameters, a scope check. Parameters declared in dependencies show up in OpenAPI like endpoint parameters.
There is no container and no registration. The graph is the call structure of plain functions, resolved fresh for each request.
Picture it The graph FastAPI built for POST /orders, then the order in which functions ran for one request.
The setup: get_settings → get_session, and get_user → require_scope("orders:write"), both feeding one endpoint. require_scope is a factory that returns the dependency.
import asyncio, httpx
from typing import Annotated
from fastapi import FastAPI, Depends
app = FastAPI()
def get_settings():
print(" get_settings()"); return {"pool": 5}
def get_session(settings: Annotated[dict, Depends(get_settings)]):
print(" get_session(settings)"); return "session"
def get_user():
print(" get_user()"); return "cust-7"
def require_scope(scope): # a factory: returns a dependency
def check(user: Annotated[str, Depends(get_user)]):
print(f" require_scope({scope!r})(user)"); return user
return check
@app.post("/orders")
def create(session: Annotated[str, Depends(get_session)],
user: Annotated[str, Depends(require_scope("orders:write"))]):
print(" endpoint(session, user)"); return {"ok": True}
def show(dep, depth=0):
name = dep.call.__qualname__ if dep.call else "endpoint"
print(" " * depth + name)
for d in dep.dependencies: show(d, depth + 1)
route = [r for r in app.router.routes if getattr(r, "path", "") == "/orders"][0]
print("graph FastAPI built at start-up:"); show(route.dependant)
async def main():
print("one request:")
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
await c.post("/orders")
asyncio.run(main())Make the invisible visible: Run it.
graph FastAPI built at start-up:
create
get_session
get_settings
require_scope.<locals>.check
get_user
one request:
get_settings()
get_session(settings)
get_user()
require_scope('orders:write')(user)
endpoint(session, user)What you see: The tree printed first is the structure inspected at start-up. At request time the leaves ran first (get_settings, then get_session; get_user, then the scope check) and the endpoint ran last, with the results already injected.
Why: Dependencies run before the endpoint body, in dependency order. That is why a failing auth dependency stops the request before any business code, and why order of parameters in the signature does not matter.
Spring Boot
Container wires beans at start-up.
// illustrative
@RestController
class OrderController {
OrderController(OrderService svc) {...}
}FastAPI
Function graph resolved per request.
@router.post("")
def create(svc: Annotated[OrderService,
Depends(get_service)]):
...The shift: Spring builds the object graph once for the process; FastAPI rebuilds the call chain for each request.
Land it I describe Depends as a graph of plain functions that FastAPI inspects at start-up and runs leaf-first for every request, injecting each result.
- "How does it handle
async defanddefdependencies together?" FastAPI runs each dependency in the way that suits its kind, so mixing is fine. An
async defdependency is awaited directly on the event loop. A plaindefdependency is sent to the threadpool (the one that holds up to 40 threads by default) and the request waits for it.The cost is the hop. Moving a call to a worker thread and back takes a small, but real, amount of time and uses a thread slot while it runs. For a dependency that only reads a header or builds a small object, that is wasted work, and on a hot route the thread slots can become the bottleneck before the CPU does.
My rule has two sides.
- Tiny and never blocking: make it
async def. It runs on the loop, finishes in microseconds, and costs no thread. Examples: parsing pagination parameters, reading settings. - Blocking work: keep it
def, so it runs in a thread and does not freeze the loop. Examples: a synchronous database call or a file read.
The danger is the wrong direction: an
async defdependency that calls blocking code freezes every request on that worker (Q1).- Tiny and never blocking: make it
- "Can a dependency read the request?"
Yes, and that is one of the main uses. A dependency's own parameters are treated exactly like an endpoint's parameters, so it can ask for headers, query values, cookies, a body, or the whole
Requestobject.The classic case is the current user.
get_current_userdeclares a header parameter (or a security class that reads theAuthorizationheader), checks the token, and returns aUser. Endpoints then just writeuser: Annotated[User, Depends(get_current_user)]and never touch the header (Q84).Three things to know.
- Validation applies: a missing or malformed value in a dependency's parameter gives a 422 before the endpoint runs, and the error path names where it was read.
- OpenAPI shows them: parameters declared in a dependency appear on every route that uses it, which is why a header requirement shows up consistently.
- Prefer typed parameters to the raw request:
Header()documents and validates the value. Reaching intorequest.headersworks, but it is invisible to OpenAPI.
- "What if a dependency raises?"
If it raises
HTTPException, FastAPI turns it into that response and the endpoint function is never called. Any other exception goes to the handlers registered for its class, and the catch-all returns a 500.What about dependencies that already ran? Those that finished earlier in the chain and use
yieldget their cleanup code run, and the exception is thrown into them, so anexceptblock can roll back andfinallycan close.A concrete order shows it. The chain is: settings, then session (with yield), then user check. The user check raises 401.
- Settings: built, nothing to clean.
- Session: opened, yielded.
- User check: raises 401, and the endpoint is skipped.
- Cleanup: the session's code after
yieldruns and closes the connection, so nothing leaks.
This is why every resource opened in a yield dependency needs a
finally, and why guards that need no database should come before the session in the chain, so a rejected request never opens a connection (Q43).- "Is the graph built per request?"
No. The graph is built once for each route, when the route is registered at start-up. FastAPI reads the endpoint's signature, then the signature of each dependency and so on, and stores the result in the route as a
Dependantobject. Only the values are produced per request.That split is why
Dependsis cheap. At request time the solver does not inspect any signatures. It walks a ready-made tree, reads the needed values from the request, and calls functions.It also means the graph can be inspected like data. The demo prints it from
route.dependant: each node lists its call and its sub-dependencies. I use that in two ways. As a debugging tool when a request fails in an unexpected dependency. And in a test that checks every route under/admincontains the auth dependency somewhere in its tree, so an unprotected route fails the build.One consequence: since the structure is fixed at start-up, you cannot choose a dependency per request by an
if. A dependency that needs to behave differently reads the request and decides inside itself.
Q42. "Are dependencies cached within a request? How do you turn that off?"
Reveal answer
Strong answer Yes. If the same dependency function appears several times in one request's graph (as a direct parameter, and again inside two sub-dependencies), FastAPI calls it once and reuses the result. The cache key is the function (and its security scopes). The cache lives for one request only: the next request calls it again.
That is what you want for get_session: the repository and the permission check both receive the same session, so they work in the same transaction. It is also what you want for get_current_user: one token validation per request, however many places ask.
Depends(fn, use_cache=False) turns it off for that use: every occurrence calls the function again. I use it when each call must produce a fresh value, such as a unique id generator or a "now" timestamp, or when two parts of the request must not share state.
In a Part B measurement a dependency used three ways ran once per request, and twice with use_cache=False on one of the uses.
Picture it One get_user used directly and through two other dependencies, with and without use_cache=False.
The setup: A counter increments each time get_user really runs. A second endpoint marks one of the three uses uncached.
import asyncio, httpx
from typing import Annotated
from fastapi import FastAPI, Depends
calls = {"n": 0}
def get_user():
calls["n"] += 1; return "cust-7"
def audit(u: Annotated[str, Depends(get_user)]): return u
def perms(u: Annotated[str, Depends(get_user)]): return u
app = FastAPI()
@app.get("/cached")
def cached(a: Annotated[str, Depends(audit)], p: Annotated[str, Depends(perms)], u: Annotated[str, Depends(get_user)]):
return {"get_user ran": calls["n"]}
def perms_nc(u: Annotated[str, Depends(get_user, use_cache=False)]): return u
@app.get("/uncached")
def uncached(a: Annotated[str, Depends(audit)], p: Annotated[str, Depends(perms_nc)], u: Annotated[str, Depends(get_user)]):
return {"get_user ran": calls["n"]}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for path in ("/cached", "/uncached"):
calls["n"] = 0; print(path, (await c.get(path)).json())
calls["n"] = 0; await c.get("/cached"); await c.get("/cached"); print("two requests ->", calls["n"], "(the cache lives for one request only)")
asyncio.run(main())Make the invisible visible: Run it.
/cached {'get_user ran': 1}
/uncached {'get_user ran': 2}
two requests -> 2 (the cache lives for one request only)What you see: /cached ran get_user once even though three places asked for it. /uncached ran it twice: the cached uses shared one call, and the uncached use made its own. Two separate requests each ran it again.
Why: Caching is per request and per function, so shared state like a transaction is consistent inside a request and never leaks between requests.
Spring Boot
Singleton bean shared by all.
// illustrative
@Bean // one instance, whole process
CurrentUser currentUser() {...}FastAPI
One result per request.
def get_user(): ... # runs once per request
Depends(get_user) # cached
Depends(get_user, use_cache=False) # runs againThe shift: A Spring bean lives as long as the process; a FastAPI dependency result lives as long as one request.
Land it I rely on per-request caching so the session and the user are the same object everywhere in a request, and use use_cache=False only when each use needs a fresh value.
- "Does the cache survive across requests, like
lru_cache?" No, and that is deliberate. The cache lives for one request only. The next request starts with an empty one and calls every dependency again. That makes it safe: a value computed for one user can never reach another, so nothing goes stale between users.
The run shows how it works. A dependency used three times in one route, twice with the default and once with
use_cache=False:q42_cache.py (output)runs offline[1, 1, 2] 2 first request: ran 2 times [1, 1, 2] 2 second request: ran 2 times againBoth requests ran the function twice: once for the two cached uses and once for the uncached one. The second request did not reuse the first request's value.
For values that should live as long as the process, I use a different tool:
@lru_cacheon a getter such asget_settings, or an object created in lifespan and stored onapp.state(Q45). So the rule is one cache per lifetime: per request for session and user, per process for settings and clients.- "What counts as "the same dependency"?"
The same function object. The cache key is the callable itself (plus the security scopes), not its name or its result. If two
Depends(...)point at one function, there is one entry.That has a trap with factories.
require_scope("a")returns a new inner function each time you call it. SoDepends(require_scope("orders:write"))written in two places creates two different functions, two cache entries, and two checks. For the scope check that is harmless but wasteful. For something expensive, such as a database lookup inside the factory, it is a hidden double cost.- Different arguments:
require_scope("a")andrequire_scope("b")are different functions and both run, which is what you want. - Same arguments, called twice: still two functions, so two runs.
- Fix: create it once as a module constant,
WRITE_ORDERS = require_scope("orders:write"), and useDepends(WRITE_ORDERS)everywhere.
As a bonus, the constant makes the name greppable.
- Different arguments:
- "Does the cache apply to class dependencies?"
Yes. A class is a callable, so the class object is the cache key. The first
Depends(Pagination)builds an instance by calling the class with the request parameters, and the second use in the same request gets that same instance.This matters when a class dependency does some work in
__init__. SayPaginationparses and validates the limit and decodes the cursor. If both the endpoint and a nested dependency ask for it, the work happens once, and both see identical values. That also avoids a quiet bug where two copies are built from the same query string and disagree.The same goes for a callable object (a class with
__call__): the instance is the key, so reuse of one instance across routes gives cache hits inside a request.The limit is that the key is the callable, not its parameters. A class that takes different parameters for different uses must be written as separate classes, or the factory pattern, so each is its own key.
I keep these classes small and stateless, because the instance may be shared by several functions in the same request.
- "When is
use_cache=Falsereally needed?" Rarely, and the reasons are narrow. It is for a dependency that must produce a fresh value at every use. Three examples:
- a
get_request_timestampthat must show the time of each call, not the first; - a unique key or id generator, where two uses must differ;
- a dependency that mutates the object it returns, where sharing it would let one part of the code disturb another.
The run in the previous answer shows the effect: with
use_cache=Falseon one of three uses, the function ran twice, and that use got a new value,2, while the cached uses shared1.My check before using it: am I disabling the cache to avoid shared state? If yes, I redesign. Sharing one session, one user and one settings object within a request is the correct model, because they must be the same object for transactions and permissions to make sense. Turning that off makes two parts of the code work on different connections, so one cannot see the other's uncommitted rows.
So the flag is for values, never for resources.
- a
Q43. "Yield dependencies: what runs when, and what happens when the endpoint raises?"
Reveal answer
Strong answer A dependency with yield is a context manager in function form. Code before yield is setup; the yielded value is injected; code after yield is teardown. Typical use: open a database session, yield it, close it.
Timing (as of FastAPI 0.141, measured below, matching Part B). When the endpoint succeeds, teardown runs after the response has been produced and sent. When the endpoint raises, FastAPI throws the exception into the generator before the error response is sent, so an except block (rollback) and finally (close) run first.
Three consequences. One: do not commit in the teardown after success if the client needs to know it failed: a failed commit there cannot change the already-sent 200, so the service should own the commit (Q78). Two: always release in finally, because validation errors in other parameters can abort after the dependency opened. Three: version behaviour changed over FastAPI releases, so I pin the version and keep a test that records the ordering.
Exceptions you raise in teardown after a successful response are logged by the server and cannot reach the client.
Picture it A session dependency instrumented with a log, run for a success and for an endpoint that raises.
The setup: A middleware records when the response object is produced.
import asyncio, httpx
from fastapi import FastAPI, Depends, HTTPException
log = []
def get_session():
log.append("session opened")
try:
yield "session"
log.append("commit (after endpoint returned)") # ❌ TRAP when put here: runs after the response
except Exception as e:
log.append(f"rollback ({type(e).__name__})"); raise
finally:
log.append("session closed")
app = FastAPI()
@app.get("/ok")
def ok(s=Depends(get_session)):
log.append("endpoint returns"); return {"ok": True}
@app.get("/boom")
def boom(s=Depends(get_session)):
log.append("endpoint raises"); raise HTTPException(409, "conflict")
@app.middleware("http")
async def mark(request, call_next):
r = await call_next(request); log.append(f"response {r.status_code} produced"); return r
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for p in ("/ok", "/boom"):
log.clear(); r = await c.get(p); print(p, r.status_code)
for i, l in enumerate(log, 1): print(f" {i}. {l}")
asyncio.run(main())Make the invisible visible: Run it.
/ok 200
1. session opened
2. endpoint returns
3. response 200 produced
4. commit (after endpoint returned)
5. session closed
/boom 409
1. session opened
2. endpoint raises
3. rollback (HTTPException)
4. session closed
5. response 409 producedWhat you see: On /ok, the response was produced at step 3 and the "commit" and close ran at steps 4 and 5. On /boom, the rollback and close (steps 3 and 4) ran before the 409 response was produced.
Why: So a commit placed after yield runs after the client already has its 200: it cannot report failure. A rollback after an exception runs before the error reaches the client.
Naive
Commit after yield.
def get_session():
s = Session(engine)
yield s
s.commit() # ❌ after the 200 was sent
s.close()Correct
Service commits; teardown closes.
def get_session():
s = Session(engine)
try:
yield s # service calls commit
finally:
s.close() # ✅ alwaysThe shift: Teardown is for releasing resources, not for deciding whether the request succeeded.
Land it I use yield dependencies to open and always release resources, I keep the commit in the service so failure reaches the client, and I pin versions because teardown timing has changed between releases.
- "What does Spring's
@Transactionaldo differently?" Spring's transaction proxy and a FastAPI yield dependency have different jobs, and mixing them up is the reason for the failed-commit bug.
In Spring,
@Transactionalwraps the service method in a proxy. The proxy begins the transaction, calls your method, and then commits on normal return or rolls back on an exception. All of this finishes before the controller returns, so if the commit fails (a constraint violation, say), the exception travels up and becomes an error response.In FastAPI there is no proxy. The equivalent guarantee is an explicit block in the service.
service owns the commitdef create_order(self, data): with self.session.begin(): # commits on exit, rolls back on error ...insert order and lines... return orderThe block exits before the endpoint returns, so a failed commit raises inside the request and becomes a 409 or 503. The yield dependency then only creates and closes the session. Same guarantee as Spring, but visible in the code that owns it, with no annotation magic (Q78).
- "Can a yield dependency handle the exception itself?"
It can, because the exception is thrown into the generator at the
yieldline, so atry/exceptaround theyieldcatches it. But catching is not the same as handling, and I follow one rule: log and re-raise, never swallow.What swallowing does. If the dependency catches the exception and does not re-raise, the failure disappears from everything outside. The exception handlers never see the error, so the client may get a confusing success or an empty answer, and the logs show nothing.
The useful things a yield dependency does with an exception are small:
- Roll back:
except Exception: session.rollback(); raise. - Add context: log the request id and the route, then
raise. - Release: a
finallythat closes the session or returns a connection.
Turning an error into a client response is the job of an exception handler, which sees the error with its full class and can build a Problem body. A dependency should clean up, and handlers should answer.
- Roll back:
- "What about background tasks that use the session?"
A background task runs after the response is sent, and by then the request's session may already be closed, so the task must open its own. This is a classic "session is closed" error that only shows up under load or when the order of events changes.
Why it goes wrong: the session was created by a yield dependency for the request. When the response has gone out, the dependency's teardown can run, closing the session and returning its connection to the pool. A task that was handed that session object now holds a dead handle, or worse, a connection that another request is already using.
- Pass ids, not objects: give the task an
order_idand plain values, not ORM instances or the session. - Open a session inside the task: use a session factory (
with SessionLocal() as s:) and close it there. - Re-read the data: load the order again in the new session, so you work on current rows.
Passing ORM objects also causes "detached instance" errors when a lazy attribute is touched later (Q127). The task needs to be self-contained.
- Pass ids, not objects: give the task an
- "How do I test the ordering?"
By recording what happens, as in the demo, and asserting the exact sequence for both outcomes. The behaviour of teardown timing has changed across FastAPI releases, so I do not trust memory or old blog posts; I keep a test that states the current behaviour.
The idea is small: a dependency appends events to a list, so the order is visible.
ordering testlog = [] def dep(): log.append("setup") try: yield "x" log.append("teardown-ok") except Exception: log.append("teardown-error"); raise # route appends "endpoint"; assert on log after success and after failureFor success I expect
setup, endpoint, teardown-ok. For an endpoint that raises I expectsetup, endpoint, teardown-error, and I assert the status the client got as well.I pin FastAPI in the lockfile and run this test on every upgrade branch. If a new release changes the sequence, the test fails in CI and I read the release notes, rather than a failed commit reaching production as a silent 200.
Q44 · Scenario. "A database-session dependency commits even when the endpoint raised. Fix it."
Reveal answer
Strong answer The dependency commits in finally, or right after a bare yield inside try/finally, so the commit runs whether or not the endpoint raised. A business rule failing after an insert (an out-of-stock 409) then leaves a half-made order in the table.
Fix: commit only on the success path and roll back on any exception, then close in finally: try: yield s; s.commit() except Exception: s.rollback(); raise finally: s.close(). Better still, move the commit into the service (with session.begin():), so the transaction boundary is the business operation and is visible in the code that owns it. The dependency then only creates and closes the session.
How I find it: a test that makes the endpoint raise after a write and asserts the table is unchanged. This kind of test catches the bug in seconds; code review often misses finally: commit().
Remember that HTTPException is an exception too: a handler that raises 404 after partial writes must not leave them behind.
Picture it The same business failure after an insert, against both dependencies, on a real in-memory SQLite database.
The setup: The endpoint inserts an order row, then raises 409. The table is emptied before each call.
import asyncio, httpx
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
with engine.begin() as c: c.execute(text("create table orders (id integer primary key, status text)"))
def count():
with engine.connect() as c: return c.execute(text("select count(*) from orders")).scalar()
def bad_session(): # ❌ TRAP: commit in finally, so it commits even after an error
s = Session(engine)
try: yield s
finally: s.commit(); s.close()
def good_session(): # ✅ commit only when no exception, else rollback
s = Session(engine)
try:
yield s
s.commit()
except Exception:
s.rollback(); raise
finally: s.close()
app = FastAPI()
def make(path, dep):
@app.post(path)
def create(s: Session = Depends(dep)):
s.execute(text("insert into orders(status) values ('placed')"))
raise HTTPException(409, "out of stock") # business failure AFTER the insert
make("/bad", bad_session); make("/good", good_session)
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for p in ("/bad", "/good"):
with engine.begin() as cx: cx.execute(text("delete from orders"))
r = await c.post(p); print(p, r.status_code, "-> rows in table after the failed request:", count())
asyncio.run(main())Make the invisible visible: Run it.
/bad 409 -> rows in table after the failed request: 1
/good 409 -> rows in table after the failed request: 0What you see: With the finally: commit() dependency the failed request left 1 row behind. With the commit-on-success dependency the table had 0 rows.
Why: Failure after a write must undo the write. finally means "always", and "always commit" is exactly wrong.
Naive
Commit in finally.
try:
yield s
finally:
s.commit() # ❌ commits after errors too
s.close()Correct
Commit only on success.
try:
yield s
s.commit() # ✅ only if no exception
except Exception:
s.rollback(); raise
finally:
s.close()The shift: Success and failure take different paths; only close belongs in the path that always runs.
Land it I roll back on any exception, commit only on success (preferably inside the service), and close in finally, and I keep a test that raises after a write.
- "Does closing the session roll back automatically?"
Yes, but I do not rely on it. When a session is closed, its connection goes back to the pool, and SQLAlchemy's pool resets a connection on return by issuing a rollback. So an open transaction is not committed by closing; it is discarded.
Why I still write the rollback myself:
- It is explicit: a reader sees what happens to a failed request without knowing pool internals.
- Behaviour can be changed: pool settings, the driver, or a different pool class (some setups use
NullPoolor an external pooler) change what "return" does. A reset on return can be turned off. - It protects the session itself: after a failed flush, a SQLAlchemy session is in a state that needs a rollback before any further use. An explicit rollback puts it right if the code continues.
So the pattern stays:
try: yield s; except Exception: s.rollback(); raise; finally: s.close(), or better, the service owns the commit and the dependency just closes. Cleanup that depends on a default I did not write is a bug waiting for a configuration change.- "What if the failure happens during commit?"
A commit can fail for real reasons: a unique constraint hit at commit time, a serialization failure under strict isolation, a deadlock, or a lost connection. The worst place for that failure is the teardown of a yield dependency after a success, because the client has already received its 200.
Part B confirmed this by test: a commit placed in teardown that raised still gave the client a 200, and the error was only logged by the server. The customer sees "order placed", and the database holds nothing.
So the commit must happen inside the request's lifetime, where an error can still become a response.
- Service commits:
with session.begin():exits, and a failure raises inside the endpoint. - Handler maps it: an integrity error becomes 409, a connection problem becomes 503 with
Retry-After. - Client sees the truth: the response is sent only after the data is safe.
For a payment or a booking, I add an idempotency key so a retry after a 503 does not create a second order.
- Service commits:
- "Should reads also commit?"
No. A read-only request has nothing to commit, so it should simply end. Committing an empty transaction is harmless but pointless, and rolling back at the end is the cleaner habit: the pool resets the connection, which releases locks and the snapshot the transaction was holding.
That last part is the one that matters at scale. On PostgreSQL, a transaction left open (idle in transaction) keeps a snapshot, which stops cleanup of old row versions and can bloat tables. A request that opens a session, reads, and forgets to end the transaction can cause this when many run.
My arrangement is two dependencies.
get_read_session: opens a session and always ends it with a rollback or close, and it may point at a read replica or set the transaction read-only.get_session: for writes, where the service owns the commit.
Routes name the one they need, so the intent is visible. For replicas, I remember lag: a read right after a write may not see it, so the "read your own order" path uses the primary.
- "How do I handle multiple writes that must all succeed?"
Put them in one transaction block in the service, so they succeed or fail together. Do not commit between steps and do not rely on a dependency for it.
one atomic operationwith session.begin(): order = Order(...) session.add(order) session.flush() # get order.id session.add_all(lines_for(order)) reserve_stock(session, order) # raises: all rolled backIf
reserve_stockraises, the block rolls back the order and the lines too. The database never shows a half-made order.Sometimes one part may fail without cancelling the whole. That is what a savepoint is for:
with session.begin_nested():wraps that part, and if it raises, only it is rolled back while the outer transaction continues (Q62). A good example is "try to apply a coupon, and continue without it if it is expired".Two cautions: keep the block short, with no network calls inside it, because the connection is held until it ends, and do not catch the exception inside the block, or the rollback will not happen.
Q45. "Lifespan: what belongs there, and what belongs in a dependency?"
Reveal answer
Strong answer Lifespan is code that runs once when the application starts and once when it stops: an @asynccontextmanager function passed to FastAPI(lifespan=...). Code before yield is start-up, code after is shutdown. It is the place for process-wide, expensive, shared resources: the database engine and its pool, an httpx.AsyncClient, a Redis client, a loaded model, a Kafka producer, background schedulers.
A dependency is for per-request things: a database session, the current user, pagination parameters, a request-scoped logger. It runs every request and its result lives for one request.
The bridge between them: store the shared object on app.state in lifespan, and expose it through a tiny dependency (request.app.state.client) so endpoints get it by injection and tests can override it.
Rules: never create engines or clients at import time (importing the app for tests or for OpenAPI export would open connections); never create them per request (Q46); close them in shutdown after the yield; and keep start-up fast, because Kubernetes readiness depends on it (Q140).
Picture it A shared client created once in lifespan, handed out by a dependency to three requests, and closed on shutdown.
The setup: FakeClient counts how many instances are created. The app runs inside its lifespan context.
import asyncio, httpx
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Depends
created = {"clients": 0}
class FakeClient:
def __init__(self): created["clients"] += 1; self.closed = False
async def aclose(self): self.closed = True; print("shutdown: client closed")
@asynccontextmanager
async def lifespan(app: FastAPI):
print("startup: create client once"); app.state.client = FakeClient()
yield # the app serves requests here
await app.state.client.aclose()
app = FastAPI(lifespan=lifespan)
def get_client(request: Request): return request.app.state.client # a dependency just hands out the shared one
@app.get("/ping")
async def ping(c=Depends(get_client)): return {"same client id": id(c) % 1000}
async def main():
async with app.router.lifespan_context(app):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for _ in range(3): print((await c.get("/ping")).json())
print("clients created:", created["clients"])
asyncio.run(main())Make the invisible visible: Run it.
startup: create client once
{'same client id': 80}
{'same client id': 80}
{'same client id': 80}
shutdown: client closed
clients created: 1What you see: One start-up line, three requests that all saw the same object, one shutdown line, and a count of exactly one client created.
Why: Start-up and shutdown happen once per process, so anything that must exist once and be closed cleanly goes there. The numbers printed show the sharing: same object each time.
Spring Boot
Singleton bean with destroy method.
// illustrative
@Bean(destroyMethod = "close")
HttpClient httpClient() {
return HttpClient.newHttpClient();
}FastAPI
Lifespan creates and closes.
@asynccontextmanager
async def lifespan(app):
app.state.http = httpx.AsyncClient()
yield
await app.state.http.aclose()The shift: Spring's container owns singleton lifetimes; in FastAPI you write the open and close yourself, in one visible place.
Land it I create shared, expensive resources in lifespan and store them on app.state, I hand them out through small dependencies, and I keep per-request state in yield dependencies.
- "Why not
@app.on_event("startup")?" Because it is deprecated, and it is the weaker design. Lifespan was introduced to replace the separate
startupandshutdownevent handlers, and the old style is kept only for compatibility.The reasons lifespan is better are practical.
- One function, shared variables: setup and teardown sit around the same
yield, so the engine you create is a local variable that you dispose at the end. With events you need a global to pass it between two functions. - Proper errors: if start-up raises, the app does not start, and with
try/finallyaround the yield you can release what was already built. - Context manager tools: you can nest
async withblocks for the client, the pool and the broker, which close in reverse order automatically.
A rule to remember for interviews: do not mix both styles in one app. When a lifespan is given, the old
on_eventhandlers are ignored, so a startup hook can silently never run. A new code base should use lifespan only.- One function, shared variables: setup and teardown sit around the same
- "Does lifespan run under
TestClientandASGITransport?" It depends on the test client, and getting it wrong is a classic source of confusing test errors. There are two cases.
- TestClient: Starlette's
TestClientruns lifespan only when used as a context manager,with TestClient(app) as c:. A bareTestClient(app)does not run start-up. - httpx ASGITransport: it does not run lifespan at all. A test that uses
AsyncClient(transport=ASGITransport(app=app))must enterapp.router.lifespan_context(app)itself, as the demo does, or use a helper such asasgi-lifespan.
What goes wrong when you forget: the lifespan never ran, so
app.state.clientwas never set, and the first request fails withAttributeError: 'State' object has no attribute 'client'. The message points at the dependency, not at the missing start-up, so people waste time looking in the wrong place.My habit is a single pytest fixture that always enters the lifespan and yields a client, and every test uses it. Then no test can forget (Q45).
- TestClient: Starlette's
- "How do I fail fast if a dependency is down at start-up?"
Check the one thing the app cannot work without, cheaply, in lifespan, and raise if it fails. If the database is unreachable, a pod that crashes at start-up is visible at once in the deploy: the rollout stops and the old version keeps serving. A pod that starts and returns errors on every request is much harder to notice.
The check is small:
SELECT 1through the engine, or a ping to Redis. I keep it bounded with a short timeout so a hung network does not block start-up forever.There is a counter-case. Dependencies in a cluster start in no fixed order, and the database may be a few seconds behind. If a brief outage would crash-loop every pod, the better design is to start, report not ready, and let the readiness endpoint return 503 until the check passes. The orchestrator then holds traffic without restarting the pod (Q131).
My policy: crash for configuration errors (a missing setting never fixes itself), and report not-ready for network dependencies that may come back. A hard dependency check is not a substitute for a readiness probe.
- "Can lifespan resources be shared between workers?"
No. Each worker process runs its own lifespan, in its own memory. A server started with four workers executes the start-up code four times, so there are four engines, four connection pools, four HTTP clients and four copies of any loaded model.
This matters in three ways.
- Pool arithmetic: the connections add up. With
pool_size=10and four workers, the database may see 40 connections from one pod, and with five pods, 200. I size pools against the database's limit, not per process (Q6). - Memory: a large model loaded in lifespan is loaded once per worker. For a big one, I prefer one process with threads, or a separate model service, instead of copying it four times.
- State: anything stored in
app.state, such as a rate-limit counter or a cache, is private to that process. A shared limit needs Redis or the database.
Treat lifespan as per-process, never per-service.
- Pool arithmetic: the connections add up. With
Q46 · Scenario. "Creating an httpx.AsyncClient per request exhausts sockets. Fix it."
Reveal answer
Strong answer Each httpx.AsyncClient owns a connection pool. Creating one per request means every request opens a new TCP connection (and a TLS handshake for HTTPS), uses a file descriptor, and then closes it. At hundreds of requests per second, connections pile up in TIME_WAIT, file descriptors run out (Too many open files), and every call pays the handshake latency.
The fix: create one client for the process in lifespan, store it on app.state, hand it out by dependency, and close it at shutdown. Reuse gives keep-alive connections, so calls are faster and the file descriptor count stays flat. Always configure timeouts explicitly, since httpx has a 5 s default and an unbounded wait is worse (httpx.Timeout(2, connect=1)), and set pool limits (httpx.Limits(max_connections=100)) so a slow partner cannot absorb every socket.
The same logic applies to database engines and Redis clients: one per process.
Picture it 300 concurrent requests, each using the client from a dependency, counted both ways.
The setup: A subclass of httpx.AsyncClient counts how many were built. This is the same experiment Part B measured (300 requests).
import asyncio, httpx
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import FastAPI, Depends, Request
made = {"n": 0}
class CountingClient(httpx.AsyncClient):
def __init__(self, *a, **k): made["n"] += 1; super().__init__(*a, **k)
async def per_request_client(): # ❌ TRAP: a new client (and its connection pool) per request
async with CountingClient(timeout=2) as c: yield c
def make(shared: bool):
@asynccontextmanager
async def lifespan(app):
if shared: app.state.http = CountingClient(timeout=httpx.Timeout(2, connect=1))
yield
if shared: await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
dep = (lambda request: request.app.state.http) if shared else per_request_client
@app.get("/rate")
async def rate(c: Annotated[httpx.AsyncClient, Depends(dep)]): return {"ok": True}
return app
async def run(shared):
made["n"] = 0; app = make(shared)
async with app.router.lifespan_context(app):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
await asyncio.gather(*[c.get("/rate") for _ in range(300)])
return made["n"]
async def main():
print("300 requests, client per request :", await run(False), "clients created")
print("300 requests, client in lifespan :", await run(True), "client created")
asyncio.run(main())Make the invisible visible: Run it.
300 requests, client per request : 300 clients created
300 requests, client in lifespan : 1 client createdWhat you see: The per-request version created 300 clients; the lifespan version created 1. These are real client objects with their own pools, so the first number is 300 pools.
Why: Sockets are the visible symptom; the cause is that something expensive was tied to the request lifetime instead of the process lifetime.
Naive
New client per request.
async def get_client():
async with httpx.AsyncClient() as c:
yield c # ❌ new pool every callCorrect
One client, created once.
def get_client(request: Request):
return request.app.state.http # ✅ sharedThe shift: Anything with a connection pool lives as long as the process.
Land it I create one pooled client in lifespan with explicit timeouts and limits, inject it by dependency, and close it at shutdown.
- "How would I notice this before an outage?"
By watching two numbers that rise slowly with traffic: open file descriptors and sockets stuck in
TIME_WAIT. Each new connection takes a descriptor, and a closed one lingers asTIME_WAITfor a while (typically about a minute on Linux) before the system frees it.On a pod I would look at
ss -sfor the socket summary and at theprocess_open_fdsmetric from the Prometheus client, graphed next to the request rate. The signature of this bug is a line that climbs with the request rate and never comes down. A healthy service shows a flat line.Three ways to catch it earlier:
- Soak test: a load test of more than a minute, because the leak needs time to build up. A 10-second test passes.
- Alert on a ratio: open descriptors over the process limit (
ulimit -n), alerting at 70 or 80 percent. - Code review rule: any
AsyncClient(,create_engine(orRedis(inside a function body gets questioned.
The earlier symptom is latency: every call pays a fresh TCP and TLS handshake, so response times creep up before the crash.
- "Is a client shared across threads safe?"
Not across event loops. An
httpx.AsyncClientbelongs to the loop it was created on, so it must be used only from async code running on that loop. In FastAPI that is the single main loop, andasync defendpoints are fine.The problem is sync endpoints. A plain
defroute runs in a worker thread, not on the loop, and calling an async client from there fails or misbehaves. So I use two clients for two worlds.- Async code: one
httpx.AsyncClient, created in lifespan, used withawaitinasync defroutes and dependencies. - Sync code: one
httpx.Client, also created in lifespan, used fromdefroutes in the threadpool. The sync client is documented as thread-safe, so many threads can share it.
Both are closed after the
yieldin lifespan. If I have only async routes, I create only the async client.The better rule is consistency: a route that calls the partner should be
async defwith the async client, so no thread is held while waiting on the network. Mixing styles in one route is where bugs appear (Q1).- Async code: one
- "What limits should I set?"
Start with a pair of explicit settings and adjust from measurements, not guesses. A reasonable first version looks like this.
client settingsclient = httpx.AsyncClient( timeout=httpx.Timeout(2.0, connect=1.0, pool=0.5), limits=httpx.Limits(max_connections=100, max_keepalive_connections=20), )Each number has a reason.
connectis short because a host that does not accept a connection quickly is down.read(the 2.0 default here) is the wait for response bytes, sized to the partner's real slow-but-normal time.poolis the wait for a free connection from the pool, and it is the one people forget: without it, a slow partner makes requests queue silently for as long as they like.max_connectionscaps the total sockets to that partner, so one slow dependency cannot take all the file descriptors.max_keepalive_connectionssets how many idle connections stay open for reuse.A short pool timeout turns "partner too slow" into a fast, bounded error you can handle with a fallback or a 503 (Q98).
- "Does this apply to the database engine too?"
Yes, and the same mistake costs more here.
create_engine()builds a connection pool. Doing it inside a dependency or an endpoint creates a new pool on every request. Each pool opens its own connections, and unless someone disposes of the engine, they stay open until garbage collection gets to them.The Part B scenario did just that: the engine was created in a dependency, and under modest load the database reached its connection limit and started to refuse new ones. The symptoms were confusing: "too many connections" errors from the database, while the application showed only a few active requests.
The rule is the same as for the HTTP client:
- One engine per process: created once, in lifespan or behind a function with a cache, never in a request path.
- Sessions per request: a cheap
Session(engine)from a factory, closed at the end of the request, which borrows and returns a pooled connection. - Dispose at shutdown:
engine.dispose()after the yield, so connections close cleanly.
Redis clients, Kafka producers and ML models follow the same rule: build once, share, release at shutdown.
Q47. "Class-based and parameterised dependencies — when do you use each?"
Reveal answer
Strong answer FastAPI accepts any callable as a dependency, so there are three shapes. A function: the simplest. A class: the class is called, so its __init__ parameters become the request parameters, and the dependency result is an instance. A callable object with __call__: you configure the object once at import, and FastAPI calls it per request.
Use a class dependency to bundle related parameters with a type: Pagination(limit, cursor) gives the endpoint one object instead of two loose parameters, and the constraints live in one place. Use a parameterised dependency (a factory function or a __call__ class) when the same check varies by configuration: require_scope("orders:write"), RoleChecker("admin"), rate_limit(per_minute=60).
Keep both small and stateless. A parameterised dependency created once per route (at import) is cheap; creating it inside the endpoint on every request is not how it works, since Depends(...) is evaluated at definition time.
The factory pattern is the one to know for interviews: it is how Security(..., scopes=[...]) and scope checks are built.
Picture it A pagination class and a role-checker object feeding one endpoint.
The setup: Pagination.__init__ declares query parameters; RoleChecker("customer","admin") is configured at import and called per request.
import asyncio, httpx
from typing import Annotated
from fastapi import FastAPI, Depends, Query
class Pagination: # class dependency: __init__ parameters are request parameters
def __init__(self, limit: Annotated[int, Query(ge=1, le=100)] = 20, cursor: str | None = None):
self.limit, self.cursor = limit, cursor
class RoleChecker: # parameterised: configure once, call per request
def __init__(self, *allowed): self.allowed = set(allowed)
def __call__(self, role: str = "customer"): # role would come from the token in real life
if role not in self.allowed: raise PermissionError(role)
return role
app = FastAPI()
@app.get("/orders")
def orders(p: Annotated[Pagination, Depends()], role: Annotated[str, Depends(RoleChecker("customer", "admin"))]):
return {"limit": p.limit, "cursor": p.cursor, "role": role}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
print((await c.get("/orders?limit=5&cursor=abc")).json())
print((await c.get("/orders?limit=500")).status_code, "(the class's own constraints apply)")
print("params in OpenAPI:", [p["name"] for p in app.openapi()["paths"]["/orders"]["get"]["parameters"]])
asyncio.run(main())Make the invisible visible: Run it.
{'limit': 5, 'cursor': 'abc', 'role': 'customer'}
422 (the class's own constraints apply)
params in OpenAPI: ['limit', 'cursor', 'role']What you see: The query parameters declared in the class constructor were parsed into the object. limit=500 produced 422 because the class's own Query(le=100) applies. OpenAPI lists limit, cursor and role as parameters.
Why: The dependency's signature is part of the endpoint's contract. A class gives it a name and a type, and a factory gives it a configuration.
Naive
Loose parameters repeated.
@router.get("/orders")
def a(limit: int = 20, cursor: str = None): ...
@router.get("/menu")
def b(limit: int = 20, cursor: str = None): ...Correct
One class dependency.
class Pagination:
def __init__(self, limit: Limit = 20,
cursor: str | None = None): ...
def a(p: Annotated[Pagination, Depends()]): ...The shift: Name a group of parameters once, with its validation, and reuse it.
Land it I use class dependencies to bundle recurring parameters and factory or callable-object dependencies when a check needs configuration, such as scopes or roles.
- "Why
Depends()with no argument?" It is a shortcut with one clear meaning: "use the annotated type as the dependency". It saves writing the same class name twice.
two ways, same result# full form def route(p: Annotated[Pagination, Depends(Pagination)]): ... # shortcut: the type is already the class def route(p: Annotated[Pagination, Depends()]): ...When
Depends()has no argument, FastAPI takes the callable from the parameter's type annotation. That only works when the annotation is a class (or another callable type) you can call with request parameters. It does not work for a function, since a function's annotation is the return type, not itself.It is documented and common for class dependencies, and I use it for that case. For a function dependency I write
Depends(get_session)in full, because the function name is the information.A style note for the team: I define a type alias once,
PageParams = Annotated[Pagination, Depends()], and routes just writep: PageParams. The wiring is then in one place, and a change to it is a one-line edit.- "Where do the scope strings end up in OpenAPI?"
Only with
Security(...). A plainDepends(require_scope("orders:write"))enforces the rule, but OpenAPI does not know about it, so the docs show nothing about the scope.Use
Security(dependency, scopes=["orders:write"])and FastAPI records the scopes in the operation'ssecuritylist, next to the scheme. That does three useful things.- Docs show it: Swagger UI marks the route with a lock and lists the required scope in the Authorize dialog.
- Clients see it: generators and gateways can read the scope list, so tooling can warn or route by it.
- The function receives it: the dependency can take a
SecurityScopesparameter and readsecurity_scopes.scopes, so one checker can enforce whatever each route asked for, rather than needing one factory call per scope.
Scopes of nested
Securitydependencies are combined, so a route behind a router-level scope still shows the union.The enforcement is still your code: OpenAPI records the requirement, and the dependency checks the token's scopes. Documentation without the check would be a lie, and a check without documentation would be invisible (Q84).
- "Is a dataclass or Pydantic model usable as a dependency?"
Yes, a dataclass works exactly like a plain class dependency. FastAPI reads its fields as the request parameters, calls it, and injects the instance. That is useful when you want a typed bundle with defaults and no hand-written
__init__.A Pydantic model is a different case, because a model is mostly used for a body. FastAPI, however, also lets a model describe a group of query parameters in recent versions: you declare
filters: Annotated[Filters, Query()], and the model's fields become query parameters, validated together as one object.The same exists for headers and cookies. It is very good for a filter group such as
status,from_date,to_dateandlimit, since constraints and docs live in one model and a model-level validator can check thatfrom_dateis beforeto_date.I do check the installed version before using it, since this feature came with a specific release, and an old pin would silently treat the model as a body. In this course's setup (FastAPI 0.141) it is available.
If I need to share a bundle across routes, a class dependency still reads clearer to most people.
- "When is a function better?"
When there is nothing to bundle and nothing to remember. A function with one parameter, such as
get_settingsor a one-line header check, is the simplest thing that works. A class for two lines of logic is ceremony: a name, an__init__, and a reader who must open the class to see that it does almost nothing.My switching rule is based on what the dependency carries.
- One parameter or none: a function.
- Three or more related parameters that always travel together: a class, so the endpoint takes one argument and the constraints live in one place.
- The same bundle in many routes: a class with a type alias, so changing a default or limit is one edit.
- Configuration of the check: a factory function or a
__call__object.
A signal I watch for: a route with five loose query parameters that are repeated in three other routes. That is a missing class dependency.
The test for either choice is the same: can a new teammate read the route signature and understand what the endpoint needs, without opening another file?
Q48. "The Spring IoC container versus FastAPI Depends."
Reveal answer
Strong answer Spring's container builds a graph of singleton beans at start-up, wires them by constructor injection, and manages their lifecycle; scoped beans (request, session) are special cases, and @Transactional works through proxies the container creates around beans.
FastAPI has no container. A dependency is a plain function (or callable) that FastAPI calls on every request, with a per-request cache. Sharing across requests is something you do deliberately (module-level object, lru_cache, app.state from lifespan). There are no proxies: transactions are explicit with blocks.
Practical differences. Lifetime: Spring default is singleton, FastAPI default is per request. Wiring: Spring resolves by type with annotations and component scanning; FastAPI resolves by explicit Depends(function) in the signature, so the call graph is greppable. Testing: Spring swaps beans via test configuration or @MockBean; FastAPI swaps with app.dependency_overrides[fn] = replacement. Failure: Spring fails at start-up if a bean is missing; FastAPI fails at the first request using the route (so tests must hit every route).
When you want container-style DI (many singletons, lifecycles), libraries such as dependency-injector or svcs exist; I use them rarely.
Picture it Two dependencies: a process-wide singleton and a per-request object, over three requests.
The setup: Service() objects take a number from a counter when created.
import asyncio, httpx, itertools
from typing import Annotated
from fastapi import FastAPI, Depends
ids = itertools.count(1)
class Service:
def __init__(self): self.n = next(ids)
singleton = Service() # Spring-style singleton: one object for the process
def get_singleton(): return singleton
def get_per_request(): return Service() # FastAPI default: a fresh object per request
app = FastAPI()
@app.get("/who")
def who(a: Annotated[Service, Depends(get_singleton)], b: Annotated[Service, Depends(get_per_request)]):
return {"singleton_id": a.n, "per_request_id": b.n}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for _ in range(3): print((await c.get("/who")).json())
asyncio.run(main())Make the invisible visible: Run it.
{'singleton_id': 1, 'per_request_id': 2}
{'singleton_id': 1, 'per_request_id': 3}
{'singleton_id': 1, 'per_request_id': 4}What you see: The singleton dependency returned object 1 every time. The per-request dependency made a new object each request (2, 3, 4).
Why: Spring defaults to the first behaviour and FastAPI to the second. In FastAPI sharing is something you write on purpose, which is why it never appears by accident.
Spring Boot
Container, singleton by default.
// illustrative
@Service
class OrderService {
OrderService(OrderRepo repo) { ... }
} // one instance, injected everywhereFastAPI
Functions, fresh per request.
def get_service(s: Session = Depends(get_session)):
return OrderService(OrderRepository(s))
# a new object every requestThe shift: Spring shares objects unless told otherwise; FastAPI shares nothing unless you make it global.
Land it I explain Depends as per-request function calls with no container or proxies, so lifetime, wiring and transactions are all explicit.
- "What do I lose without a container?"
Less than people fear, and I gain more than I lose. What I lose are two services a container gives for free.
- Lifecycle management: Spring creates singletons, orders them by dependency, and destroys them at shutdown. In FastAPI I do that myself in lifespan, with an explicit order.
- A start-up check: Spring refuses to start if a bean cannot be built. FastAPI finds a missing dependency when the first request uses that route. So I add a test that calls every route, or a start-up check that builds the key objects.
What I gain is simplicity. The wiring is the function signature. I can read the call graph, step through it in a debugger, and replace any part in a test with one line:
app.dependency_overrides[get_session] = fake_session. There is no scanning, no proxies, no hidden bean, and no question about which implementation was injected.The balance moves if an application has hundreds of long-lived collaborators with complex lifetimes. Then a library such as
dependency-injectoris worth a look. For a typical API with a few shared resources and a handful of per-request services, plain functions are enough.- "Is creating a service per request expensive?"
No. Creating an
OrderService(session)is making one small Python object with a reference or two, which costs microseconds. Compare that to the request itself, where a single database query takes milliseconds, which is a thousand times more.The right split is by cost, not by habit.
- Expensive and shared: the engine, the HTTP client, a loaded model. Built once in lifespan and stored on
app.state(Q45). - Cheap and stateful: the session, the repository, the service. Built per request by dependencies, so each request has its own and nothing is shared by accident.
That is the reverse of Spring's habit, where services are singletons. In Python a per-request service is safe: it holds the request's session, so there is no thread-safety question and no state to leak between users.
The one thing to watch is that "cheap" assumes the constructor does no work. If
__init__reads a file, builds a regex table or opens a connection, move that to a module-level constant or lifespan. Constructors should only store references, and I check this when reviewing a new service class.- Expensive and shared: the engine, the HTTP client, a loaded model. Built once in lifespan and stored on
- "How do I get request-scoped state without
ThreadLocal?" The tool is a
ContextVar. It gives you a variable whose value belongs to the current request, and it works acrossawaitand across threads started with asyncio's helpers. It is Python's answer to Java'sThreadLocal, and unlike a thread-local it is also correct in async code, where many requests share one thread (E19,#pat-contextvars).A real use is the request id, which log lines deep in the code want to include without every function taking it as a parameter.
request id in contextrequest_id = ContextVar("request_id", default="-") @app.middleware("http") async def stamp(request, call_next): request_id.set(request.headers.get("x-request-id", new_id())) return await call_next(request)A logging filter then reads
request_id.get()and adds it to each record.For everything else, I pass things explicitly. The session is request-scoped because the dependency creates one per request, and the function that needs it receives it. Passing a parameter is clearer than hidden context, so a
ContextVaris only for cross-cutting values such as ids, user for audit and trace context.- "How do
@Transactionaland a yield dependency differ?" They answer different questions, and mixing them is how data gets lost.
@Transactionalis declarative. A proxy around the method begins the transaction and commits when the method returns. The boundary is an annotation, and it can be surprising: a call from one method to another in the same class bypasses the proxy, so the second annotation does nothing.A yield dependency in FastAPI only manages the resource: open the session, hand it out, close it, and roll back on an error. It does not decide where the business operation starts and ends.
- Boundary in the service:
with session.begin():around the operation. Everything inside commits together or not at all. - Commit before returning: the block exits before the endpoint returns, so a failed commit reaches the client as an error (Q78).
- Visible in the code: a reader sees the exact lines that are atomic.
It is less magic and more typing. For a senior interview, I would say that I prefer explicit transaction scope: it is easier to review, and the self-invocation trap cannot happen.
- Boundary in the service:
Q49. "How do you override dependencies in tests?"
Reveal answer
Strong answer FastAPI keeps a dict, app.dependency_overrides, mapping an original dependency function to a replacement. During a request, whenever the graph would call the original, it calls the replacement instead, with the replacement's own parameters resolved as usual.
In tests I override at the boundaries: get_session (point at an in-memory SQLite engine with StaticPool), get_current_user (return a fixed User or build a token through a fixture), get_settings (test settings), and any outbound client (a fake). I clear the overrides after each test (a fixture with yield and app.dependency_overrides.clear()).
Why this is better than monkeypatching: the override sits on the same seam production uses, so the test exercises the real routing, validation, serialisation and error handling. It is also explicit: you see exactly which collaborators were replaced.
Pitfalls: overrides are matched by function identity, so override the exact function object the route uses (not a copy or re-export). And never leave the override dict populated: it is global app state and will leak into the next test.
Picture it A route whose real dependencies cannot run in a test, called without and with overrides.
The setup: The real get_current_user and get_session raise, as they would without a token server and a database.
import asyncio, httpx
from typing import Annotated
from fastapi import FastAPI, Depends
class User:
def __init__(self, id, role): self.id, self.role = id, role
def get_current_user() -> User: raise RuntimeError("real auth needs a token and a JWKS server")
def get_session(): raise RuntimeError("real session needs PostgreSQL")
app = FastAPI()
@app.get("/me")
def me(u: Annotated[User, Depends(get_current_user)], s: Annotated[str, Depends(get_session)]):
return {"user": u.id, "role": u.role, "session": s}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
try: await c.get("/me")
except RuntimeError as e: print("no override ->", e)
app.dependency_overrides[get_current_user] = lambda: User("cust-7", "customer")
app.dependency_overrides[get_session] = lambda: "sqlite-test-session"
print("with overrides ->", (await c.get("/me")).json())
app.dependency_overrides.clear()
print("cleared, overrides left:", len(app.dependency_overrides))
asyncio.run(main())Make the invisible visible: Run it.
no override -> real auth needs a token and a JWKS server
with overrides -> {'user': 'cust-7', 'role': 'customer', 'session': 'sqlite-test-session'}
cleared, overrides left: 0What you see: Without overrides the request raised the real dependency's error. With two overrides the same route returned the fake user and session. After clear() no overrides remained.
Why: The route code did not change at all; only the two seams did. That is the entire testing story for FastAPI dependencies.
Spring · MockMvc
Replace beans in the test context.
// illustrative
@WebMvcTest(OrderController.class)
class OrdersTest {
@MockBean OrderService svc;
}FastAPI
Override the function.
app.dependency_overrides[get_session] = fake
app.dependency_overrides[get_current_user] = \
lambda: User("c7", "customer")The shift: Both swap collaborators at a seam; FastAPI's seam is the dependency function itself.
Land it I override the session, user, settings and outbound clients through dependency_overrides in a fixture that always clears them, so tests keep the real routing and validation.
- "Can an override take parameters?"
Yes. The replacement is resolved like any dependency, so it can declare its own parameters, take
Dependsof other things, and even ask for theRequest. FastAPI runs it with the same solver as the original.The common case needs none of this: a lambda with no parameters, such as
lambda: User(id=1, scopes=["orders:write"]). It returns a fixed object, and the test is easy to read.The parameter case is useful when the fake should depend on the request. Example: a fake
get_current_userthat reads anX-Test-Userheader, so one test can call the same app as different users without changing the override.override with a parameterdef fake_user(x_test_user: str = Header("alice")): return USERS[x_test_user] app.dependency_overrides[get_current_user] = fake_userThis lets an ownership test (someone else's order gives 404) run as two users in one function. The limit is to keep fakes simple: if a fake grows its own logic, I am testing the fake.
- "How do I override something used inside another dependency?"
You do not need to do anything special. The override replaces the function everywhere it appears in the graph, whether it is a direct parameter of the endpoint or three levels down inside another dependency.
A small example.
get_sessiondepends onget_settingsto read the database URL. A test setsapp.dependency_overrides[get_settings] = lambda: Settings(database_url="sqlite://"). When FastAPI builds the graph for a request, it findsget_settingsinsideget_session, swaps in the override, and the session is created with the test URL. No change toget_sessionis needed.This is the reason to put configuration and external clients behind dependencies from the start: one override at the bottom of the tree changes every consumer above it.
The rule that makes it work is identity: the key must be the exact function object the route uses. If a module re-exports a wrapper, or the dependency was built by a factory call, overriding a different object has no effect and the real one runs. When an override seems ignored, I check that first, and I print
app.dependency_overridesin the test.- "Should I mock the repository instead?"
It depends on what the test is for. There are two levels, and I use both.
- Service unit tests: yes, pass a fake repository directly. No HTTP, no database, and the test runs in microseconds. It is the right tool to check business rules such as "restaurant closed gives a 409 error".
- API tests: no, I prefer a real session on an in-memory database. The route, validation, serialisation, queries and transaction all run for real, so a typo in a query or a missing flush shows up.
Mocking the repository in an API test only proves that the route calls the mock. It tells me nothing about the SQL, the joins, or the mapping to the response, and those are where most real bugs sit.
The cost of the in-memory route is that SQLite differs from PostgreSQL in some details, such as locking and types. So the canonical app runs its test suite on SQLite by default (44 passed, 1 skipped) and on a real PostgreSQL in CI (45 passed), and the Postgres run covers the cases SQLite cannot (Q119).
- "How do I handle async overrides?"
FastAPI does not mind. An override may be
async defeven when the original wasdef, or the other way around. Each is run the right way: anasync defis awaited on the loop, and adefis sent to the threadpool.The safe habit is to keep the same kind as the original where I can, because the kind changes behaviour in ways a test can hide.
An example. The real
get_sessionis a plaindef, so blocking database work runs in the threadpool. A test replaces it with anasync deffake that is a few lines. Now nothing in the test runs through a worker thread, so a bug that only appears when two threads share an object, or when code blocks a thread, cannot show up in that test.A second reason: a sync fake used in place of an async original blocks the loop in the test, which hides a slow-call problem that production would have.
So when the shape differs, I write a comment saying why. A different kind of override is a decision to record, not an accident.
Q50. "Router-level and app-level dependencies — what are they for?"
Reveal answer
Strong answer FastAPI(dependencies=[...]) runs those dependencies for every route in the app. APIRouter(dependencies=[...]) runs them for every route in that router, and include_router(router, dependencies=[...]) adds more at include time. The return value is discarded: these are for side effects and guards, not for supplying data.
Good uses: authentication on a whole router (dependencies=[Depends(require_user)]), an API-key check on /admin, a rate limiter, a request counter or audit hook, a Deprecation header setter for an old version. They keep a guard from being forgotten on one route, which is the usual way a protected API grows an unprotected endpoint.
When the endpoint also needs the value (the current user), declare the same dependency as a parameter too: the per-request cache (Q42) means it still runs once.
Compare with middleware: a dependency knows which route matched, can read validated parameters, raises HTTPException cleanly, shows up in OpenAPI (if it is a security class) and is overridable in tests. Middleware cannot do any of that, so I use dependencies for authentication and authorisation, and middleware only for pure cross-cutting concerns such as request ids.
Picture it One app-level dependency, one router-level guard, and three calls.
The setup: /healthz is on the app; /admin/stats is on a router guarded by an API-key check.
import asyncio, httpx
from fastapi import FastAPI, APIRouter, Depends, Header, HTTPException
def verify_api_key(x_api_key: str = Header(default="")):
if x_api_key != "k1": raise HTTPException(401, "bad api key")
def count_calls():
print(" app-level dependency ran")
admin = APIRouter(prefix="/admin", dependencies=[Depends(verify_api_key)]) # every route in this router
@admin.get("/stats")
def stats(): return {"orders": 12}
app = FastAPI(dependencies=[Depends(count_calls)]) # every route in the app
app.include_router(admin)
@app.get("/healthz")
def health(): return {"ok": True}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for path, h in (("/healthz", {}), ("/admin/stats", {}), ("/admin/stats", {"x-api-key": "k1"})):
r = await c.get(path, headers=h); print(path, h, "->", r.status_code)
asyncio.run(main())Make the invisible visible: Run it.
app-level dependency ran
/healthz {} -> 200
app-level dependency ran
/admin/stats {} -> 401
app-level dependency ran
/admin/stats {'x-api-key': 'k1'} -> 200What you see: The app-level dependency ran on all three calls. The router-level key check stopped the second call with 401 and let the third through with the right key. /healthz was untouched by the router guard.
Why: Put the guard where the group is defined and a new route added to that router is protected on day one.
Spring Security
URL rules in one config.
// illustrative
http.authorizeHttpRequests(a -> a
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated());FastAPI
Guard on the router.
admin = APIRouter(
prefix="/admin",
dependencies=[Depends(require_admin)])The shift: Spring protects URL patterns from a central config; FastAPI protects routers where they are declared.
Land it I attach authentication and policy guards at the router, so a new route in that group is protected by default, and I keep the value-bearing dependencies on the endpoint.
- "Can a route opt out of an app-level dependency?"
Not directly. A dependency listed on
FastAPI(dependencies=[...])is attached to every route, including the ones added later and the built-in docs routes, and there is no per-route switch to turn it off.This is the main reason I prefer router-level guards. The structure does the work.
- Public router: health, readiness, login and docs live in routers with no auth dependency.
- Protected routers: every other router has
dependencies=[Depends(require_user)]. - App level: reserved for things that truly apply to all, such as a request counter or a header setter.
A new route in a protected router is protected by default, and a new public route needs a deliberate decision to put it in the public router. That is the right way round: forgetting is safe.
The other solution is to make the app-level dependency check
request.url.pathagainst an allow-list and skip some paths. I avoid it, because the allow-list is a second routing table, and paths that change in one place silently stop matching in the other. A guard that decides by string comparison is hard to review, and a typo opens a hole.- "In which order do the dependencies run?"
The order is fixed and I confirmed it by running it. Dependencies from the app level run first, then the router level, then the ones on the route itself, and within each group in the order of the list.
q50_order.py (output)runs offline['app', 'router', 'route']If an earlier one raises, the later ones and the endpoint never run. That gives a design rule: order the checks from the cheapest to the most expensive.
- Cheap rejections first: an API key check, a rate limit, a header format check. They cost microseconds and stop abusive callers early.
- Then identity: validating a token, which may need a signature check or a key lookup.
- Then the database: loading the user, permissions or the resource. Each costs a connection and a query.
A request without a key then never touches the database. Order also matters for information: an attacker should get 401 before learning whether a resource exists, so authentication goes before any lookup (Q84).
- "Does the OpenAPI document show them?"
Parts of them. What shows up depends on what the dependency declares, and the difference is worth knowing.
- Parameters: a header, query value or cookie declared in a dependency, with
Header()and similar, appears as a parameter on every operation that uses it, including router-level ones. - Security classes:
HTTPBearer,OAuth2PasswordBeareror an API key class add a security scheme to the document. The docs page shows a lock on each route and an Authorize button. - A plain function: a function that checks something inside, or that reads
request.headersdirectly, is invisible. It protects the route, but the document says nothing about it.
So I use a security class as the base of my auth dependency, even if my own code does the real checking. Then the generated client and the Swagger page know the route needs a token.
A dependency whose return value is discarded at router level still contributes its parameters and schemes. I check
/openapi.jsonafter adding a router-level guard, to see that the lock really appears.- Parameters: a header, query value or cookie declared in a dependency, with
- "What about
Security()versusDepends()?" SecurityisDependsplus scopes. It is a subclass-like variant, so it injects the same way, but it also records which scopes the route requires, and that list goes into OpenAPI and into the dependency as aSecurityScopesobject.When to use which:
- Authentication only: "there must be a valid user".
Depends(get_current_user)is enough. - Authorisation by scope: "the user must hold orders:write". Use
Security(get_current_user, scopes=["orders:write"]), so the requirement is visible to tools.
The checker reads the needed scopes and compares them with the token.
scope checkdef get_current_user(scopes: SecurityScopes, token=Depends(bearer)): claims = verify(token) if not set(scopes.scopes) <= set(claims["scope"].split()): raise HTTPException(403, "missing scope") return user_from(claims)A missing scope gives 403, an unknown token gives 401, and someone else's order gives 404, so the status codes are distinct and tests can check each (Q84).
- Authentication only: "there must be a valid user".
Q51 · Scenario. "A dependency loads the current user from the database on every request and latency is up. What are your options?"
Reveal answer
Strong answer First measure: confirm the user lookup is the slow part (a span or a timer), and how often it runs. Then choose the cheapest option that keeps correctness acceptable.
Option one: put what you need in the token. A signed JWT already carries sub, roles and scopes, validated by signature in microseconds with no database. Fine for identity and coarse roles; the cost is that role changes and revocation take effect only when the token expires (keep tokens short-lived, 5 to 15 minutes).
Option two: cache the user by id for a short TTL (30 to 60 seconds) in process memory or Redis. Latency drops; staleness is bounded by the TTL; and a deactivation event can evict the entry. Option three: load only what the request needs (a single indexed column query, not a full ORM entity with relationships).
Option four: make the lookup a single cheap query combined with the main query when the endpoint needs the same row. Never skip checks such as "account disabled" for sensitive routes; keep those fresh (shorter TTL or event-based invalidation).
In every case the dependency is cached per request already (Q42), so only the first use in a request pays.
Picture it 100 concurrent requests for the same user, loaded from a database stand-in that takes 5 ms, with and without a 30-second cache.
The setup: /a queries every time; /b consults a TTL cache first.
import asyncio, time, httpx
from typing import Annotated
from fastapi import FastAPI, Depends, Header
db_hits = {"n": 0}
def load_user_from_db(uid):
db_hits["n"] += 1; time.sleep(0.005); return {"id": uid, "role": "customer", "active": True} # 5 ms query
_cache: dict[str, tuple[float, dict]] = {}
def cached_user(uid, ttl=30.0):
hit = _cache.get(uid)
if hit and time.monotonic() - hit[0] < ttl: return hit[1]
u = load_user_from_db(uid); _cache[uid] = (time.monotonic(), u); return u
def user_every_time(x_user: Annotated[str, Header()]): return load_user_from_db(x_user)
def user_cached(x_user: Annotated[str, Header()]): return cached_user(x_user)
app = FastAPI()
@app.get("/a")
def a(u=Depends(user_every_time)): return u
@app.get("/b")
def b(u=Depends(user_cached)): return u
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for p in ("/a", "/b"):
db_hits["n"] = 0; _cache.clear(); t = time.perf_counter()
await asyncio.gather(*[c.get(p, headers={"x-user": "cust-7"}) for _ in range(100)])
print(f"{p}: 100 requests, {db_hits['n']:3} user queries, {time.perf_counter()-t:.2f}s")
asyncio.run(main())Make the invisible visible: Run it.
/a: 100 requests, 100 user queries, 0.09s
/b: 100 requests, 40 user queries, 0.05sWhat you see: The uncached route ran 100 user queries. The cached route ran 40: the first batch of concurrent requests raced past an empty cache before the first result was stored, and then every later request hit it.
Why: Notice the 40 rather than 1. A cache that is empty when a burst arrives still sends many misses to the database: the stampede problem of Q71. A lock or "single flight" would make it 1.
Naive
Query on every request.
def get_user(sub=Depends(token_sub)):
return db.get(User, sub) # ❌ 1 queryBetter
Claims plus short cache.
def get_user(claims=Depends(verify_jwt)):
return cached_user(claims["sub"], ttl=30)The shift: Authentication data changes rarely and is read constantly, so serve it from the cheapest trustworthy place.
Land it I read identity and roles from the validated token, cache the heavier user record with a short TTL and event invalidation, and keep security-critical flags fresh.
- "What about revoking a token immediately?"
Short-lived tokens limit the window, but they cannot end it. If a user is fired or a token leaks, a 15-minute token stays valid for up to 15 minutes. For instant revocation I add a small deny-list and check it in the same dependency that reads the token.
The deny-list is a Redis set (or an in-process set refreshed from Redis) holding revoked token ids (the JWT
jticlaim) or user ids. Checking it is one in-memory lookup, not a database read, so the latency win is kept.Each entry only has to live until the token would have expired anyway, so I give it the token's remaining lifetime as its TTL. The set therefore never grows without bound.
For ordinary role changes I do not revoke anything: I let the token expire and refresh. The deny-list is for the rare events, such as a stolen device or a disabled account, where waiting is not acceptable.
- "Where should the cache live, process or Redis?"
I start with process memory and move to Redis only when consistency across workers matters. The two differ in speed, in sharing, and in how eviction reaches every copy.
- Process memory: a lookup costs nanoseconds and needs no network. But each worker process and each pod has its own copy, so an eviction in one does not reach the others. You rely on the TTL to bound staleness.
- Redis: one shared copy, so an eviction is seen by every pod at once. The price is a network round trip, about a millisecond in the same data centre, plus a new component that can be down.
- Both: a tiny in-process cache (5 seconds) in front of Redis (60 seconds) keeps most reads local.
With four workers and a 30-second TTL, an in-process cache can serve a deactivated user for up to 30 seconds on every worker. If that is unacceptable for a route, I use Redis or skip the cache for that check.
- "Does the ORM identity map help?"
No, it does not help across requests. The identity map is a dictionary inside one Session, and a Session lives for one request in the canonical app. When the request ends, the session is closed and the map is thrown away. The next request builds a new session with an empty map and runs the query again.
What it does give is a saving inside a request. If three code paths each ask the session for user 42, the first one runs the SELECT and the other two get the same Python object back with no query. That is the same dependency cache idea as Q42, one layer lower.
The trap is to try to fix this by keeping a session alive between requests. A long-lived session shares one transaction and one set of objects among users, which is unsafe and not thread-safe (Q53). Cross-request reuse needs a real cache with a TTL, as in the main answer.
- "How do I stop the cache from growing forever?"
I bound it with a maximum size and a TTL, so memory stays predictable. A plain dictionary with no limit grows by one entry per distinct user and never shrinks, which is a slow memory leak that shows up as a pod killed for running out of memory days after a deploy.
The simplest fix is a library cache:
cachetools.TTLCache(maxsize=10_000, ttl=30). When it holds 10,000 entries and a new one arrives, it drops the least recently used one. Entries older than 30 seconds are treated as missing, so the TTL also bounds staleness.I pick the size from arithmetic. If one cached user is about 1 KB, 10,000 entries are about 10 MB per worker, and with four workers about 40 MB. That is a number I can check against the pod's memory limit.
Two cautions:
TTLCacheis not thread-safe, so I guard it with a lock when it is used fromdefendpoints running in the threadpool. And I watch the hit rate: a cache that is mostly evicted before it is reused only adds cost.
Q52 · Design. "Lay out the project structure (routers, schemas, services, repositories) for a 40-endpoint service and justify every layer."
Reveal answer
Strong answer Four layers with a strict rule: calls go down only. Routers speak HTTP: parse parameters, call a service, map the result to a response model and status code. Services hold business rules and own the transaction: stock checks, state transitions, idempotency. Repositories hold queries: the only code that builds select() statements. Models and schemas are data: ORM classes for storage, Pydantic classes for the API.
Why each layer exists. Without services, rules end up in endpoints and cannot be reused by a background job or tested without HTTP. Without repositories, query details leak into services and the same query gets copied. Separating schemas from models stops database changes from leaking into the contract (Q17).
At 40 endpoints I group by feature (orders/, menu/, restaurants/) once folders get crowded, each containing its own router, schemas, service and repository; shared code (core/config.py, db.py, security.py, errors.py) stays at the top. I do not add layers for their own sake: a read-only lookup endpoint can call a repository through a thin service, but I would not add a "manager" and a "facade".
The canonical QuickBite app is the small version of this.
Picture it The real layout of the course's canonical app, printed from disk.
The setup: A script walks quickbite_api/ and prints the tree (cache files hidden).
import os, pathlib
root = pathlib.Path("/home/iam100god/Desktop/AI_COURSE/code/e20-python-api/quickbite_api")
def walk(p, prefix=""):
items = sorted([x for x in p.iterdir() if x.name not in {"__pycache__", ".venv", ".pytest_cache", "uv.lock", ".deepeval"} and not x.name.endswith(".pyc")],
key=lambda x: (x.is_file(), x.name))
for i, x in enumerate(items):
last = i == len(items) - 1
print(prefix + ("└── " if last else "├── ") + x.name + ("/" if x.is_dir() else ""))
if x.is_dir(): walk(x, prefix + (" " if last else "│ "))
print("quickbite_api/"); walk(root)Make the invisible visible: Run it.
quickbite_api/
├── app/
│ ├── core/
│ │ ├── __init__.py
│ │ ├── config.py
│ │ └── logging.py
│ ├── routers/
│ │ ├── __init__.py
│ │ ├── health.py
│ │ └── orders.py
│ ├── __init__.py
│ ├── db.py
│ ├── errors.py
│ ├── main.py
│ ├── models.py
│ ├── repositories.py
│ ├── schemas.py
│ ├── security.py
│ ├── seed.py
│ └── services.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py
│ ├── test_errors_pagination.py
│ ├── test_observability.py
│ ├── test_orders.py
│ ├── test_postgres.py
│ └── test_security.py
├── .dockerignore
├── Dockerfile
├── README.md
└── pyproject.tomlWhat you see: routers/ has only HTTP code; services.py and repositories.py sit under it; models.py and schemas.py hold the two kinds of data classes; core/ holds configuration and logging; tests/ mirrors the behaviour, not the files.
Why: A new teammate can answer "where does the stock check live?" by looking at the folder names. That is the test of a layout.
Naive
Everything in the endpoint.
@router.post("")
def create(body: OrderCreate, db=Depends(s)):
item = db.get(MenuItem, ...) # query
if item.stock < ...: ... # rule
db.add(Order(...)); db.commit() # txCorrect
Router, service, repository.
@router.post("", status_code=201)
def create(body: OrderCreate,
svc: Svc = Depends(get_service)):
return svc.create_order(body)The shift: The endpoint translates HTTP; the service decides; the repository asks the database.
Land it I use routers for HTTP, services for rules and transactions, repositories for queries and separate schemas and models, with calls going down only and folders grouped by feature when the service grows.
- "Isn't a repository over SQLAlchemy redundant, since the session is already a repository?"
For small apps it can be redundant. The Session already tracks objects, loads by primary key and builds queries, so a repository that only forwards
session.getadds a layer and no value. I skip it in that case.I keep a repository when queries are non-trivial or reused, for three reasons. First, one place enforces ownership:
WHERE customer_id = :useris written once, so no endpoint forgets it and leaks another customer's order. Second, one place decides loading: theselectinloadthat prevents N+1 (Q56) lives next to the query it protects. Third, tests: a service can be tested against a fake repository without a database.With 40 endpoints the same "open orders for a restaurant" query will be wanted by a route, a report and a background job. Copy-pasting it three times is how the three copies drift apart.
My rule: a repository earns its place when it holds a query with a rule in it. Otherwise the service uses the session directly.
- "Where do transactions begin and end?"
In the service method, and nowhere else. The service wraps one business operation in
with session.begin():. The router never commits and the repository never commits. This one rule prevents most partial-write bugs.The reason is that only the service knows what "one operation" means. Placing an order is a stock decrement, an order row, its lines and an idempotency key row. If the repository committed after each insert, a crash between the second and third would leave an order with no lines.
- Router: opens nothing, commits nothing; it calls the service.
- Service: opens the transaction, calls several repository methods, and the block commits on success or rolls back if an exception escapes.
- Repository: receives the session, adds statements to the current transaction, returns data.
The same rule makes nested calls safe (Q62): inner functions take the session and never commit. When I review code, a
commit()outside a service is the first thing I flag.- "How do I stop cycles between features?"
By making features talk only through each other's service interfaces, never through each other's repositories or models. If orders needs a menu price, it calls a menu service function, which returns a small value, instead of importing the menu table.
A cycle appears when feature A imports feature B and B imports A, and Python then fails at import time or you hide the import inside a function. That hiding is the warning sign. I treat a function-level import as a design smell, not a fix.
When I find two features that need each other constantly, there are two honest answers. They may really be one feature, so I merge the folders. Or the shared piece (say, "pricing") is a third thing that both depend on, so it gets its own module that depends on neither.
The top-level shared code (
core/,db.py,errors.py) must not import any feature. A simple check in CI, such as an import-linter rule or a grep, keeps the arrows pointing down.- "Where do domain exceptions go?"
In a small
errors.pynext to the services. A domain exception names a business fact, such asOutOfStockorOrderNotFound. The service raises it, and one exception handler near the app maps each one to a Problem Details response (Q94).The key rule is that services never import FastAPI. A service that raised
HTTPException(409)would work only inside a web request. A background job or a worker script calling the same service would then catch a web exception, which makes no sense there.With domain exceptions the mapping is one table in one place:
- OutOfStock: 409, type
out-of-stock. - OrderNotFound: 404 (also used when the order belongs to someone else).
- IllegalTransition: 409.
Adding a new rule means adding one class and one line in the table. Tests assert the exception type at service level and the status code at router level, so each layer is tested for its own job.
- OutOfStock: 409, type
These questions test whether you know what the session actually does (unit of work, identity map, lazy loading), can reproduce and fix N+1, and understand the sync/async split.
Q53. "Engine, Connection and Session in SQLAlchemy 2.0 — what is each?"
Reveal answer
Strong answer The Engine is the long-lived factory for connections and owns the connection pool. One per database per process, created at start-up. It knows the URL, driver (dialect) and pool settings; it does not hold a transaction itself.
A Connection is one checked-out database connection with a transaction on it. In SQLAlchemy 2.0 it begins a transaction automatically on first use ("autobegin") and nothing is saved until you call commit(); leaving the with block without committing rolls back. It runs SQL (Core select(), text()).
A Session sits on top: the ORM's unit of work. It borrows a connection when it first needs one, tracks the objects you load and change (identity map, dirty state), writes the changes with flush(), and ends the transaction with commit() or rollback(). When closed it returns the connection to the pool.
So: Engine = pool and configuration (shared); Connection = one transaction's worth of database access (short); Session = ORM bookkeeping around that (one per request, never shared across requests or threads).
Picture it The three objects in a few lines, printing the state that proves each definition.
The setup: SQLite in memory; a table, an insert on a connection, a read through a session.
from sqlalchemy import create_engine, text, event
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool, echo=False) # Engine: the factory + connection pool
print("Engine :", engine.url, "| pool class:", type(engine.pool).__name__)
with engine.connect() as conn: # Connection: one checked-out DBAPI connection
conn.execute(text("create table t (id integer primary key, v text)"))
conn.execute(text("insert into t(v) values ('a')"))
print("Connection: in transaction =", conn.in_transaction(), "(autobegin; nothing committed yet)")
conn.commit()
with Session(engine) as session: # Session: unit of work on top of a connection
row = session.execute(text("select v from t")).scalar()
print("Session: read", repr(row), "| holds a connection now:", session.in_transaction())
print("after the with-block: session closed, connection returned to the pool, in_transaction =", session.in_transaction())Make the invisible visible: Run it.
Engine : sqlite:// | pool class: StaticPool
Connection: in transaction = True (autobegin; nothing committed yet)
Session: read 'a' | holds a connection now: True
after the with-block: session closed, connection returned to the pool, in_transaction = FalseWhat you see: The engine names its pool. The connection says it is already in a transaction after the first statement ("autobegin"). The session read the row, held a connection while open, and had released it after the with.
Why: Nothing was committed by accident: in 2.0 every statement happens inside a transaction that you must end explicitly. That is the opposite of old autocommit habits.
Java · JDBC / JPA
DataSource, Connection, EntityManager.
// illustrative
DataSource ds; // pool (Engine)
Connection c = ds.getConnection();
EntityManager em = emf.createEntityManager();Python · SQLAlchemy
Engine, Connection, Session.
engine = create_engine(url) # pool
with engine.connect() as conn: ...
with Session(engine) as session: ...The shift: The roles map one to one: pool, raw connection, persistence context; the Python names make the ORM layer optional.
Land it I say the Engine is the shared pool, a Connection is one transaction's database access, and a Session is the ORM unit of work I create per request on top of a pooled connection.
- "Why one Session per request and not a global one?"
Because a Session holds an identity map and an open transaction, and it is not thread-safe. A global session shares both among all users, which breaks in three ways.
First, transactions mix. Request A flushes an order, request B hits an error and calls
rollback(), and A's work is undone with no sign in A's code. Second, objects go stale: the identity map keeps returning old copies of rows that other transactions changed, and the map grows without limit as more rows are loaded. Third, threads race: two threads using one session at once can corrupt its internal state, because its bookkeeping is not locked.One session per request avoids all three. It gives each request its own transaction (isolation) and a clean lifetime: the
get_sessionyield dependency opens it, and the code afteryieldcloses it and returns the connection to the pool.In the canonical app that dependency is the whole pattern (
pat-session-per-request). The shared thing is the Engine, never the Session.- "What is the difference between
commit()andflush()?" flush()sends pending SQL to the database inside the current transaction.commit()flushes and then ends the transaction, making the changes permanent.After a flush, the database has run the INSERT and filled in generated values, such as an auto-increment
idor a server default, so you can read them. But the transaction is still open. Other connections do not see the row, and arollback()removes it.- Flush: use it when you need an id before the end, for example to create the order lines that point to the new order. The session also autoflushes before queries.
- Commit: use it once, at the end of the business operation, in the service.
- Failure: if a flush raises, for example a unique constraint, the transaction is inactive until you roll back (Q62).
A common mistake is to call
commit()only to get an id. Useflush()for that, and keep the commit at the boundary (Q54).- "Is
session.begin()needed?" It is not needed, but I use it. With
with session.begin():the transaction scope is written in the code and cannot be forgotten. The block commits when it ends normally and rolls back if an exception escapes.Without it, SQLAlchemy 2.0 still starts a transaction automatically ("autobegin") on the first statement. You must then call
session.commit()yourself, and every code path, including error paths, must either commit or roll back. If one path forgets, the connection goes back to the pool, or stays checked out, with an open transaction. That produces the idle-in-transaction connections that exhaust a pool (Q61).One catch:
session.begin()raises an error if a transaction has already begun, for example after a query ran earlier on the same session. So I open it at the top of the service method, before any statement, and I pass the session down rather than reopening it.The result is a visible boundary: reading the service, you can point to the lines that are one transaction.
- "Should I use Core or ORM?"
I use the ORM for entities and relationships, and Core for bulk work and reports. They are not rivals: Core is the SQL expression layer under the ORM, and both use the same engine and the same session.
The ORM is good when you load an order, change a field and save. It tracks the change, orders the SQL and handles relationships. It is a poor fit for "mark 50,000 rows as expired" or a report with window functions, where loading objects first only wastes memory and time.
So in the repository I mix. A typical order flow uses ORM objects for the order and lines, and a Core
update()withWHERE stock >= :qfor the atomic stock decrement (Q63). A daily report usesselect()withfunc.sumand returns plain rows.The rule I follow: reach for Core when the work is set-based (many rows, one statement) and for the ORM when the work is object-based (one entity, a few fields). Never build either with string formatting (Q65).
Q54. "Session, unit of work and identity map — compare them with JPA's persistence context."
Reveal answer
Strong answer They are the same idea. A SQLAlchemy Session and a JPA EntityManager (persistence context) both keep a unit of work: objects you load are tracked, changes are noticed, and on flush or commit the library emits the SQL in a safe order. Both keep an identity map: within one session, loading the same row twice returns the same Python or Java object, and issues no second query.
Differences. SQLAlchemy has no automatic dirty-checking on every query as aggressively as JPA flush modes, but it does autoflush before queries by default so queries see pending changes. JPA entities are managed by the container and often proxied; SQLAlchemy instances are plain objects with instrumented attributes. @Transactional hides the boundary in Spring; in SQLAlchemy you write with session.begin():.
Lifecycle states are similar: transient (new, not added), pending (added, not flushed), persistent (in the session and database), detached (session closed or object expunged), deleted. Touching a lazy relationship on a detached object fails (DetachedInstanceError), the same family as JPA's LazyInitializationException.
Picture it One object read twice, modified, flushed and rolled back, with each SQL statement counted.
The setup: A single Order row with status "placed".
from sqlalchemy import create_engine, String, event
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
status: Mapped[str] = mapped_column(String(20))
engine = create_engine("sqlite://"); Base.metadata.create_all(engine)
sql = []
event.listen(engine, "before_cursor_execute", lambda c, cur, stmt, *a: sql.append(stmt.split()[0]))
with Session(engine) as s:
s.add(Order(id=1, status="placed")); s.commit()
sql.clear()
a = s.get(Order, 1); b = s.get(Order, 1) # identity map: second get costs no query
print("same Python object for the same row:", a is b, "| statements:", sql)
a.status = "preparing" # unit of work: change is only tracked...
print("dirty objects:", [o.id for o in s.dirty], "| statements so far:", sql)
s.flush() # ...until flush writes it
print("after flush :", sql)
s.rollback()
print("after rollback, reload sees:", s.get(Order, 1).status)Make the invisible visible: Run it.
same Python object for the same row: True | statements: ['SELECT']
dirty objects: [1] | statements so far: ['SELECT']
after flush : ['SELECT', 'UPDATE']
after rollback, reload sees: placedWhat you see: Two gets returned the same Python object and only one SELECT ran (identity map). Changing status made the object dirty but sent nothing. flush() emitted the UPDATE. After rollback() the reload showed the original value.
Why: The session buffered the change and decided when to write it. That is the unit of work: your code edits objects, the session turns the edits into SQL.
JPA · Hibernate
Managed entity, dirty checking.
// illustrative
@Transactional
void ready(long id) {
Order o = em.find(Order.class, id);
o.setStatus("ready"); // UPDATE at commit
}SQLAlchemy
Persistent object, flush.
def ready(self, order_id):
with self.session.begin():
o = self.session.get(Order, order_id)
o.status = "ready" # UPDATEThe shift: In both, you change objects and the session writes SQL; the Python version just shows the transaction block.
Land it I describe the Session as JPA's persistence context: identity map, dirty tracking and a flush that writes ordered SQL, with the transaction boundary written explicitly.
- "What does autoflush do and why does it matter?"
Autoflush means the session writes its pending changes to the database before running a query, so the query sees them. It matters because it makes results match what your code did, but it moves errors in time.
Take this sequence: you add an order with a duplicate unique value on line 10, and on line 12 you run a SELECT. The INSERT is only sent at line 12, so the integrity error is raised at the SELECT line and the stack trace points there. People then debug the wrong line.
The other effect is performance: a loop that adds an object and then queries each time sends an INSERT before every query.
- Pause it: inside
with session.no_autoflush:queries do not flush, which is useful when the objects are half-built and would fail constraints. - Flush deliberately: call
session.flush()where you want the failure to appear.
I leave autoflush on by default and read the trace with this in mind.
- Pause it: inside
- "What is
expire_on_commit?" expire_on_commitcontrols what happens to loaded objects after a commit. By default it is true: commit marks every attribute of every loaded object as expired, and the next access reloads it with a SELECT.The idea is safety: after a commit other transactions may have changed the rows, so the old values are not trusted. The cost is hidden queries. Code that commits, then reads
order.statusto build the response, quietly runs one query per object.In async code the hidden query cannot run inside an attribute read, so it fails with
MissingGreenlet(Q59). That is why async sessionmakers are normally created withexpire_on_commit=False.- Sync, default on: fine for short request-scoped sessions; accept or avoid the extra query.
- Async, set False: the objects keep their values after commit.
The trade-off with False is that the values may be slightly stale, which is fine when the session is closed right after the response is built.
- "What are the object states and why care?"
There are four states, and the important question is which of them can still reach the database. The states are transient, pending, persistent and detached (plus deleted).
- Transient: a new object, not added to a session, with no row.
- Pending: added with
session.add, but no SQL sent yet. - Persistent: in a session and in the database, after a flush or a load.
- Detached: had a row, but its session is closed or it was expunged.
A detached object keeps the values it already loaded, but it cannot lazy-load anything else, because no session is there to run the query. Touching an unloaded relationship raises
DetachedInstanceError, the same family as JPA'sLazyInitializationException.The classic bug: an endpoint returns an ORM object from a function that has already closed its session, and FastAPI serialises it afterwards, touching
order.lines. It works in tests on loaded data and fails in production on a different path. The fix is to build the response model inside the session, or to eager-load what the response needs.- "Can the identity map return stale data?"
Yes, within one session. Once a row is loaded into the identity map, later loads of the same row return the same Python object without refreshing its values. If another transaction changes the row in the meantime, your object keeps showing the old data.
The reason is the design: the map guarantees that one row is one object, so the session can track your changes without conflicting copies. It will not overwrite attributes you may have modified.
For a short request-scoped session this is harmless. The session lives for tens of milliseconds and is then discarded, so the staleness window is tiny.
It becomes a real bug in long-lived sessions, such as a worker that holds one session while it loops over a queue for an hour. Each item sees data frozen at its first load.
- Refresh:
session.refresh(obj)reloads the row now. - Expire:
session.expire(obj)reloads on next access. - Better: use a new session per unit of work, as the service does.
- Refresh:
Q55. "Typed declarative models with Mapped[] and mapped_column."
Reveal answer
Strong answer SQLAlchemy 2.0 declares ORM classes with Python type annotations. A class inherits from DeclarativeBase; each column is an annotated attribute: id: Mapped[int] = mapped_column(primary_key=True). The annotation tells both SQLAlchemy and your type checker what the attribute holds.
Nullability comes from the type: Mapped[int] means NOT NULL, Mapped[str | None] means nullable. mapped_column(...) adds what a type cannot say: String(20) length, index=True, ForeignKey(...), default= (Python side) and server_default= (database side, such as func.now()).
Relationships are Mapped[list["OrderLine"]] = relationship(back_populates="order"): a typed collection, loaded lazily by default. Money stays an integer column (total_cents: Mapped[int]), never Float.
Benefits over the old untyped style: autocomplete and mypy catch order.totl, the column set is readable in one place, and Mapped[...] makes the schema reviewable. These classes are the ORM model of the three-model rule; they are never returned directly from an endpoint (Q17).
Picture it The DDL SQLAlchemy would send to PostgreSQL for a small Order class, compiled without a database.
The setup: note is str | None; total_cents is plain int; created_at has a server default.
from datetime import datetime
from sqlalchemy import ForeignKey, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
from sqlalchemy.schema import CreateTable
from sqlalchemy.dialects import postgresql
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(index=True)
status: Mapped[str] = mapped_column(String(20), default="placed")
note: Mapped[str | None] # Optional type -> nullable column
total_cents: Mapped[int] # plain Mapped[int] -> NOT NULL
created_at: Mapped[datetime] = mapped_column(server_default=func.now())
lines: Mapped[list["OrderLine"]] = relationship(back_populates="order")
class OrderLine(Base):
__tablename__ = "order_lines"
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"))
qty: Mapped[int]
order: Mapped["Order"] = relationship(back_populates="lines")
print(CreateTable(Order.__table__).compile(dialect=postgresql.dialect()))Make the invisible visible: Run it.
CREATE TABLE orders (
id SERIAL NOT NULL,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL,
note VARCHAR,
total_cents INTEGER NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT now() NOT NULL,
PRIMARY KEY (id)
)What you see: note became a nullable VARCHAR; total_cents is INTEGER NOT NULL; status has its length 20; created_at has DEFAULT now(); id became SERIAL on PostgreSQL.
Why: The annotation is the schema. The same classes feed Alembic's autogenerate (Q67), so reading the model tells you the table.
JPA · Hibernate
Annotations on fields.
// illustrative
@Entity class Order {
@Id @GeneratedValue Long id;
@Column(nullable = false) int totalCents;
String note; // nullable by default
}SQLAlchemy 2.0
Types on attributes.
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(
primary_key=True)
total_cents: Mapped[int]
note: Mapped[str | None]The shift: Java makes everything nullable unless told otherwise; the Python type decides nullability for you.
Land it I write models with Mapped and mapped_column so the types document and enforce nullability, keep money as integer cents, and never expose these classes in responses.
- "
defaultversusserver_default?" The difference is who computes the value and which clients are covered.
default=is computed by SQLAlchemy in Python at insert time.server_default=is part of the table definition, so the database computes it, for inserts from any client.That second point is the one that matters. If an engineer inserts a row with psql, or another service writes to the same table, a Python
defaultis not applied, because that code path never ran SQLAlchemy. Aserver_defaultstill applies. It is also visible in Alembic migrations as part of the schema.For timestamps I use
server_default=func.now(). Then the database clock is the one source, and application pods with slightly different clocks cannot produce out-of-ordercreated_atvalues.- Python default: good for values the database cannot compute, such as a generated UUID or a value from application code.
- Server default: good for timestamps and constants; it must be a database expression.
Note that a server default is only visible on the object after a flush plus a refresh, because the database makes it.
- "How do I model an enum column?"
I map it as
Mapped[OrderStatus]with a Pythonenum.Enum, but store it as a string rather than as a database enum type. The reason is migration pain in PostgreSQL.A native PostgreSQL enum is a separate type. Adding a value is easy, but removing or renaming one is hard, and changes interact badly with transactions in older versions. Teams end up writing awkward migrations just to retire a status.
A string column avoids that. In SQLAlchemy you get it with
native_enum=False, which stores the names as text. To keep the data honest, add aCHECKconstraint listing the allowed values, so a typo from another client is rejected by the database.Often I go one step simpler: a plain
String(20)column, plus aLiteral["placed", "preparing", ...]type in the Pydantic schema and the state machine in the service. Pydantic rejects bad input at the edge with a 422.My rule: the database holds the cheap-to-change shape, and the service owns which transitions are legal (Q66).
- "Why is lazy
relationshipthe default and is that bad?" Lazy loading is the default because it is safe and cheap for objects you never touch: a relationship you do not read costs no query. The problem is that it hides the cost. A plain attribute read,
order.lines, runs SQL.That causes the two failures the chapter covers. In a loop over 50 orders it is N+1 (Q56): 51 statements. In async code, it cannot run at all and raises
MissingGreenlet(Q59).So I treat lazy loading as a trap in service code, and I set
lazy="raise"on the relationship. Any access to an unloaded relationship then raises an error immediately, in both sync and async, instead of running a surprise query. Each query must say what it needs:- Detail endpoint:
selectinload(Order.lines). - List endpoint: no lines at all, a summary only.
- Test: the suite fails on the first unplanned access.
Lazy stays fine in scripts and notebooks, where one extra query is not a problem.
- Detail endpoint:
- "Do type annotations validate data?"
No. The annotation
Mapped[int]tells SQLAlchemy the column type and nullability and tells your type checker what to expect. It does not check values at runtime. If you assign a string to anintattribute, SQLAlchemy does not stop you.What happens next depends on the database. PostgreSQL rejects a string that is not a number when the INSERT runs, with an error that looks like a server fault. SQLite is looser and may store the value anyway, which is one reason to test on the real engine.
The real enforcement is layered, and each layer has its own job:
- Pydantic: validates input at the boundary and returns a 422 with field names (Q21).
- Database: NOT NULL,
CHECK (qty > 0), foreign keys and unique constraints, which hold even when the app has a bug. - Type checker: mypy catches wrong attribute names and types before the code runs.
I never rely on annotations alone for safety. They are documentation that tools can check, not a guard.
Q56 · Scenario. "An endpoint listing 50 orders issues 51 queries. Diagnose and fix."
Reveal answer
Strong answer This is the N+1 query problem: one query loads the orders (the "1"), and then touching order.lines on each of the 50 orders runs one lazy-load query per order (the "N"). Each is cheap in a local test and costly in production: 51 round trips of 15 to 20 ms each become about a second.
Diagnose: log SQL (echo=True in development), count statements per request with an event listener or an OpenTelemetry SQL instrumentor, and add a test that asserts "at most 3 statements for this endpoint". The pattern in logs is the same SELECT ... FROM order_lines WHERE order_id = ? repeated with different ids.
Fix: tell the query to load the relationship up front. selectinload(Order.lines) runs a second query with WHERE order_id IN (...): 2 statements regardless of N, and no row duplication. joinedload(Order.lines) fetches in one LEFT OUTER JOIN: 1 statement, but rows repeat for each line and SQLAlchemy requires .unique() for collections. For list endpoints I default to selectinload.
Part B measured the same numbers: 51 lazy, 2 with selectinload, 1 with joinedload.
Picture it 50 orders with 2 lines each, loaded three ways, with the statement count from an event listener.
The setup: The listener counts every statement sent to SQLite.
from sqlalchemy import create_engine, ForeignKey, select, event
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, Session, selectinload, joinedload
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int]
lines: Mapped[list["OrderLine"]] = relationship(back_populates="order")
class OrderLine(Base):
__tablename__ = "order_lines"
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"))
qty: Mapped[int]
order: Mapped["Order"] = relationship(back_populates="lines")
engine = create_engine("sqlite://"); Base.metadata.create_all(engine)
with Session(engine) as s:
for i in range(1, 51):
s.add(Order(id=i, customer_id=7, lines=[OrderLine(qty=1), OrderLine(qty=2)]))
s.commit()
n = {"q": 0}
event.listen(engine, "before_cursor_execute", lambda *a: n.__setitem__("q", n["q"] + 1))
def run(label, opt=None, unique=False):
n["q"] = 0
with Session(engine) as s:
stmt = select(Order).where(Order.customer_id == 7)
if opt is not None: stmt = stmt.options(opt)
res = s.execute(stmt); orders = (res.unique() if unique else res).scalars().all()
total_lines = sum(len(o.lines) for o in orders)
print(f"{label:22} {n['q']:3} statements | {len(orders)} orders, {total_lines} lines")
run("lazy (default)")
run("selectinload", selectinload(Order.lines))
run("joinedload + unique", joinedload(Order.lines), unique=True)
try: run("joinedload no unique", joinedload(Order.lines))
except Exception as e: print("joinedload without .unique():", type(e).__name__)Make the invisible visible: Run it.
lazy (default) 51 statements | 50 orders, 100 lines
selectinload 2 statements | 50 orders, 100 lines
joinedload + unique 1 statements | 50 orders, 100 lines
joinedload without .unique(): InvalidRequestErrorWhat you see: Lazy loading used 51 statements, selectinload 2, joinedload 1. All returned the same 50 orders and 100 lines. joinedload on a collection without .unique() raised InvalidRequestError rather than silently returning duplicate rows.
Why: SQLAlchemy 2.0 refuses the ambiguous case loudly. The error text says to call .unique(), which removes the duplicates the join created.
Naive
Lazy loading in a loop.
orders = s.scalars(select(Order)).all()
out = [(o.id, len(o.lines)) # ❌ query per order
for o in orders]Correct
Eager load in the query.
stmt = select(Order).options(
selectinload(Order.lines)) # ✅ 2 queries
orders = s.scalars(stmt).all()The shift: Decide what to load when you write the query, not when you touch the attribute.
Land it I count statements per endpoint in a test, and fix N+1 with selectinload in the repository query, using joinedload only for single-row to-one joins.
- "Why not always
joinedload?" Because one query is not always cheaper. A join repeats every parent column on every child row, so the result can be much larger than two simple queries.
Work it through with 50 orders, each with 10 lines. The join returns 500 rows, and each row carries all the order columns (customer, address, notes) again. The selectin approach sends 50 order rows, then 500 line rows with only line columns. Less data crosses the network.
The worse case is joining two collections at once, say lines and status history. Each order then returns lines times history rows: 10 lines and 5 history entries give 50 rows per order, 2,500 in total, for 50 orders. This is the cartesian explosion, and SQLAlchemy cannot make it smaller.
A collection join combined with
LIMITalso forces a subquery rewrite (Q57).For to-one relations, such as order to customer, the join adds one column set per order and no duplication, so
joinedloadis ideal there. My default:selectinloadfor collections,joinedloadfor to-one.- "How do I stop N+1 from reappearing?"
By making an accidental lazy load fail loudly, and by testing the statement count. Fixing the endpoint once is easy. Keeping it fixed as 40 endpoints change is the hard part.
- lazy="raise": set it on relationships, so any lazy load that was not planned raises an error instead of running a query. Every query must now say what it loads.
- Statement-count test: an event listener on the engine counts statements during a request, and the test asserts "at most 3" for the list endpoint. A new field that touches a relationship breaks the test in CI, not in production.
- Logs in development:
echo=Trueshows the sameSELECT ... WHERE order_id = ?repeating.
The first catches the mistake where it is written; the second catches it where it is shipped. With both in place, the number 51 cannot come back unnoticed, because the build fails when an endpoint goes from 2 statements to 51.
- "What if I only need the count of lines?"
Do not load the lines at all. Loading 10 line objects to call
len()on them moves all their columns across the network, builds 10 Python objects and throws them away.Ask the database to count. For a list of orders, one grouped query returns the counts for all of them:
line counts per orderruns offlinestmt = ( select(OrderLine.order_id, func.count()) .where(OrderLine.order_id.in_(order_ids)) .group_by(OrderLine.order_id) ) counts = dict(session.execute(stmt).all())That is one statement for any number of orders, returning two small columns. You then read
counts.get(order.id, 0)when you build each summary.Two alternatives: a correlated scalar subquery in the main SELECT, so the count arrives with each order row, or a
column_propertyon the model if the count is needed almost everywhere. If the count is read often and orders are huge, a storedline_countcolumn kept up to date in the same transaction is also reasonable.- "Does the problem exist with async sessions?"
Yes, and it is worse. In sync code a lazy load is only slow: it runs one extra query and the code carries on. In async code, the attribute read cannot await, so SQLAlchemy raises
MissingGreenletinstead (Q59).That makes the failure louder, and in a sense safer: you find out in the first test instead of in production latency graphs. But it also means a sync codebase with hidden N+1 patterns cannot be moved to async without work. Every relationship the code touches must be loaded explicitly first.
For async I follow three rules:
- Eager-load in the query:
selectinloadfor collections,joinedloadfor to-one. - lazy="raise": so a missed case fails the same way everywhere.
- expire_on_commit=False: so commit does not mark loaded attributes as expired.
If a rare case really needs lazy loading,
await order.awaitable_attrs.linesmakes the extra query explicit. The N+1 shape is the same in both worlds, and so is the fix.- Eager-load in the query:
Q57. "selectinload versus joinedload versus subqueryload."
Reveal answer
Strong answer All three load a relationship together with its parent to avoid N+1. They differ in the SQL they send.
joinedload adds a LEFT OUTER JOIN to the parent query: one statement; parent columns repeat per child, so collections need .unique(); best for to-one relationships and small collections. selectinload runs the parent query, then a second query ... WHERE child.parent_id IN (id1, id2, ...): two statements, no duplicates, works well with pagination (LIMIT applies to parents only); the default recommendation for collections. subqueryload runs the child query with the parent query as a subquery: two statements, but the parent query repeats inside the second one, so it costs more and is rarely needed now.
Pitfalls. joinedload combined with LIMIT on a collection forces SQLAlchemy to wrap the parent query in a subquery to limit parents correctly, which gets heavy. Very large IN lists in selectinload are chunked by SQLAlchemy (500 ids at a time by default).
My default: selectinload for collections, joinedload for many-to-one, and measure for the odd case.
Picture it The SQL each strategy actually sent for three orders.
The setup: Order.lines loaded each way; statements captured by a listener.
from sqlalchemy import create_engine, ForeignKey, select, event
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, Session, selectinload, joinedload, subqueryload
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int]
lines: Mapped[list["OrderLine"]] = relationship()
class OrderLine(Base):
__tablename__ = "order_lines"
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"))
engine = create_engine("sqlite://"); Base.metadata.create_all(engine)
with Session(engine) as s:
s.add_all([Order(id=i, customer_id=7, lines=[OrderLine(), OrderLine()]) for i in (1, 2, 3)]); s.commit()
log = []
event.listen(engine, "before_cursor_execute", lambda c, cur, stmt, p, *a: log.append(" ".join(stmt.split())))
for name, opt in (("selectinload", selectinload(Order.lines)), ("joinedload", joinedload(Order.lines)), ("subqueryload", subqueryload(Order.lines))):
log.clear()
with Session(engine) as s:
orders = s.execute(select(Order).where(Order.customer_id == 7).options(opt)).unique().scalars().all()
print(f"--- {name}: {len(log)} statement(s)")
for st in log: print(" ", st[:150])Make the invisible visible: Run it.
--- selectinload: 2 statement(s)
SELECT orders.id, orders.customer_id FROM orders WHERE orders.customer_id = ?
SELECT order_lines.order_id AS order_lines_order_id, order_lines.id AS order_lines_id FROM order_lines WHERE order_lines.order_id IN (?, ?, ?)
--- joinedload: 1 statement(s)
SELECT orders.id, orders.customer_id, order_lines_1.id AS id_1, order_lines_1.order_id FROM orders LEFT OUTER JOIN order_lines AS order_lines_1 ON ord
--- subqueryload: 2 statement(s)
SELECT orders.id, orders.customer_id FROM orders WHERE orders.customer_id = ?
SELECT order_lines.id AS order_lines_id, order_lines.order_id AS order_lines_order_id, anon_1.orders_id AS anon_1_orders_id FROM (SELECT orders.id AS What you see: selectinload sent the parent query and then WHERE order_lines.order_id IN (?, ?, ?). joinedload sent one LEFT OUTER JOIN. subqueryload sent the child query with an inner SELECT of the parents.
Why: Reading the generated SQL tells you the cost model: IN list size for selectin, row multiplication for joined, a repeated parent query for subquery.
joinedload
One query, rows repeat.
SELECT o.*, l.*
FROM orders o
LEFT OUTER JOIN order_lines l
ON l.order_id = o.id;selectinload
Two queries, no repeats.
SELECT * FROM orders WHERE customer_id = ?;
SELECT * FROM order_lines
WHERE order_id IN (?, ?, ?);The shift: Trade one wide query with duplicated parents for two narrow queries that fetch each row once.
Land it I default to selectinload for collections and joinedload for to-one relations, and I read the generated SQL when I choose.
- "Why does
joinedloadplusLIMITmisbehave?" Because a joined result has one row per child, and LIMIT counts rows, not parents. Take orders with three lines each and write
LIMIT 10: the join returns ten rows, which is roughly three and a third orders, and the last order may have only some of its lines loaded.That would give you half an order, which is wrong. So SQLAlchemy rewrites the statement. It wraps the parent query with its LIMIT in a subquery, so exactly 10 parents are selected first, and then joins the lines to that subquery. The result is correct, but the SQL is bigger and the database has more work to plan.
Compare
selectinload. The parent query runs by itself withLIMIT 10and returns exactly 10 orders. The second query then loads lines for those ten ids withWHERE order_id IN (...). Both are simple and fast.So for a paginated list with a collection I choose
selectinload, and I read the generated SQL (echo=True) when I am unsure.- "Can I choose a strategy per relationship globally?"
Yes.
relationship(lazy="selectin")makes selectin the default loader for that relationship. Every query that loads the parent then also loads the children, without writing.options(...).The cost is that it applies even when you do not need the children. A list endpoint that shows only order ids and totals would still run the extra query for lines. At 50 orders per page that is one wasted statement and a few hundred wasted rows on every request.
So I prefer to choose per query, in the repository:
- List query: no options, summary columns only.
- Detail query:
.options(selectinload(Order.lines)). - Report query: whatever that report needs.
The model then stays neutral, with
lazy="raise"as the safety net, and each query declares its own needs. A global default is acceptable for a small relationship that is read nearly every time, such as a restaurant's opening hours, where leaving it out would be rare.- "How do I load nested relationships?"
By chaining the options, one per level. For orders, their lines, and each line's menu item, I write
selectinload(Order.lines).selectinload(OrderLine.menu_item).Each level adds one statement, so the cost is constant in the number of rows. Three levels means three statements whether there are 5 orders or 500.
statements for a nested loadruns offline1 SELECT ... FROM orders ... LIMIT 50 2 SELECT ... FROM order_lines WHERE order_id IN (50 ids) 3 SELECT ... FROM menu_items WHERE id IN (ids from the lines)The third query only asks for the distinct menu items that the lines point to, so shared items are fetched once.
For a to-one step you can mix strategies:
selectinload(Order.lines).joinedload(OrderLine.menu_item)folds the menu item into the line query, giving two statements. The caution is depth: past three levels the code is usually a sign that the endpoint should return a smaller shape or use a purpose-built query.- "Which is fastest?"
It depends on the shape of the data and on the network, and I will not claim a winner without measuring. Each strategy wins in a different situation.
- High latency to the database: every round trip is costly. At 20 ms per trip,
joinedload(1 statement) saves about 20 ms overselectinload(2 statements). Fewer trips win. - Wide parents, many children: a join repeats the parent columns for each child, so it transfers more bytes. Selectin wins.
- To-one relation: the join adds no duplication, so joined wins.
When latency is small, as on a database in the same zone with 1 ms round trips, the extra statement hardly matters and the data size dominates.
The way I settle it is a small benchmark with realistic data: a few thousand parents and their real average number of children, run against the real database engine, not three rows on SQLite. I compare both statement count and time per request, then record the decision in a comment next to the query so the next person does not have to guess.
- High latency to the database: every round trip is costly. At 20 ms per trip,
Q58. "Sync or async SQLAlchemy — when is async worth it?"
Reveal answer
Strong answer Async SQLAlchemy (create_async_engine, AsyncSession, await session.execute(...)) uses an async driver (asyncpg, psycopg 3 async, aiosqlite) so waiting for the database does not block the event loop. Sync SQLAlchemy uses a normal driver, which blocks the calling thread; in FastAPI that is fine in a plain def endpoint, which already runs in the 40-thread pool.
Async is worth it when you have many concurrent requests that mostly wait on I/O and want to hold thousands in flight on few threads, or when the rest of the endpoint is async anyway (calls to httpx.AsyncClient, Redis, streaming). It is not faster for a single query; the speed-up is capacity.
Sync-in-threadpool is worth it when the app is mostly CRUD with modest concurrency, the team knows the sync API, you rely on lazy loading and ORM conveniences, or you use libraries without async support. It is simpler and has fewer traps.
The traps of async: lazy loading raises MissingGreenlet (Q59), expire_on_commit surprises, mixing sync and async sessions in one request, and a pool that becomes the queue for thousands of waiting coroutines.
Picture it A quick comparison of 200 tiny queries on SQLite, async driver versus sync session in threads.
The setup: This is not a fair latency test: SQLite is in-process, with no network round trip. It only shows both styles working side by side.
import asyncio, time
from sqlalchemy import create_engine, text
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
async_engine = create_async_engine("sqlite+aiosqlite://", poolclass=StaticPool)
async def async_query(i):
async with AsyncSession(async_engine) as s: # await at every I/O step
return (await s.execute(text("select :i"), {"i": i})).scalar()
async def main():
async with async_engine.begin() as c: await c.execute(text("select 1"))
t = time.perf_counter()
r = await asyncio.gather(*[async_query(i) for i in range(200)])
print(f"async : 200 tiny queries, {time.perf_counter()-t:.3f}s, results ok: {r[:3]}...")
await async_engine.dispose()
sync_engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
def sync_query(i):
with Session(sync_engine) as s: return s.execute(text("select :i"), {"i": i}).scalar()
t = time.perf_counter()
r = await asyncio.gather(*[asyncio.to_thread(sync_query, i) for i in range(200)])
print(f"sync : 200 tiny queries in threads, {time.perf_counter()-t:.3f}s")
print("SQLite is in-process, so this shows API shape, not network latency; with a 5 ms network round trip both overlap waits.")
asyncio.run(main())Make the invisible visible: Run it.
async : 200 tiny queries, 0.093s, results ok: [0, 1, 2]...
sync : 200 tiny queries in threads, 0.049s
SQLite is in-process, so this shows API shape, not network latency; with a 5 ms network round trip both overlap waits.What you see: Both finished 200 queries in well under a tenth of a second here, and the thread version was slightly faster, because there is no real waiting to overlap and async adds bookkeeping per await.
Why: That result is the honest answer to "is async faster?": for fast local calls, no. The case for async is hundreds or thousands of requests waiting on a 5 to 50 ms network database at once.
Sync · plain def
Blocking driver in the threadpool.
@router.get("/{order_id}")
def get(order_id: int,
s: Session = Depends(sess)):
return s.get(Order, order_id)Async · async def
Awaiting driver on the loop.
@router.get("/{order_id}")
async def get(order_id: int,
s: AsyncSession = Depends(asess)):
return await s.get(Order, order_id)The shift: The function bodies look alike; the difference is who waits, a pool thread or the event loop.
Land it I choose async SQLAlchemy only when I need high I/O concurrency or the endpoint is async end to end, and otherwise I use sync sessions in plain def endpoints for simplicity.
- "How does the sync approach hit its limit?"
The limit is concurrent requests that hold a thread while they wait. FastAPI runs plain
defendpoints in AnyIO's threadpool, whose default limiter is 40 tokens. The 41st simultaneous request waits for a free thread.Work out what 40 threads can serve. If a request spends 20 ms waiting on the database, one thread handles 1000 / 20 = 50 requests per second. Forty threads then give 40 x 50 = 2,000 requests per second per worker, assuming the database keeps up.
threadpool capacityruns offline1000 ms / 20 ms per request = 50 requests/s per thread 50 x 40 threads = 2,000 requests/s per workerThat is plenty for most services. The limit bites when requests are long, for example a 2-second call to a slow partner API: then one thread serves only 0.5 requests per second and 40 threads serve 20.
My order of action: raise the limiter, add worker processes, then consider async, because those steps change a setting, not the code. Async is the answer when waiting is long and concurrency must reach the thousands.
- "What about
run_syncand mixing?" AsyncSession.run_sync(fn)runs a normal synchronous function inside the async session's greenlet context. The function receives a syncSession, and any blocking ORM call inside it, even a lazy load, works, because it is executed through the async driver underneath.It is a bridge, not a goal. Two real uses: libraries that expect a sync session or connection, and Alembic when your app uses an async engine. Alembic's migration code is synchronous, so the usual
env.pyopens an async connection and callsconnection.run_sync(do_migrations).The caution is the other kind of mixing: using a sync
Sessionand anAsyncSessionin the same request. They hold separate connections and transactions, so they cannot see each other's uncommitted work, and you can double the pool use of one request.My rule is one style per request path. If an endpoint is async, every database access in it goes through the async session, and
run_syncis confined to small adapter functions.- "Which drivers for PostgreSQL?"
For PostgreSQL, I choose
psycopg3 unless I have a measured reason for something else. It supports both styles with one library: a sync connection and an async connection, with the same SQL behaviour. The course machine has psycopg 3.3.5.- Sync:
postgresql+psycopg://with psycopg 3. The olderpsycopg2still works and is widespread, but it is in maintenance mode. - Async:
postgresql+psycopg_async://(psycopg 3 async) orpostgresql+asyncpg://. - asyncpg: has its own binary protocol implementation and is often quicker in benchmarks, but it behaves differently in details such as prepared statements, which matters behind PgBouncer.
Check the dialect names against the SQLAlchemy documentation for your version before copying a URL.
The benefit of psycopg 3 is a team that runs a sync API and an async worker with one set of habits and one driver to upgrade. I would pick asyncpg when a profile shows the driver is the bottleneck, which is rare.
- Sync:
- "Can I avoid MissingGreenlet without learning greenlets?"
Yes, with discipline, and without needing to understand greenlets. MissingGreenlet is the symptom of one thing: an attribute read tried to run a query. If no attribute read can ever need a query, the error cannot occur.
Three habits make that true:
- Eager-load in the query: every relationship the response needs is named with
selectinloadorjoinedload. - expire_on_commit=False: after a commit, loaded attributes are not marked expired, so reading them needs no refresh query.
- Read only what you loaded: build the response model from loaded data, while the session is open.
Add
lazy="raise"as the guard. It turns a slip into an immediate, clear error in tests, with the name of the relationship, instead of a confusing greenlet message.If the team cannot guarantee these habits, because many people touch the code or the models are deep, then the honest answer is sync sessions in plain
defendpoints (Q59). A simpler tool used correctly beats a faster one used with luck.- Eager-load in the query: every relationship the response needs is named with
Q59 · Scenario. "MissingGreenlet appears when an async endpoint touches order.lines. Why?"
Reveal answer
Strong answer Attribute access is synchronous Python: order.lines cannot await. If the relationship was not loaded, SQLAlchemy would need to run a SQL query right there, inside a plain attribute read, which the async driver can only do by awaiting. SQLAlchemy cannot await from a normal attribute access, so it raises MissingGreenlet ("greenlet_spawn has not been called; can't call await_only() here").
In sync code the same access silently runs a lazy-load query, which is why the bug only shows up when you switch to async. The error is a favour: it tells you an implicit query was about to happen.
Fixes. One: eager-load in the query (selectinload(Order.lines)), then order.lines is already in memory. Two: use await session.refresh(order, ["lines"]) to load on demand. Three: lazy="raise" on the relationship so mistakes fail the same way in sync and async. Four: set expire_on_commit=False on the async sessionmaker, because after commit() attributes are expired and touching them triggers the same error.
Serialise in the endpoint while the session is open or from loaded data only.
Picture it The error text, then the two working alternatives.
The setup: An async SQLite session; an order with two lines.
import asyncio
from sqlalchemy import ForeignKey, select
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, selectinload
from sqlalchemy.pool import StaticPool
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
lines: Mapped[list["OrderLine"]] = relationship()
class OrderLine(Base):
__tablename__ = "order_lines"
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"))
async def main():
engine = create_async_engine("sqlite+aiosqlite://", poolclass=StaticPool)
async with engine.begin() as c: await c.run_sync(Base.metadata.create_all)
async with AsyncSession(engine, expire_on_commit=False) as s:
s.add(Order(id=1, lines=[OrderLine(), OrderLine()])); await s.commit()
async with AsyncSession(engine) as s:
order = (await s.execute(select(Order))).scalars().first()
try: print(len(order.lines)) # ❌ TRAP: implicit lazy load needs I/O
except Exception as e: print(type(e).__name__, "|", str(e)[:150])
async with AsyncSession(engine) as s:
order = (await s.execute(select(Order).options(selectinload(Order.lines)))).scalars().first()
print("with selectinload, lines =", len(order.lines)) # ✅ already loaded, no I/O
async with AsyncSession(engine) as s:
order = (await s.execute(select(Order))).scalars().first()
await s.refresh(order, ["lines"]); print("with await refresh, lines =", len(order.lines))
await engine.dispose()
asyncio.run(main())Make the invisible visible: Run it.
MissingGreenlet | greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlal
with selectinload, lines = 2
with await refresh, lines = 2What you see: Touching order.lines raised MissingGreenlet with the greenlet message. Loading with selectinload worked, and so did an explicit await session.refresh(order, ["lines"]).
Why: Both fixes do the I/O in an awaited step before the attribute is read. The attribute access itself stays pure memory.
Naive
Implicit lazy load.
order = (await s.execute(select(Order))).scalar()
n = len(order.lines) # ❌ MissingGreenletCorrect
Load before you touch.
stmt = select(Order).options(
selectinload(Order.lines))
order = (await s.execute(stmt)).scalar()
n = len(order.lines) # ✅ in memoryThe shift: In async code, every query must be an explicit await, so relationships need to be loaded in the query, not discovered later.
Land it I treat MissingGreenlet as SQLAlchemy refusing a hidden query: I eager-load in the statement, set lazy raise and expire_on_commit False, and never touch unloaded attributes.
- "Why does it appear after
commit()even without relationships?" Because commit also expires the attributes, not only because of relationships. With
expire_on_commit=True, the default, the session marks every loaded attribute of every object as expired when it commits. The next read oforder.statusthen needs a SELECT to reload it.In sync code that reload runs silently. In async code the read is a plain attribute access that cannot await, so you get
MissingGreenleton a column that looks as simple as can be. That surprises people, because the model has no relationship at all.A typical sequence:
await session.commit(), thenreturn OrderOut.model_validate(order). The commit expired the object, and validation reads its attributes.The fixes:
- expire_on_commit=False on the async sessionmaker: values stay as loaded.
- Refresh explicitly:
await session.refresh(order)after the commit, if you need database-generated values.
I use False and refresh only when I need server defaults.
- "Is there a way to make lazy loads work in async?"
Yes. SQLAlchemy provides
AsyncAttrsas a mixin for the declarative base. With it, a model getsawaitable_attrs, and you writelines = await order.awaitable_attrs.lines. That runs the lazy load as an awaited query, so it works in async code.This keeps the cost visible: an
awaitin the source marks the exact place where a query runs. It is the honest version of lazy loading for async.I use it for rare cases only, for example a background job that touches one relationship on one object, where an extra statement is acceptable.
For lists it is the wrong tool. Looping over 50 orders and awaiting
awaitable_attrs.lineson each is still N+1: 51 statements, just spelled withawait. So lists useselectinloadin the query (Q56).Think of it this way: awaitable_attrs makes a hidden query visible, while eager loading removes the query. The second is better whenever you know in advance what you need.
- "Why not just go back to sync?"
For many apps that is the right decision. The cost of async SQLAlchemy is not syntax, it is discipline about what gets loaded and when. If the team will not keep that discipline, sync sessions in plain
defendpoints are the lower-risk choice (Q58).The performance argument for async is capacity, not speed. A
defendpoint runs in a threadpool of 40 threads, and with a 20 ms query that is about 2,000 requests per second per worker. If the service needs fewer than that, async buys nothing measurable and costs you the traps: MissingGreenlet, expire-on-commit, pool queues.Sync also gives you things for free: lazy loading when you want it, simple tests, and every library that has no async version.
I would stay on async when the endpoint is async anyway (it calls an
httpx.AsyncClient, Redis, a stream) and the team has the habits listed in the main answer. Otherwise: sync first, measure, and move only the endpoints that need the concurrency. The two styles can live in the same app as long as each request path uses one.- "Does the same happen with Pydantic
from_attributes?" Yes, and the failure is the same one with a different location. Validating an ORM object into a response model with
from_attributes=Trueworks by reading attributes, one by one, from the object. If a relationship was not loaded, that read triggers the lazy load inside Pydantic's code.In async code, that lazy load raises
MissingGreenlet, and the traceback points into Pydantic's validation, not at your query. That is confusing, because the real mistake is in the repository, which did not load the relationship. In sync code the same read would run a silent extra query.The same applies to expired attributes after a commit.
The fix is to make the loading complete before validation:
- Query side: eager-load every relationship that the response model lists.
- Model side: keep the response model small, so it needs few relationships.
- Safety net:
lazy="raise"makes the error name the relationship.
A useful habit: whenever a field is added to a response model, check which query feeds it.
Q60. "How do you size the connection pool when you run N workers?"
Reveal answer
Strong answer Start from the database, not from the application. PostgreSQL allows max_connections (default 100) and every connection is a server process using several MB. Reserve some for migrations, psql and monitoring (I keep 10). The rest is the budget for all application processes together.
Then divide: per_process = budget ÷ (pods × workers). SQLAlchemy's QueuePool allows pool_size + max_overflow connections per process, so I set pool_size to the per-process share and max_overflow to 0 or a small number. Set pool_timeout to a few seconds so overload becomes a quick error instead of a long hang (Q61), and pool_pre_ping=True to survive connections dropped by the database or a proxy.
Also check demand: a sync worker can run at most 40 def requests at once, so a pool far larger than 40 is wasted; and the pool should be at least as big as the number of requests that really hold a connection at the same time.
If the division gives 1 or 0, the architecture has outgrown direct connections: put PgBouncer (transaction pooling) in front, or reduce processes.
Picture it The division done for five fleet sizes against the PostgreSQL default.
The setup: Budget 100, with 10 reserved; two workers per pod; max_overflow=0.
# Choose pool settings from a connection budget, not from defaults.
def plan(budget, pods, workers, spare_for_ops=10):
usable = budget - spare_for_ops
per_process = usable // (pods * workers)
pool_size = max(1, per_process)
return usable, per_process, pool_size
print("max_connections=100 (PostgreSQL default); 10 kept for migrations, psql, monitoring")
print(f"{'pods':>4} {'workers':>7} | {'usable':>6} {'per process':>11} {'pool_size':>9} max_overflow=0")
for pods, workers in [(2, 2), (6, 2), (10, 2), (20, 2), (45, 2)]:
usable, per, ps = plan(100, pods, workers)
flag = "" if per >= 1 else " <- does not fit: need PgBouncer or fewer processes"
print(f"{pods:>4} {workers:>7} | {usable:>6} {per:>11} {ps:>9}{flag}")Make the invisible visible: Run it.
max_connections=100 (PostgreSQL default); 10 kept for migrations, psql, monitoring
pods workers | usable per process pool_size max_overflow=0
2 2 | 90 22 22
6 2 | 90 7 7
10 2 | 90 4 4
20 2 | 90 2 2
45 2 | 90 1 1What you see: Two pods of two workers can each hold 22 connections. At 20 pods the share is 2. At 45 pods it is 1: any further scale-out needs a pooler.
Why: The same service configured with the same code needs different pool sizes at different scales, so the pool size should be a setting (db_pool_size), not a constant in code.
Naive
Default pool, copied everywhere.
engine = create_engine(url)
# 5 + 10 overflow per process,
# whatever the fleet sizeBudgeted
Pool from settings.
engine = create_engine(
url, pool_size=cfg.db_pool_size,
max_overflow=0, pool_timeout=3,
pool_pre_ping=True)The shift: The pool is a share of a fixed database budget, not a framework default.
Land it I divide the database's connection budget by pods times workers, set pool size from settings with a short timeout and pre-ping, and add PgBouncer when the share reaches one.
- "What does PgBouncer change?"
PgBouncer is a connection pooler that sits between your applications and PostgreSQL. In transaction pooling mode, which is the useful one, a server connection is assigned to a client only for the length of one transaction and then goes back to a shared pool.
That changes the arithmetic. Your pods can open 500 client connections to PgBouncer, which are cheap, while PostgreSQL sees only 30 real connections, each an expensive server process. With 10 pods x 4 workers x pool 10 = 400 client connections, the database still holds 30.
The catches all come from the fact that two transactions in a row may use different server connections:
- Session state is lost:
SETcommands, advisory locks and temporary tables do not carry over. - Prepared statements: may break in some modes or driver settings, so check the driver and PgBouncer documentation for your versions.
- Idle transactions: hold a server connection the whole time, so keep transactions short.
I add it when the per-process share would be one or zero, and I test the driver settings first.
- Session state is lost:
- "Why
pool_pre_ping?" It checks that a pooled connection is still alive before the application uses it. With
pool_pre_ping=True, when SQLAlchemy hands out a connection it first sends a tiny test statement. If the connection is dead, it discards it and opens a fresh one, and your request never sees the failure.Without it, connections can die silently while idle in the pool. Typical causes are a database failover or restart, a firewall or load balancer that drops idle connections after, say, five minutes, or a PgBouncer restart. The first request that picks up a dead connection fails with "connection closed" or "server closed the connection unexpectedly". With 10 pooled connections, that can mean ten failed requests after a quiet night.
The cost is one very small round trip per checkout, usually a fraction of a millisecond on a good network.
The alternative is
pool_recycle, which replaces connections older than a set age. It works when you know the idle limit exactly, for example recycling at 240 seconds under a 300-second firewall limit. I use pre-ping because it needs no such knowledge.- "How is async different?"
An async engine has a pool and the same arithmetic. The difference is how many requests can be waiting for it at once. In sync code, at most 40
defrequests per worker hold a thread, so at most 40 can need a connection. In async code, thousands of coroutines can be in flight, and any of them may be waiting for the pool.So the pool is the real concurrency limit. If it has 10 connections and 2,000 requests arrive, 1,990 queue, each waiting up to
pool_timeout, which defaults to 30 seconds. Latency climbs and memory grows with the queue.- Size from the database: the same budget divided by pods x workers.
- Short pool_timeout: 3 to 5 seconds.
- Reject quickly: catch the timeout and answer 503 with
Retry-After(Q61).
That gives backpressure: when the database is the bottleneck, clients are told quickly instead of waiting in a long hidden queue. Not holding a connection during external calls matters even more in async.
- "Should
max_overflowbe zero?" When the budget is tight, I set it to zero so the arithmetic is exact.
max_overflowallows extra connections beyondpool_sizewhen all pooled ones are busy. They are opened on demand and closed when returned.Overflow is useful for short bursts, but it multiplies the worst case. Take a budget of 80 connections, 4 pods x 2 workers, so a per-process share of 10. With
pool_size=10andmax_overflow=10, the worst case is 8 x 20 = 160 connections, twice the budget. Under a spike, every process overflows at once, the database refuses connections, and the failure is worse than a polite wait.worst case with overflowruns offlineper process = pool_size + max_overflow = 10 + 10 = 20 all processes = 8 x 20 = 160 (budget was 80)With overflow 0 the ceiling is 8 x 10 = 80, so the maths is exact. If I need burst room, I lower
pool_sizeand give the difference to overflow, so that the sum still matches the share.
Q61 · Scenario. "Under load, requests wait 30 seconds for a connection and then fail with a QueuePool limit error. Diagnose."
Reveal answer
Strong answer The default pool_timeout is 30 seconds: a request that finds no free connection waits that long, then fails with QueuePool limit of size N overflow M reached, connection timed out. The message tells you the pool is exhausted, not why.
Common causes, in the order I check them. One: connections held too long: a slow query, a transaction left open while the endpoint calls a slow external service, or an idle-in-transaction session. Two: leaks: a session never closed (a manual Session() without close, an exception path skipping cleanup). Three: pool too small for the concurrency, for example 40 threads and a pool of 5. Four: too many workers exhausting the database so everything is slow. Five: N+1 patterns holding a connection for 51 round trips.
How I diagnose: engine.pool.status() (size, checked out, overflow) as a metric; PostgreSQL pg_stat_activity filtered by application name to see states (idle in transaction is the red flag) and the running queries; and a log line when checkout takes over one second.
Fixes: close and release promptly (do not hold a session across external calls), keep transactions short, set a small pool_timeout (3 to 5 s) so overload fails fast with a clean 503, and size the pool by Q60.
Picture it A pool of two with no overflow and a one-second timeout, three requests asking at once.
The setup: Two connections are held (slow requests); the third asks.
import tempfile, time, threading, os
from sqlalchemy import create_engine, text
from sqlalchemy.pool import QueuePool
path = os.path.join(tempfile.mkdtemp(), "t.db")
engine = create_engine(f"sqlite:///{path}", poolclass=QueuePool, pool_size=2, max_overflow=0, pool_timeout=1)
held = [engine.connect(), engine.connect()] # two requests holding a connection (slow work)
print("pool status:", engine.pool.status())
t = time.perf_counter()
try: engine.connect() # the third request has to wait
except Exception as e:
print(f"after {time.perf_counter()-t:.2f}s ->", type(e).__name__)
print(str(e).splitlines()[0][:160])
for c in held: c.close()
print("after release:", engine.pool.status())Make the invisible visible: Run it.
pool status: Pool size: 2 Connections in pool: 0 Current Overflow: 0 Current Checked out connections: 2
after 1.00s -> TimeoutError
QueuePool limit of size 2 overflow 0 reached, connection timed out, timeout 1.00 (Background on this error at: https://sqlalche.me/e/20/3o7r)
after release: Pool size: 2 Connections in pool: 2 Current Overflow: 0 Current Checked out connections: 0What you see: The status shows both connections checked out. The third request waited exactly 1.00 s, then TimeoutError with the QueuePool message. After the others released, both connections were back in the pool.
Why: Part B measured the same 1.00 s. The default would have waited 30 s while holding a worker thread, which is why a long timeout makes overload worse.
Naive
Hold the connection while waiting.
with Session(engine) as s:
order = s.get(Order, oid)
pay(order) # ❌ 2 s call, slot held
order.status = "paid"; s.commit()Correct
Release around slow I/O.
order = load_order(oid) # short session
result = pay(order) # no connection held
with Session(engine) as s, s.begin():
mark_paid(s, oid, result)The shift: A connection is a scarce slot; hold it only while talking to the database.
Land it I read the pool status and idle-in-transaction sessions to find who holds connections, shorten transactions, close sessions promptly, and set a short pool timeout so overload fails fast.
- "How do I spot idle-in-transaction connections?"
I look at what PostgreSQL itself reports, because it shows what every connection is doing, not what the application believes. The first query groups connections by state:
connection statesruns offlineSELECT state, count(*) FROM pg_stat_activity WHERE application_name = 'quickbite-api' GROUP BY state;A healthy pool shows mostly
idleand a fewactive. A pile ofidle in transactionis the red flag: some code started a transaction (often an autobegun session) and then went off to do something slow, such as calling a payment API, while holding a connection.Next I list the offenders, ordered by how long their transaction has been open, using
xact_startand thequerycolumn, which shows the last statement they ran. That points at the code path.As a safety net I set
idle_in_transaction_session_timeout(for example 30 seconds) for the application role, so the server kills such sessions instead of letting them starve the pool. It is a net, not a fix: the fix is in the code.- "Should I just increase the pool?"
Only if the arithmetic of Q60 allows it. A bigger pool does not create database capacity, it only lets more requests reach the database at the same time.
Think about what happens next. Suppose the database is already at its limit and you double each pool. The queue that was in the application, cheap and visible as a pool timeout, moves into the database, where every connection is a server process using memory and competing for CPU. Queries get slower for everyone, so connections are held longer, so more are needed. That is a feedback loop.
If the real cause is connections held too long (a slow query, a transaction open during an external call), a bigger pool delays the same failure by a few minutes.
- First: find who holds connections and for how long.
- Second: shorten transactions and fix N+1.
- Third: grow the pool only inside the budget, or add PgBouncer.
Raising the pool is a last step, never the first one.
- "Why does the error mention overflow?"
Because the message reports the pool's full configuration, so that you can see how the limit was reached.
QueuePoolallowspool_sizepermanent connections plus up tomax_overflowtemporary ones. A typical message reads like "QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30".That tells you three facts at once: the permanent size (5), the overflow allowance (10), and the time the request waited (30 seconds, the default
pool_timeout). So at most 15 connections can be checked out per process, and every one of them was busy for 30 seconds.It does not tell you why they were busy. That is the reason for the diagnosis steps in the main answer.
Two practical readings of the numbers. If the pool is tiny compared to the thread count (5 + 10 against 40 threads), the pool itself may be too small. If it is large and still full, something is holding connections too long, and a bigger number would hide the problem.
- "How do I make overload a clean response?"
I catch the pool timeout in an exception handler and return a 503 with a
Retry-Afterheader. The exception issqlalchemy.exc.TimeoutError, raised when no connection became free withinpool_timeout.The handler maps it to a Problem Details body (type
service-busyor similar) with status 503 and, say,Retry-After: 2. A client or gateway that understands 503 can back off and retry, and a load balancer may send the next request to a less busy pod.The second half of the fix is shortening the wait. With the default 30 seconds, a client sees a request hang for half a minute, often longer than its own timeout, so it gives up and retries, which adds load. With
pool_timeout=3, the failure arrives in 3 seconds.- Setting:
pool_timeout=3to5in the engine. - Handler: one function, registered once, returns 503 plus
Retry-After. - Metric: count these 503s and alert on the rate.
Overload then becomes fast, honest and visible.
- Setting:
Q62. "Transactions: session.begin(), commit, rollback and savepoints."
Reveal answer
Strong answer A transaction groups statements so they all take effect or none do. In SQLAlchemy 2.0 a session starts a transaction automatically on first use and you end it. The clearest form is with session.begin(): which commits when the block ends normally and rolls back if an exception escapes.
session.commit() and session.rollback() do the same by hand. flush() writes pending changes inside the transaction without ending it. After a failed flush the transaction is "inactive": you must roll back before continuing.
A savepoint is a nested checkpoint: with session.begin_nested(): issues SAVEPOINT. If an error occurs inside, only the work since that savepoint is rolled back, and the outer transaction continues. I use it for an operation that may legitimately fail (inserting a unique row that might exist) without losing the surrounding work.
Rules: the service owns the boundary, so one business operation is one transaction; keep transactions short; do not call slow external services inside them; and choose the isolation level deliberately (PostgreSQL's default READ COMMITTED is fine for most; use row locks or atomic updates for contended rows, Q63).
Picture it Three blocks: a successful commit, an exception that rolls back, and a savepoint that absorbs a duplicate.
The setup: A coupons table with a primary key. The table starts empty.
from sqlalchemy import create_engine, text, String
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase): pass
class Coupon(Base):
__tablename__ = "coupons"
code: Mapped[str] = mapped_column(String(20), primary_key=True)
engine = create_engine("sqlite://"); Base.metadata.create_all(engine)
def n():
with engine.connect() as c: return c.execute(text("select count(*) from coupons")).scalar()
with Session(engine) as s: # 1. begin() commits on success
with s.begin():
s.add(Coupon(code="EID10"))
print("after begin() block:", n(), "row(s)")
with Session(engine) as s: # 2. exception inside begin() -> rollback
try:
with s.begin():
s.add(Coupon(code="DIWALI")); raise ValueError("boom")
except ValueError: pass
print("after exception :", n(), "row(s) (DIWALI rolled back)")
with Session(engine) as s: # 3. savepoint: only the inner part rolls back
with s.begin():
s.add(Coupon(code="NEWYEAR"))
try:
with s.begin_nested(): # SAVEPOINT
s.add(Coupon(code="EID10")) # duplicate primary key
except IntegrityError:
print("savepoint rolled back the duplicate; outer transaction continues")
s.add(Coupon(code="HOLI"))
print("after savepoint demo:", n(), "row(s):", sorted(r[0] for r in Session(engine).execute(text("select code from coupons"))))Make the invisible visible: Run it.
after begin() block: 1 row(s)
after exception : 1 row(s) (DIWALI rolled back)
savepoint rolled back the duplicate; outer transaction continues
after savepoint demo: 3 row(s): ['EID10', 'HOLI', 'NEWYEAR']What you see: The first block left 1 row. The block that raised left it at 1, so DIWALI was rolled back. In the third, the savepoint rolled back the duplicate EID10 insert, the outer transaction continued, and the final table had 3 rows.
Why: Each construct has a visible scope. The savepoint is what lets you try something risky without throwing away the work around it.
Spring
@Transactional on a method.
// illustrative
@Transactional
void place(...) {
repo.save(order); // rollback on error
}SQLAlchemy
A with-block you can see.
def place(self, ...):
with self.session.begin():
self.repo.add(order) # rollback on errorThe shift: Spring declares the transaction around a method; SQLAlchemy puts the boundary where you write it.
Land it I make each business operation one with session.begin(): in the service, use savepoints for steps that may fail on their own, and keep transactions short.
- "Does Spring's
@Transactionalroll back on checked exceptions?" By default only for unchecked exceptions. Spring's
@Transactionalrolls back onRuntimeExceptionandError, and commits on checked exceptions unless you list them withrollbackFor. That is a well-known trap: a method throws a checkedIOExceptionand the half-finished work is committed.Python has no checked exceptions, so the rule is simpler. With
with session.begin():, any exception that leaves the block rolls the transaction back. If it propagates, it rolls back. There is no list to configure and nothing to forget.The one thing to watch is catching an exception inside the block. If you write a
try/exceptaround a statement that failed and carry on, the exception never escapes, and the block commits whatever is left. After a failed flush the session is inactive and the commit itself fails, so it is not silent. For a failure you really want to recover from, use a savepoint withbegin_nested()around only that step.My summary for a Spring developer: same idea, fewer exceptions to the rule.
- "What isolation level should I use?"
I start with
READ COMMITTED, PostgreSQL's default, and add targeted tools for the rows that need more. Each statement sees the data committed before it started. That is enough for most CRUD, and it allows the most concurrency.It does not protect an invariant that spans a read and a later write, such as "stock never goes below zero" (Q63). For that I do not raise the isolation level first. I make the write itself safe.
- Atomic UPDATE: the check and the write in one statement, with
WHERE stock >= :q. - SELECT ... FOR UPDATE: lock the row when logic needs several reads before the write.
- SERIALIZABLE: for the few operations whose rule spans many rows and cannot be expressed otherwise. PostgreSQL may abort a transaction with a serialization failure, so the code must retry the whole transaction.
I use
SERIALIZABLEsparingly, because retries cost work and complicate the service. REPEATABLE READ sits between them and gives a stable snapshot per transaction. My rule: pick the lowest level and the narrowest lock that protects the invariant, and test it.- Atomic UPDATE: the check and the write in one statement, with
- "What happens if the connection drops mid-transaction?"
The database rolls back the open transaction, because a transaction that loses its connection is never committed. The application sees an
OperationalError, and the session must be rolled back and discarded.The hard case is a drop at the moment of commit. The client sends COMMIT, the server may or may not have processed it, and the connection dies before the reply. The application cannot know whether the order exists. Retrying blindly could create it twice.
So the service should not retry a write whose result is unknown unless the write is safe to repeat. The way to make it safe is an idempotency key (Q72): on retry the service looks up the key, finds either the stored order or nothing, and acts accordingly. The client does the same one level up, with the same key.
- Before the commit: the work is lost cleanly, and a retry is safe.
- At the commit: result unknown; retry only with an idempotency key.
- After the commit: the order exists; the client just did not hear.
- "Can I mix commit inside nested services?"
I avoid it. Only the outermost operation should commit. Inner functions receive the session and add their statements to the current transaction, but never commit or roll back on their own.
The reason is atomicity. Suppose
create_ordercallsreserve_stock, thenwrite_lines, thenwrite_outbox. Ifreserve_stockcommits at its own end, the stock is permanently reduced. Ifwrite_linesthen fails, the order rolls back, but the stock stays reduced, and the system is inconsistent. The guarantee that a business operation either happens fully or not at all is gone.When an inner step really can fail on its own and the outer work should continue, I use a savepoint with
session.begin_nested(), which rolls back only that step.A simple review rule works well in practice:
commit()appears only in service methods that own the boundary, and any other call to it in a pull request gets a comment.
Q63 · Scenario. "Two concurrent requests sell the last item twice. Fix it."
Reveal answer
Strong answer The service does check then update in Python: read stock, see 1, decide "enough", write stock - 1. Two requests interleave: both read 1 before either writes, both decide yes, both write. Two biryanis sold, one in stock. The gap between the read and the write is the bug; no amount of if in Python closes it, because the other request's read happens inside the gap.
Fixes, from simplest. One: an atomic conditional UPDATE: UPDATE menu_items SET stock = stock - :q WHERE id = :id AND stock >= :q, then check rowcount: 1 means success, 0 means out of stock (409). The database does the check and the write as one indivisible step.
Two: pessimistic lock: SELECT ... FOR UPDATE (SQLAlchemy with_for_update()) locks the row for the transaction, so the second request waits and then sees the new stock. Three: optimistic locking with a version column (Q74), and retry on conflict. Four: a database constraint (CHECK (stock >= 0)) as a last-resort net.
I use the atomic UPDATE first: shortest transaction, no locks held, simplest to test.
Part B ran this and I ran it again here. FOR UPDATE was not run (SQLite has no row locks); it is documented PostgreSQL behaviour.
Picture it One biryani left, two orders interleaved by hand (SQLite serialises writers, so a real race cannot be shown), then the atomic version.
The setup: menu_items(id=1, stock=1). The naive path reads in both sessions before either writes.
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
def reset():
with engine.begin() as c:
c.execute(text("drop table if exists menu_items")); c.execute(text("create table menu_items (id integer primary key, stock integer)"))
c.execute(text("insert into menu_items values (1, 1)")) # ONE biryani left
def stock():
with engine.connect() as c: return c.execute(text("select stock from menu_items")).scalar()
# NAIVE: read in Python, decide, write. Two requests interleave: both read before either writes.
reset()
a, b = Session(engine), Session(engine)
sa = a.execute(text("select stock from menu_items where id=1")).scalar()
sb = b.execute(text("select stock from menu_items where id=1")).scalar() # both see 1
accepted = 0
for s, seen in ((a, sa), (b, sb)):
if seen >= 1:
s.execute(text("update menu_items set stock = :n where id = 1"), {"n": seen - 1}); s.commit(); accepted += 1
print(f"naive check-then-update : accepted {accepted} orders, stock = {stock()} <- oversold by one (stock is 0, two sold)")
# SAFE: one atomic conditional UPDATE; the database decides, rowcount tells us.
reset(); accepted = 0
for _ in range(2):
with Session(engine) as s, s.begin():
r = s.execute(text("update menu_items set stock = stock - 1 where id = 1 and stock >= 1"))
if r.rowcount == 1: accepted += 1
print(f"atomic UPDATE .. >= qty : accepted {accepted} order, stock = {stock()}")Make the invisible visible: Run it.
naive check-then-update : accepted 2 orders, stock = 0 <- oversold by one (stock is 0, two sold)
atomic UPDATE .. >= qty : accepted 1 order, stock = 0What you see: Naive: both orders accepted and stock ended at 0 after two sales (it should have refused one). Atomic UPDATE: exactly one order accepted, stock 0, the other got rowcount == 0.
Why: The condition stock >= :q is evaluated by the database at write time, inside the same statement that changes the value. There is no gap for a second request to slip into.
Naive
Read, decide, write.
item = s.get(MenuItem, id)
if item.stock >= q: # ❌ gap
item.stock -= qCorrect
One conditional UPDATE.
r = s.execute(update(MenuItem)
.where(MenuItem.id == id,
MenuItem.stock >= q)
.values(stock=MenuItem.stock - q))
if r.rowcount == 0: raise OutOfStock(id)The shift: Move the check into the write, so checking and changing cannot be separated.
Land it I never check stock in Python and then write it; I use a conditional atomic UPDATE and check the row count, with FOR UPDATE or a version column for more complex invariants.
- "Why does the race not show in SQLite?"
Because SQLite has one writer at a time and locks the whole database file during a write. The harmful interleaving needs two transactions to read the same stock value and then both write, and SQLite's locking makes that sequence very hard to produce.
That is a trap for tests. A test that fires ten concurrent orders at SQLite may pass with the broken check-then-update code, because the writes were effectively serialised. The same code on PostgreSQL, where many transactions run at once under READ COMMITTED, oversells.
So a green test on SQLite proves little about this bug. I do two things:
- Simulate the interleaving by hand: two sessions, session A reads stock, session B reads stock, A writes, B writes. With the broken code the final stock is wrong and two orders succeeded.
- Test the atomic version: assert that exactly one of two competing orders for the last item succeeds, and the other gets 409.
For the final proof I run the same test against PostgreSQL in CI, since the engine decides the behaviour.
- "When do I prefer
FOR UPDATE?" I prefer
FOR UPDATEwhen the decision needs more than one read, or business logic, between the lock and the write. The atomic UPDATE handles "subtract if enough" in one statement. It cannot express "read the order, check its status is placed, check the refund window, compute the amount, then update".With
with_for_update()the first request locks the row and others wait on that row until the transaction ends. The waiter then sees the committed new state, so its checks run against the truth.The cost is that requests on that row are serialised, so the locked section must be tiny.
- Lock late: do slow work, such as external calls, before taking the lock or after releasing it.
- Lock in a fixed order: when several rows are locked, always lock them in the same order, for example by id.
- Set a lock timeout: so a stuck holder fails requests quickly instead of queueing them.
Two transactions locking rows A then B and B then A is the classic deadlock. A fixed order removes it.
- "What about a multi-item order?"
I decrement the items one by one in a fixed order, inside one transaction, each with the conditional UPDATE. If any statement matches zero rows, the service raises
OutOfStock, the block rolls back, and every earlier decrement in the same order is undone.Take an order for items 7, 3 and 9. I sort the lines by item id first: 3, 7, 9. Then for each item I run
UPDATE menu_items SET stock = stock - :q WHERE id = :id AND stock >= :qand check the row count.- Sort by id: every order touches rows in the same sequence.
- Update each: a row count of 0 means not enough stock.
- Raise on 0: the whole transaction rolls back, so partial reservations vanish.
The fixed order is the important detail. If order X locks item 3 then 9 while order Y locks 9 then 3, each holds one lock and waits for the other, and PostgreSQL has to abort one with a deadlock error. Sorted ids make both ask for 3 first, so one simply waits for the other.
- "What does the client see on a conflict?"
A 409 Conflict with a Problem Details body. The error type is something like
out-of-stock, the title says what happened, and the detail or an extra member names the item and the quantity still available.The status choice matters. A 500 means "the server broke", which triggers alerts and tells clients to retry the same request. Running out of stock is not a fault. It is a normal business outcome: the request was well formed, but the current state of the data does not allow it. 409 says exactly that, and 400-class codes are not retried blindly.
A good body also helps the client act:
- Which item: the menu item id, so the app highlights it.
- How many are left: so it can offer a smaller quantity.
- No retry hint: retrying with the same quantity will fail again.
The client can then reduce the quantity, choose another dish, or tell the user the item is sold out, all without guessing from an error string.
Q64. "SQLModel, SQLAlchemy or raw psycopg 3 — when do you use each?"
Reveal answer
Strong answer They sit at different levels. SQLAlchemy (ORM plus Core) is the mature, full toolkit: typed models, unit of work, relationships, a SQL expression language, migrations through Alembic, and a huge ecosystem. SQLModel is a thin layer that lets one class be both a Pydantic model and a SQLAlchemy table; it reduces boilerplate in small apps, but it is younger, follows SQLAlchemy and Pydantic versions with lag, and blurs the three-model boundary that keeps secrets out of responses.
Raw psycopg 3 (async or sync) means you write SQL and map rows yourself: the most control and speed for hot paths, the least help with relationships and changes.
My default is SQLAlchemy 2.x with separate Pydantic schemas. I use Core or raw SQL inside the repository for reports, bulk inserts and special queries (window functions, ON CONFLICT). I consider SQLModel for prototypes and small services where one class per table is enough and the team accepts the coupling. I choose raw psycopg when the service is mostly a few hand-tuned queries.
SQLModel is not installed on the course machine, so it is described, not run.
Picture it One query written three ways (ORM, Core, driver), compiled or run on in-memory SQLite.
The setup: orders rows with a status; fetch the ready ones. The raw version uses the standard-library sqlite3 driver as a stand-in for psycopg.
from sqlalchemy import create_engine, select, text, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
from sqlalchemy.pool import StaticPool
import sqlite3
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
status: Mapped[str] = mapped_column(String(20))
engine = create_engine("sqlite://", poolclass=StaticPool); Base.metadata.create_all(engine)
with Session(engine) as s: s.add_all([Order(id=1, status="placed"), Order(id=2, status="ready")]); s.commit()
with Session(engine) as s: # 1. ORM: typed objects
o = s.scalars(select(Order).where(Order.status == "ready")).one()
print("ORM :", type(o).__name__, o.id, o.status)
stmt = select(Order.id).where(Order.status == "ready") # 2. Core: just the statement
print("Core SQL :", str(stmt).replace("\n", " "))
print("Core rows:", s.execute(stmt).all())
raw = sqlite3.connect(":memory:") # 3. raw driver (stands in for psycopg 3): tuples
raw.execute("create table orders (id integer, status text)"); raw.execute("insert into orders values (2, 'ready')")
print("raw :", raw.execute("select id from orders where status = ?", ("ready",)).fetchall(), "(you write SQL, map rows, handle types)")
print("SQLModel : not installed here; it is Pydantic + SQLAlchemy in one class, described in the text only")Make the invisible visible: Run it.
ORM : Order 2 ready
Core SQL : SELECT orders.id FROM orders WHERE orders.status = :status_1
Core rows: [(2,)]
raw : [(2,)] (you write SQL, map rows, handle types)
SQLModel : not installed here; it is Pydantic + SQLAlchemy in one class, described in the text onlyWhat you see: The ORM returned a typed object, Core returned row tuples and showed the SQL it generated, the raw driver returned tuples from SQL I wrote and mapped myself.
Why: More abstraction means less typing and more behaviour hidden; less abstraction means more control and more repeated mapping code.
SQLModel
One class, two jobs.
class Order(SQLModel, table=True):
id: int | None = Field(primary_key=True)
status: str
# also used as the API modelSQLAlchemy + Pydantic
Two classes.
class Order(Base): ... # table
class OrderOut(BaseModel): ... # contractThe shift: One class is shorter; two classes keep the database and the API contract separate.
Land it I default to SQLAlchemy 2.x with separate Pydantic schemas, drop to Core or raw SQL for special queries, and consider SQLModel only for small services that accept the coupling.
- "Why not use the ORM for everything?"
Because ORMs are built for objects, and some work is better described as sets of rows. An ORM is excellent at "load this order, change a field, save it": it tracks changes, orders statements and handles relationships.
It is poor in three places. Bulk updates: marking 100,000 old rows as archived through the ORM loads 100,000 objects, while one
UPDATE ... WHEREdoes it in a single statement. Reporting: grouped sums, window functions and joins across many tables produce rows, not entities, and forcing them into objects adds nothing. Database-specific features:ON CONFLICTupserts,FOR UPDATE SKIP LOCKED, full-text search and JSON operators are easier to write directly.In SQLAlchemy this is not a choice between two tools. The same session runs ORM operations and Core statements (
select(),update(),insert(),text()), in the same transaction.So my repositories mix: ORM for entities, Core for sets and reports. The goal is not purity but the shortest code that is clear and correct.
- "Is raw SQL faster?"
Often a little, for simple queries, but not by enough to decide the design. Raw SQL skips the work of building objects, tracking them and generating the statement, which costs microseconds per row.
The dominant cost of a typical request is elsewhere. A query that takes 20 ms is mostly the network round trip and the database executing the plan, and both are identical whether the SQL was typed by hand or generated by SQLAlchemy. Shaving 0.2 ms of Python overhead off a 20 ms query is a 1% change.
Where raw speed does matter is bulk work: inserting 50,000 rows with one multi-row statement or
COPYis much faster than adding 50,000 ORM objects. That is a place to drop to Core, not necessarily to raw strings.My criterion for raw SQL is clarity. A complex report with window functions is easier to read and review as SQL than as nested expression-language calls. I decide with a measurement on the real query, never on a belief that SQL is faster.
- "What about Django ORM or Tortoise?"
I would choose them only when the rest of the stack already uses them. Each is good at its own job, but neither fits a FastAPI service built on SQLAlchemy by default.
- Django ORM: excellent inside Django, where it comes with migrations, the admin and forms. It is designed around the Django project and settings, so using it alone beside FastAPI is awkward and you lose much of its value.
- Tortoise ORM: async-first and inspired by Django's ORM, so it avoids the greenlet issues. Its ecosystem is smaller, with fewer tools, fewer examples and less proven behaviour at scale.
- SQLAlchemy: the largest ecosystem, Alembic for migrations, and Core for the cases where the ORM is not enough.
I have not run Django or Tortoise on the course machine, so this comparison is from their documentation and general experience; check current versions before deciding.
The deciding question for a senior engineer is the team's cost: who knows it, who can debug it at 3 a.m., and how hard would it be to leave. SQLAlchemy wins on those for most FastAPI teams.
- "How do I keep raw SQL safe?"
Three rules, and the first one is not negotiable: always pass values as bound parameters, never build SQL from strings, and use an allow-list for anything that is not a value.
With psycopg 3 the placeholder is
%sor%(name)sand the values go in a second argument. With SQLAlchemytext()it is:namewith a dict. In both, the driver sends the SQL and the values separately, so a quote orOR 1=1in the value stays plain data.- Values: bound parameters only, never f-strings,
%formatting or concatenation. - Identifiers: column names, table names and sort direction cannot be parameters, so map the user's choice through a dict of known names (Q65).
- Privileges: the application's database user has only the rights it needs, so a mistake cannot drop a table.
In psycopg 3, the
psycopg.sqlmodule builds identifiers safely withsql.Identifier. Reviewers should grep for f-strings nearexecute.- Values: bound parameters only, never f-strings,
Q65. "How do you avoid SQL injection when you need text()?"
Reveal answer
Strong answer SQL injection happens when user input becomes part of the SQL text, so the database parses it as code. The defence is to keep code and data apart: write the SQL with named placeholders (:name) and pass values separately (conn.execute(text("... WHERE customer = :name"), {"name": value})). The driver sends the values as data, never as SQL, so quotes and OR 1=1 stay harmless text.
What you must never do: build SQL with f-strings, % formatting, + concatenation, or .format(), even for "safe-looking" values like ids (a string "1; DROP TABLE" is still a string).
Placeholders cannot stand for identifiers (column names, table names, ORDER BY columns, sort direction). For those use an allow-list: map the user's choice through a dict of known columns ({"created": Order.created_at, "total": Order.total_cents}), and reject anything else. SQLAlchemy's select() with column objects is safe by construction, so prefer it over text() unless the SQL is truly special.
Also limit damage: the application's database user should have only the privileges it needs (no DROP, no superuser), and LIKE patterns should escape % and _ in user input.
Picture it One malicious value through an f-string, then through a bound parameter, then a sort column through an allow-list.
The setup: A three-row orders table; the attacker sends x' OR '1'='1 as the customer name.
from sqlalchemy import create_engine, text
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool)
with engine.begin() as c:
c.execute(text("create table orders (id integer, customer text, status text)"))
c.execute(text("insert into orders values (1,'asha','placed'),(2,'ravi','ready'),(3,'meera','ready')"))
evil = "x' OR '1'='1" # attacker-controlled input
with engine.connect() as c:
bad = f"select id, customer from orders where customer = '{evil}'" # ❌ TRAP: string formatting
print("f-string SQL :", bad)
print(" returns :", c.execute(text(bad)).all(), "<- every row")
good = text("select id, customer from orders where customer = :name") # ✅ bound parameter
print("bound param :", c.execute(good, {"name": evil}).all(), "<- the text is just a name that matches nobody")
cols = {"id", "customer", "status"}
sort = "customer; drop table orders"
print("ORDER BY col :", sort if sort in cols else "rejected (not in allow-list)", "<- identifiers cannot be bound, so allow-list them")Make the invisible visible: Run it.
f-string SQL : select id, customer from orders where customer = 'x' OR '1'='1'
returns : [(1, 'asha'), (2, 'ravi'), (3, 'meera')] <- every row
bound param : [] <- the text is just a name that matches nobody
ORDER BY col : rejected (not in allow-list) <- identifiers cannot be bound, so allow-list themWhat you see: The f-string version returned every row. The bound-parameter version returned none, because the whole string was treated as a customer name. The sort column customer; drop table orders was rejected by the allow-list.
Why: The quotes in the attack only changed the meaning of the SQL when they were part of the SQL text. As a bound value they are just characters.
Naive
Text built from input.
sql = f"SELECT * FROM orders WHERE c = '{name}'"
conn.execute(text(sql)) # ❌ injectableCorrect
Placeholder and allow-list.
q = text("SELECT * FROM orders WHERE c = :n")
conn.execute(q, {"n": name}) # ✅
col = SORTABLE[sort] # allow-listThe shift: Values travel as parameters and identifiers come from a fixed list; user text never becomes SQL.
Land it I use bound parameters for every value, an allow-list for every identifier, and the expression language instead of text() whenever I can.
- "Is the ORM automatically safe?"
Mostly, because the ORM and
select()generate parameterised statements. A filter such asOrder.customer_id == user_idbecomes SQL with a bound placeholder, and the value never joins the SQL text.The safety ends at a short list of escape hatches, where user input can become part of the SQL text:
- text() with formatting: an f-string inside
text(), or inwhere(text(...)). - order_by(text(user_input)): a very common one, since sort columns cannot be bound.
- literal_column(user_input): treats the string as raw SQL.
- Raw execute strings:
connection.exec_driver_sql(f"...")and similar.
When I review a codebase for injection, I do not read every query. I search for exactly these calls and check where each argument comes from. In a 40-endpoint service that is usually fewer than ten places.
The conclusion is that the ORM removes the common mistakes, but it is not a guarantee: a single
order_by(text(request_param))brings the whole problem back, and it looks harmless in a code review.- text() with formatting: an f-string inside
- "How do I allow a user-chosen sort order?"
I define a dictionary from allowed keys to column objects, type the query parameter as a
Literal, and fall back to a default. The user never supplies SQL, only a choice among names I wrote.sort allow-listSORTS = { "created": Order.created_at, "total": Order.total_cents, } def list_orders(sort: Literal["created", "total"] = "created"): column = SORTS[sort] return select(Order).order_by(column.desc())FastAPI sees the
Literalin the signature, so a request with?sort=name;DROPis rejected with a 422 before any SQL is built. The dictionary is a second wall, in case the function is called from elsewhere.Direction is also an identifier. I take it as a separate
Literal["asc", "desc"]and choosecolumn.asc()orcolumn.desc()in code. For keyset pagination, add the id column as a tie-breaker (Q39).- "What about
LIKEsearch?" Bind the pattern as a value, and escape the wildcard characters in what the user typed. Two separate problems are involved, and only the first one is injection.
First, the injection side: write
WHERE name LIKE :pand passf"%{q}%"as the value ofp. The percent signs are added in Python and sent as data, so a quote inqis harmless.Second, the wildcard side: in LIKE, the characters
%and_are special. If a user types%or a string of them, the pattern becomes a wildcard that matches almost everything and forces a full scan, which is a cheap way to load the database. So I escape them in the user's text and add anESCAPEclause (SQLAlchemy's.contains(q, autoescape=True)does this).Also note that a leading wildcard,
'%text%', cannot use an ordinary B-tree index. For real search I would use a trigram index or full-text search, and limit the pattern length and the page size.- "Does a Pydantic model protect me?"
No, validation is a useful extra layer, but it is not the defence. A Pydantic model checks types, lengths and patterns, and that shrinks what an attacker can send. A field limited to 20 characters cannot carry a long payload.
But a valid string can still contain a quote. A customer called
O'Brienis legitimate, and so is the namex' OR '1'='1as far as a length check is concerned, since both are short strings. If either is pasted into SQL text, the second one changes the query. A pattern that forbids quotes would break real names and would still miss other tricks.The defence has to work whatever the string contains, and that is parameter binding: the driver never treats a value as SQL.
- Binding: the guarantee; works for any value.
- Allow-lists: for identifiers that cannot be bound.
- Validation: an extra layer that limits size and shape and gives users clear 422 errors.
I never accept "we validate input" as an answer to an injection question.
Q66 · Design. "Design the persistence layer for orders with lines and a status history."
Reveal answer
Strong answer Tables: orders (id, customer_id, restaurant_id, current status, total_cents, version, created_at), order_lines (order_id, menu_item_id, qty, captured price_cents), and an append-only order_status_history (order_id, from_status, to_status, actor, at). The current status lives on orders for fast reads; the history is the audit trail and is never updated or deleted.
Rules. Money: integer cents, captured per line at order time, so later price changes never alter old orders. State machine: allowed transitions live in one place (placed → preparing → ready → delivered, plus cancelled) and are enforced in the service; an illegal move raises a 409. One transaction writes the status change and the history row together, so they cannot disagree. Concurrency: a version column (optimistic locking, Q74) or UPDATE ... WHERE status = :expected so two actors cannot both move the same order.
Indexes: orders(customer_id, created_at DESC, id DESC) for the customer's list (keyset pagination, Q39); order_lines(order_id); order_status_history(order_id); a partial index for the restaurant's open orders (WHERE status IN ('placed','preparing')). Constraints: CHECK (qty > 0), foreign keys, CHECK (total_cents >= 0).
Events: write an outbox row in the same transaction (Q75). Queries: selectinload(Order.lines) for detail, summaries for lists.
Picture it The models and a transition function, run against SQLite: two legal moves, one illegal move rejected, and the history as stored.
The setup: Order holds the current status; OrderStatusHistory has a row per transition with actor and time.
from datetime import datetime, timezone
from sqlalchemy import create_engine, ForeignKey, String, select, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, Session
from sqlalchemy.pool import StaticPool
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
status: Mapped[str] = mapped_column(String(20)) # current status, for fast reads
version: Mapped[int] = mapped_column(default=1)
history: Mapped[list["OrderStatusHistory"]] = relationship(order_by="OrderStatusHistory.id", back_populates="order")
class OrderStatusHistory(Base):
__tablename__ = "order_status_history" # append-only: rows are never updated
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"), index=True)
from_status: Mapped[str | None]
to_status: Mapped[str]
actor: Mapped[str]
at: Mapped[datetime]
order: Mapped["Order"] = relationship(back_populates="history")
ALLOWED = {"placed": {"preparing", "cancelled"}, "preparing": {"ready", "cancelled"}, "ready": {"delivered"}}
def transition(s: Session, order: Order, to: str, actor: str):
if to not in ALLOWED.get(order.status, set()): raise ValueError(f"illegal transition {order.status} -> {to}")
s.add(OrderStatusHistory(order=order, from_status=order.status, to_status=to, actor=actor, at=datetime(2026, 11, 24, 10, 0, tzinfo=timezone.utc)))
order.status = to
engine = create_engine("sqlite://", poolclass=StaticPool); Base.metadata.create_all(engine)
with Session(engine) as s, s.begin():
o = Order(id=1, status="placed"); s.add(o); s.flush()
s.add(OrderStatusHistory(order=o, from_status=None, to_status="placed", actor="customer:7", at=datetime(2026, 11, 24, 9, 55, tzinfo=timezone.utc)))
transition(s, o, "preparing", "restaurant:3"); transition(s, o, "ready", "restaurant:3")
try: transition(s, o, "placed", "admin")
except ValueError as e: print("rejected:", e)
with Session(engine) as s:
o = s.get(Order, 1)
print("current:", o.status)
for h in o.history: print(f" {h.from_status!s:10} -> {h.to_status:10} by {h.actor}")Make the invisible visible: Run it.
rejected: illegal transition ready -> placed
current: ready
None -> placed by customer:7
placed -> preparing by restaurant:3
preparing -> ready by restaurant:3What you see: The illegal move ready → placed was rejected with a clear message. The order's current status is ready, and the history lists the creation and both legal moves with who made them.
Why: Current state is for reading quickly; history is for explaining how we got there. Writing both in one transaction keeps them consistent.
Naive
Overwrite the status.
order.status = new # ❌ who? when? from what?
session.commit()Correct
Validate, record, then change.
check(order.status, new) # state machine
s.add(History(order=o, to_status=new, ...))
order.status = new # one transactionThe shift: Never overwrite the only copy of a fact you may need to explain later.
Land it I keep current status on the order for reads, write an append-only history row in the same transaction, capture prices on lines, and enforce transitions and concurrency in the service.
- "Should I use event sourcing instead?"
Usually not, for an orders service. Event sourcing means storing only the events (placed, preparing, delivered) and deriving the current state by replaying them. It gives a complete history, the ability to replay, and the chance to rebuild new read views from the past.
The price is real. Every read of "current status" needs a projection or a snapshot. Changing the shape of an event later (schema evolution) means handling old and new versions forever. Debugging requires tooling that most teams do not have, and engineers need a new mental model.
My design already gets most of the value more cheaply. The
ordersrow holds the current status for fast reads, and the append-onlyorder_status_historytable records who changed what and when. That answers "what happened to order 812" and supports audit.I would move toward event sourcing only if the business needs to rebuild past states or feed many independent read models from one stream. Then I would introduce it for that part, not for the whole system, and I would say so to the team up front.
- "How do I stop two staff moving the same order at once?"
I make the update conditional, so that only one of them can succeed, and the other learns it lost. Two staff members open the same order on tablets. One taps "preparing", the other taps "cancelled". Without protection, the later write silently overwrites the earlier one.
- Conditional update:
UPDATE orders SET status = :new WHERE id = :id AND status = :expected. Zero rows matched means the order was already changed. - Version column: SQLAlchemy's
version_id_coladdsAND version = :vto every update and raisesStaleDataErroron a mismatch (Q74). - Response: the loser gets 409, with a body that says the order changed and shows the current status.
I prefer the conditional update on status for this table, because the state machine needs it anyway: "move from placed to preparing" is only legal if the order is currently placed.
The history row is written in the same transaction, only when the update matched a row, so the audit trail records exactly the transitions that happened.
- Conditional update:
- "How big will the history table get?"
It stays small and boring. An order has a few status changes: placed, preparing, ready, delivered, perhaps cancelled. That is about four or five rows per order.
history sizeruns offline5 rows per order x 10,000,000 orders = 50,000,000 rows 50,000,000 x about 100 bytes = about 5 GB (rows only, before indexes)The row size of 100 bytes is my assumption (ids, two short statuses, actor, timestamp); real tables carry some overhead, so I would check with
pg_total_relation_size.That is a modest table for PostgreSQL, because it is append-only and every lookup goes through the index on
order_id. Inserts are cheap, and nothing is updated or deleted, so there is little bloat.If it grows large, I partition by month on the timestamp and detach old partitions to archive storage, because monthly partitions make dropping or archiving old data a fast metadata operation instead of a huge delete. I would not do this on day one. I would watch the table size and query plans first.
- "Where do timestamps come from?"
From the database or from one clock source in the service, never from clients. The column type is
TIMESTAMP WITH TIME ZONE, which PostgreSQL stores as an absolute instant (internally in UTC) and converts on output.The reason to avoid client clocks is trust and consistency. A phone with the wrong time, or in the wrong timezone, would write an order that appears to be from last Tuesday. Pods can also drift by a few seconds, so two events in a sequence can look reversed. Using
server_default=func.now()(Q55) means one clock, the database's.- Store: timestamptz, set by the database.
- Send: ISO 8601 with an offset, such as
2026-11-24T09:15:00Z. - Display: the client converts to the user's local time (Q112).
A column of type "timestamp without time zone" is the trap. It stores the wall-clock digits with no zone, so two readers in different zones disagree about when it happened, and daylight-saving changes create ambiguous values. I use the zoned type everywhere.
These questions test whether you can change a live schema safely, keep a cache from hurting you, and make retried writes harmless.
Q67. "Alembic: how does autogenerate work, and what does it miss?"
Reveal answer
Strong answer Alembic keeps migrations as numbered Python scripts, each with upgrade() and downgrade(). alembic revision --autogenerate compares two things: the live database (reflected through SQLAlchemy) and your models' MetaData. Differences become operations in a new script: add_column, drop_column, create_table, create_index, alter_column.
It is a draft generator, not an oracle. What it misses or gets wrong: a rename looks like a drop plus an add, which loses the data; a server default or type change is not detected unless you enable compare_server_default and compare_type; check constraints, some index options and enum changes are partial; and it knows nothing about data: backfilling a new NOT NULL column, splitting a column, or converting values needs hand-written SQL.
So the rule is: always read the generated script, fix renames with op.alter_column(..., new_column_name=...), add data steps, and think about locking before you merge it (Q68). Also name constraints with a naming convention so later migrations can drop them, and keep exactly one head.
Run each migration against a copy of production-like data in CI.
Picture it The comparison Alembic does, run directly between a table as deployed and the models as desired.
The setup: The table has note; the model renamed it remarks, changed a server default on status, and added a NOT NULL tip_cents.
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, text
from alembic.migration import MigrationContext
from alembic.autogenerate import compare_metadata
engine = create_engine("sqlite://")
with engine.begin() as c: # the database as deployed today
c.execute(text("create table orders (id integer not null primary key, status varchar(20), note text)"))
md = MetaData() # the models as we want them
Table("orders", md,
Column("id", Integer, primary_key=True),
Column("status", String(20), server_default="placed"), # a new server default
Column("remarks", String), # 'note' renamed to 'remarks'
Column("tip_cents", Integer, nullable=False)) # NOT NULL column with no default
with engine.connect() as conn:
diff = compare_metadata(MigrationContext.configure(conn), md)
print("default autogenerate found", len(diff), "difference(s):")
for d in diff:
if isinstance(d, list):
for x in d: print("MODIFY", x[0], x[2], x[3], "| from", x[5], "to", x[6])
else:
print(d[0], d[3].name if hasattr(d[3], "name") else d[3])Make the invisible visible: Run it.
default autogenerate found 3 difference(s):
add_column remarks
add_column tip_cents
remove_column noteWhat you see: Three differences: add remarks, add tip_cents and remove note. The rename is shown as an add plus a remove, so applying it as generated would drop the notes. The changed server default on status was not reported at all with the default settings.
Why: Part B saw the same rename behaviour. The dangerous parts are the ones that look correct in the diff: a data-losing drop and a NOT NULL column with no default would fail on a table that has rows.
Flyway
SQL files by hand.
-- illustrative
ALTER TABLE orders ADD COLUMN tip_cents INT;
UPDATE orders SET tip_cents = 0;Alembic
Python script, drafted for you.
def upgrade():
op.add_column("orders",
sa.Column("tip_cents", sa.Integer()))
op.execute("UPDATE orders SET tip_cents = 0")The shift: Flyway is hand-written SQL; Alembic can draft from your models, and you still review and add the data steps.
Land it I use autogenerate as a first draft, always read it, replace drop-plus-add with renames, add backfills by hand, and test the migration against realistic data.
- "How do I make autogenerate detect type and default changes?"
By enabling two options in
env.py:compare_type=Trueandcompare_server_default=True, passed tocontext.configure(...). Without them, Alembic compares only the presence of tables, columns and indexes, so changingString(20)toString(40)or a default from 0 to 1 produces an empty migration and the database quietly stays different from the models.With them on, autogenerate emits
op.alter_columnoperations for those differences. That is the safer setting, but it is not perfect. Some dialects report types in a different form from how they are declared, so you may get false positives such as analter_columnthat changes nothing real.I accept that, because the two kinds of mistake are not equal. A false positive costs me a minute to delete a line from the draft. A missed change means production and the models disagree, with the bug found weeks later.
I also keep a CI check,
alembic check, that fails when models and migrations differ, so a forgotten migration is caught at pull-request time.- "What is a naming convention for constraints?"
A naming convention is a rule, set once on the
MetaData, that gives every constraint and index a predictable name. You passnaming_conventionwith patterns for indexes (ix), unique constraints (uq), checks (ck), foreign keys (fk) and primary keys (pk).Why it matters: if you do not name a constraint, the database invents a name, such as
orders_customer_id_fkeyin PostgreSQL, and other databases invent different ones. A later migration that wants to drop the constraint withop.drop_constraint("name", "orders")must know that name. If different environments created it at different times or on different engines, the name can differ, and the migration fails in production but passes locally.- Set once: in the declarative base's
MetaData. - Autogenerate uses it: new constraints get stable names in migrations.
- Existing databases: older unnamed constraints may need a one-time rename.
It is five minutes of setup that saves a painful incident later.
- Set once: in the declarative base's
- "What happens with two developers creating migrations at the same time?"
The history forks into two heads. Alice creates revision B from A, and Bob, who also started from A, creates revision C. Both are valid, but Alembic cannot run "upgrade head" when there are two heads, because the order of B and C is undefined.
The fix is simple and mechanical.
alembic headsshows the two heads, andalembic merge -m "merge" B Ccreates a new revision that depends on both, giving one head again. If the two migrations touch different tables, the merge is empty. If they touch the same table, you must check that they do not conflict, for example both adding a column with the same name.- Detect in CI: a step that fails if
alembic headsshows more than one line. - Merge: whoever merges second creates the merge revision.
- Review: run the migrations on a fresh database to check that they work together.
The CI check matters because the fork is invisible in either branch alone. It exists only after both are merged, and without the check it surfaces at deploy time.
- Detect in CI: a step that fails if
- "Should downgrades be maintained?"
In practice most teams roll forward: if a migration is wrong, they write a new migration that fixes it. I still write simple downgrades for development, but I do not depend on them in production.
A downgrade is easy to write for an added nullable column, since it just drops it. It is dangerous or impossible for many others. Downgrading a migration that dropped a column cannot bring the data back. A downgrade of a type change may lose precision. And a downgrade that runs after the application has been writing data in the new shape can destroy that data.
The safer production story is the expand and contract pattern (Q68). The expand step is additive and backward compatible, so rolling back the application is enough: the old code still works against the new schema. Destructive steps come later, once no running code needs the old shape, and by then nobody wants to go back.
My rule: downgrades are a development convenience and a documentation of intent. The real rollback plan is a compatible schema plus a previous application image, with backups for the worst case.
Q68 · Scenario. "A migration locked the orders table for four minutes. What went wrong, and how do you migrate safely?"
Reveal answer
Strong answer A statement took a lock that blocked reads or writes for as long as it ran. Typical causes in PostgreSQL: ALTER TABLE ... ADD COLUMN ... DEFAULT <volatile> or SET NOT NULL that scans the whole table while holding ACCESS EXCLUSIVE; CREATE INDEX (without CONCURRENTLY) which blocks writes; changing a column type, which rewrites the table; adding a foreign key that validates every row. Even a quick ALTER can queue behind a long transaction and then block everything behind it.
The safe approach is expand and contract (pat-expand-contract-migration): in small steps, each deployed separately. Expand: add the new column as nullable (fast). Backfill in batches (a few thousand rows per transaction, with pauses). Switch the application to write both, then read the new column. Enforce: add the constraint in two stages, ADD CONSTRAINT ... NOT VALID (fast) then VALIDATE CONSTRAINT (scans without blocking writes). Contract: drop the old column in a later release.
Add a lock_timeout (for example 3 seconds) to each migration so it fails fast instead of queueing and blocking traffic, and a statement_timeout. Create indexes with CREATE INDEX CONCURRENTLY (outside a transaction block). Rehearse on a production-sized copy and measure.
Picture it The unsafe and safe versions of the same change, as SQL to read (they need a PostgreSQL table of real size, so this block is an illustration and was not run).
The setup: Add tip_cents INT NOT NULL DEFAULT 0 and an index on created_at to an orders table with 50 million rows.
-- illustrative: PostgreSQL
-- ❌ UNSAFE
ALTER TABLE orders ADD COLUMN tip_cents INT NOT NULL; -- fails on existing rows; with a default may rewrite
CREATE INDEX idx_orders_created ON orders (created_at); -- blocks writes while it builds
-- ✅ SAFE (several deploys)
SET lock_timeout = '3s'; -- fail fast instead of queueing
ALTER TABLE orders ADD COLUMN tip_cents INT; -- nullable: metadata-only, instant
-- app now writes tip_cents; backfill in batches:
UPDATE orders SET tip_cents = 0 WHERE id BETWEEN 1 AND 5000 AND tip_cents IS NULL; -- repeat per batch
ALTER TABLE orders ADD CONSTRAINT tip_nn CHECK (tip_cents IS NOT NULL) NOT VALID; -- instant
ALTER TABLE orders VALIDATE CONSTRAINT tip_nn; -- scans, but does not block writes
CREATE INDEX CONCURRENTLY idx_orders_created ON orders (created_at); -- outside a transactionWhat you see: Every unsafe step either scans or rewrites while holding a strong lock; every safe step is either instant or does its slow work without blocking writers.
Why: The principle is to split "change the structure" (instant) from "change the data" (slow, batched) from "enforce the rule" (validated gently).
Naive
One big migration.
ALTER TABLE orders
ADD COLUMN tip_cents INT NOT NULL DEFAULT 0;
CREATE INDEX i ON orders (created_at);Safe
Expand, backfill, enforce.
ALTER TABLE orders ADD COLUMN tip_cents INT;
-- batch backfill, then:
CREATE INDEX CONCURRENTLY i
ON orders (created_at);The shift: Never combine structure change, data change and enforcement in one lock-holding statement.
Land it I split risky changes into expand, batched backfill, gentle enforcement and contract across separate deploys, with lock and statement timeouts and concurrent index builds.
- "Is adding a column with a constant default still slow?"
Yes, since PostgreSQL 11, adding a column with a constant default is a metadata-only change and finishes immediately. The server stores the default in the catalog and applies it when reading old rows, so it does not rewrite the table. On a table with 50 million rows, that is milliseconds instead of minutes.
It is still slow when the default is volatile, meaning its value can differ per row, such as
random()orclock_timestamp(). Then every existing row must be rewritten, and the table is locked for the duration. Anow()default is a special case worth knowing: it is evaluated once per statement, so it counts as non-volatile, but I would check rather than rely on memory.- Constant default: fast on PostgreSQL 11 and later.
- Volatile default: add the column nullable, then backfill in batches.
- NOT NULL: add with
NOT VALIDcheck, then validate (Q68).
The habit I recommend: test the exact statement on a copy of the production-sized table and look at the time and the locks, because versions and expressions both change the answer.
- "Why does a short
ALTERsometimes block everything?" Because a lock request waits in a queue, and queued requests block everything behind them.
ALTER TABLEneeds a strong lock. If a long-running transaction already holds a weaker lock on the table, say a report that reads orders for ten minutes, the ALTER cannot start and waits.While it waits, it sits in the lock queue. Every new query on that table, even a simple SELECT, wants a lock that conflicts with the waiting ALTER, so it queues behind it. Within seconds, all traffic to the table is stuck. The ALTER itself would take 50 milliseconds, but it turned into a ten-minute outage.
The defence is
SET lock_timeout = '3s'at the start of every migration. The ALTER then gives up after 3 seconds, the queue drains, and the migration fails with a clear error that can be retried later, perhaps at a quieter time.I also add a
statement_timeoutso a statement cannot run forever. A failed migration is an inconvenience. A migration that blocks the table is an incident.- "How do I backfill without hurting production?"
In small batches, each in its own short transaction, run as a separate job, with a pause between batches, and written so it can be restarted at any point.
- Batch by primary key range: for example 5,000 ids at a time, so each transaction touches a bounded number of rows and holds locks briefly.
- Idempotent condition:
WHERE tip_cents IS NULL. After a crash, rerunning picks up only the rows still missing. - Pause and watch: sleep a short time between batches, and watch replication lag and database load. If lag grows, slow down.
The reason not to do it as one big UPDATE: one statement over 50 million rows holds locks, produces a huge amount of write-ahead log, and may delay replicas by minutes. It can also run for so long that the migration timeout kills it and rolls it all back.
Running it as a separate job, not inside the migration, lets me stop, resume and throttle it without touching the deployment. Only after it finishes do I add the NOT NULL constraint.
- "Are SQLite migrations different?"
Yes, because SQLite supports far fewer ALTER operations, and Alembic has to work around that. SQLite cannot drop or change a column type in place on many versions, and it cannot add most constraints to an existing table.
Alembic's batch mode (
op.batch_alter_table) handles this by creating a new table with the desired shape, copying the data across, dropping the old table, and renaming the new one. It works, and it is fine for tests and small applications.The danger is trusting it. A migration that passes on SQLite says nothing about locking, timeouts or a lock queue on PostgreSQL. A batch recreation of a big table would be a disaster on PostgreSQL, and the statements that are safe on one engine may be unsafe, or not even valid, on the other.
- Tests on SQLite: fine for the application tests that create tables from the models.
- Migration tests: run on a real PostgreSQL, in CI, with the same major version as production.
The engine in the test should be the engine in production wherever the behaviour depends on it.
Q69. "How do you run migrations in a deployment — as a job or at start-up?"
Reveal answer
Strong answer My default is a separate migration job that runs once per release before the new application version receives traffic: a Kubernetes Job or a Helm pre-upgrade hook that runs alembic upgrade head with its own credentials, and the rollout waits for it to succeed.
Why not at app start-up. With 20 pods starting together, 20 processes try to migrate at once (Alembic uses a version table, but concurrent DDL can still race or deadlock; a lock helps, but it is fragile). Start-up becomes slow and unpredictable, so readiness probes may fail and Kubernetes restarts pods halfway through a migration. The app's database user would also need DDL rights at runtime, which is excessive privilege.
When start-up migrations are acceptable: a single instance, a small internal tool or a development environment, ideally guarded by an advisory lock so only one process migrates.
Pair the job with backward-compatible migrations (expand and contract, Q68, Q144): the old code must keep working against the new schema, because during a rolling deploy both versions run at the same time.
Picture it A pre-deploy migration job and the app deployment waiting for it, as configuration to read (not run).
The setup: Helm pre-upgrade hook; the job uses the same image as the app and a migration-only database user.
# illustrative
apiVersion: batch/v1
kind: Job
metadata:
name: quickbite-migrate
annotations:
"helm.sh/hook": pre-upgrade,pre-install
"helm.sh/hook-delete-policy": before-hook-creation
spec:
backoffLimit: 0 # a failed migration stops the release; a human decides
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: registry.example/quickbite:{{ .Values.tag }}
command: ["alembic", "upgrade", "head"]
env:
- name: QB_DATABASE_URL
valueFrom: { secretKeyRef: { name: db-migrator, key: url } } # DDL-capable userWhat you see: One execution per release, separate credentials, and no retry loop that could re-run half a migration; the Deployment only rolls out if the hook succeeds.
Why: Migration is a release step with an owner and a log, not a side effect of a pod starting.
At start-up
Every pod tries.
@asynccontextmanager
async def lifespan(app):
run_alembic_upgrade() # ❌ x20 pods
yieldAs a job
Once, before rollout.
# pre-upgrade hook
command: ["alembic", "upgrade", "head"]
# app pods start after it succeedsThe shift: Schema change is a one-time release action; pods are interchangeable workers that should not own it.
Land it I run Alembic as a pre-deploy job with its own credentials, keep migrations backward compatible for the rolling window, and only migrate at start-up for single-instance tools.
- "What if the migration fails halfway?"
The migration runs inside a transaction in PostgreSQL, so a failure rolls the whole thing back and the schema stays as it was. PostgreSQL supports transactional DDL:
CREATE TABLE,ALTER TABLEandDROPcan be undone, unlike in some other databases.The exceptions are statements that cannot run inside a transaction block.
CREATE INDEX CONCURRENTLYis the main one. If it fails halfway, it can leave an invalid index behind that you must drop by hand before trying again.So the sequence for a failed release is calm:
- The job fails: the Kubernetes Job or hook reports an error and the rollout stops.
- The old version keeps serving: nothing was switched yet, and the schema is unchanged.
- You fix and rerun: check for leftovers from non-transactional steps.
This is a reason to keep migrations small: one concern per migration means a failure leaves a clear, small situation. A single migration with twelve changes, some of them non-transactional, can leave you in a state that is hard to describe.
- "How do I roll back a bad release?"
I roll back the application to the previous image, and that works because the schema is backward compatible. The expand and contract approach (Q68) ensures that, at every release, the schema supports both the new code and the one before it.
Take a release that adds a nullable column
tip_cents. The new code writes it. If the release is bad, I deploy the previous image. The old code ignores the extra column and works. No database change is needed, and the rollback takes the time of a rolling deploy.The contract step, such as dropping the old column, is delayed until no running version needs it, which means at least one release later and after a safe period. By then, a rollback to a version that needs the old column is no longer on the table.
Rolling the database back, with a downgrade or a restore from backup, is the last resort. It can lose data written since the release, so I treat it as a disaster-recovery action and not as a normal rollback.
- "How do tests check migrations?"
In CI, with three checks, each aimed at a different failure.
- Empty database upgrade: create an empty PostgreSQL database, run
alembic upgrade headand see that it completes. This proves the chain of migrations works from nothing. - Models match migrations: run
alembic check, or a test that compares the migrated schema with the models' metadata. It fails if someone changed a model and forgot a migration. - Data-heavy migrations: for a risky one, load a database with sample or production-shaped data, run the migration and check both the time taken and the result.
I also check that there is exactly one head (Q67) and, where the team keeps downgrades, that
upgradethendowngradethenupgradeworks on the empty database.The engine must be the production engine and version. A migration test on SQLite proves very little for PostgreSQL behaviour, such as locks and transactional DDL (Q68). A Docker PostgreSQL container in CI costs a few seconds and removes that gap.
- Empty database upgrade: create an empty PostgreSQL database, run
- "Who gets DDL rights?"
Only the migration user. The application's database user gets exactly the rights it needs to do its work:
SELECT,INSERT,UPDATEandDELETEon its own tables, and usage on its sequences. It cannot create, alter or drop tables.That separation limits the damage from two kinds of mistakes. If a bug or an injection (Q65) lets someone run arbitrary SQL through the application, the worst they can do is what the app user can do. They cannot drop the orders table or alter its columns.
The migration user is a different role with the DDL rights, and its credentials are given only to the migration job, not to the long-running pods. In practice, that means two secrets in the cluster and two connection URLs, with the migration job reading its own.
- App role: data access only.
- Migration role: owns the tables, runs Alembic.
- Superuser: kept for people, not for services.
This is least privilege applied to the database, and it is one of the cheapest security wins in the whole chapter.
Q70. "Cache-aside with Redis in FastAPI — and how do you invalidate?"
Reveal answer
Strong answer Cache-aside (lazy loading) means the application manages the cache: on a read, look in the cache; on a miss, load from the database, store the result with a TTL (time to live), and return it. On a write, update the database first, then delete the cache entry, so the next read reloads fresh data. The cache is never the source of truth.
In FastAPI I use an async Redis client created in lifespan and shared (Q45), a small cache helper with get_json/set_json, namespaced keys with a version (menu:v2:restaurant:3), and a TTL on every entry, since invalidation can fail and the TTL bounds the staleness.
Invalidation options: delete on write (simple, the default), short TTL only (tolerate staleness, for example 30 to 60 s), versioned keys (bump a version number to invalidate a whole group), or events (a message on change evicts entries across services). Order matters: update the database, then delete the key; deleting first lets a concurrent reader refill the cache with the old value.
Cache what is read often and changes rarely (menus, restaurant details), not per-user private data unless the key includes the user, and never cache errors forever.
Redis is not available on the course machine, so the demo uses a small in-memory stand-in with the same get/set/delete shape; the client library (redis 8.1) is installed but no server was run.
Picture it The read path and write path with a counter on database queries.
The setup: get_menu is cache-aside with a 60-second TTL; update_menu writes then deletes the key.
import time
class FakeRedis: # stands in for redis.asyncio.Redis (no Redis server on this machine)
def __init__(self): self.d = {}
def get(self, k):
v = self.d.get(k); return v[1] if v and v[0] > time.monotonic() else None
def set(self, k, v, ex): self.d[k] = (time.monotonic() + ex, v)
def delete(self, k): self.d.pop(k, None)
db = {"menu:3": ["biryani", "dosa"]}; queries = {"n": 0}
def load_menu(rid):
queries["n"] += 1; return db[f"menu:{rid}"]
cache = FakeRedis()
def get_menu(rid): # cache-aside: read path
key = f"menu:{rid}"
hit = cache.get(key)
if hit is not None: return hit, "HIT"
value = load_menu(rid); cache.set(key, value, ex=60); return value, "MISS"
def update_menu(rid, items): # write path: update DB first, then invalidate
db[f"menu:{rid}"] = items; cache.delete(f"menu:{rid}")
print(get_menu(3), "| db queries:", queries["n"])
print(get_menu(3), "| db queries:", queries["n"])
update_menu(3, ["biryani", "dosa", "idli"])
print(get_menu(3), "| db queries:", queries["n"], "<- invalidated, fresh value loaded")Make the invisible visible: Run it.
(['biryani', 'dosa'], 'MISS') | db queries: 1
(['biryani', 'dosa'], 'HIT') | db queries: 1
(['biryani', 'dosa', 'idli'], 'MISS') | db queries: 2 <- invalidated, fresh value loadedWhat you see: First read: MISS and one database query. Second read: HIT, still one query. After an update the key was deleted, so the next read was a MISS and loaded the new three-item menu: two queries in total.
Why: Reads got faster and the data stayed correct after a write. The TTL is the safety net for the day a delete is lost.
Naive
No expiry, no invalidation.
v = redis.get(k)
if v is None:
v = load(); redis.set(k, v) # ❌ foreverCorrect
TTL and delete on write.
v = await r.get(k)
if v is None:
v = load(); await r.set(k, v, ex=60)
# on write: db.update(); await r.delete(k)The shift: A cache entry is a temporary copy with an expiry date; the database remains the truth.
Land it I use cache-aside with a TTL on every key, update the database first and then delete the key, and only cache data that is read often and safe to be briefly stale.
- "What can go wrong with delete-after-write?"
The delete-after-write order has a small race, and I accept it because the TTL bounds the damage. The sequence is: reader A misses the cache and reads the old row from the database. Writer B updates the row and deletes the cache key. Then A stores its old value into the cache, because A already holds it. The cache now has stale data and no one will delete it.
The window is small: A must be slow between reading and writing the cache, exactly across B's whole update. But at thousands of requests per second, small windows happen.
The damage is limited by the TTL on every key. With a 60-second TTL the stale entry disappears within a minute, and no more reads are wrong after that.
- Accept: for menus and restaurant details, a minute of staleness is fine.
- Versioned keys: include a version number in the key, and bump it on write, so A's late write goes to an old key nobody reads.
- Single write path: for data that must be exact, do not cache it, or write through one place.
- "Should I cache in process memory instead?"
In-process caches are right for tiny, slow-changing data, and Redis for shared data. A library such as
cachetools.TTLCachekeeps entries in the process's own memory. A lookup costs nanoseconds, with no network and no new service to run.The cost is that every worker and every pod has its own copy. With 3 pods and 4 workers each, there are 12 caches. A write that evicts the key in one process cannot reach the other eleven, so they serve the old value until their TTL expires. Memory is also multiplied by 12, and each cache warms up separately, so the database sees up to 12 misses per key after a deploy.
- Process memory: settings, feature flags, a list of countries; anything small that changes rarely or can be a minute stale.
- Redis: menus, shared rate limits, anything that must be evicted everywhere or is too big to copy 12 times.
- Both: a very short in-process TTL in front of Redis cuts Redis traffic.
My default is Redis for business data, and in-process only where staleness is harmless.
- "What do I store, objects or JSON?"
I store JSON of the response model, or msgpack, never pickle. The cache should hold the shape that the API serves, so that a hit skips both the database query and the mapping from rows to objects.
With Pydantic I call
model_dump_json()to produce the string on a miss, andModel.model_validate_json(text)on a hit. That validates the data on the way back in, so a cache entry written by an older version of the code, with a missing field, fails cleanly and is treated as a miss.The reason to avoid pickle is security. Unpickling data can run arbitrary code. If an attacker, or just another service with write access to Redis, can put bytes into your cache, then a pickle load becomes remote code execution on your API pods. JSON and msgpack carry only data.
- JSON: readable in
redis-cli, easy to debug, a little larger. - msgpack: smaller and faster, harder to read.
- Key versioning: change the key prefix (
menu:v3:) when the shape changes.
- JSON: readable in
- "What if Redis is down?"
I treat the cache as optional. If Redis is down, the service should get slower, not stop. The code catches connection errors, logs them, and falls through to the database as if the cache had missed.
Two details make this work. The first is a short timeout on every Redis call, for example 50 to 100 milliseconds. Without it, a hung Redis makes each request wait for the default socket timeout, and the cache outage becomes a full outage. The second is a circuit breaker or a simple "skip Redis for the next 10 seconds" flag after repeated failures, so the application does not pay the timeout on every request.
The hard part is what happens to the database. If 95% of reads were served from the cache and suddenly all reach the database, the load can be twenty times higher. That is a stampede (Q71).
- Size for the fallback: know what the database can survive.
- Protect it: rate limits, pool timeouts and a single flight on the hot keys.
- Test it: stop Redis in staging and watch.
Q71 · Scenario. "A cache stampede after a deploy flattened the database. Fix it."
Reveal answer
Strong answer The deploy emptied (or restarted) the cache, so a burst of requests all missed the same key at the same moment and each one ran the expensive query. With 200 concurrent requests and one hot key that is 200 identical queries; with many hot keys the database collapses. The same happens when many keys share a TTL and expire together.
Fixes, combined. Single flight (request coalescing): the first request that misses takes a lock for that key and loads the value; the others wait for the result. In-process an asyncio.Lock per key does it; across processes a short Redis lock (SET key NX PX) with a timeout.
TTL jitter: add random seconds to each TTL so keys do not expire together. Stale-while-revalidate: keep serving the old value for a short time while one request refreshes it. Warm the cache before taking traffic (a start-up job that loads the hottest keys, in readiness).
Protect the database: pool limits, statement timeouts and rate limiting so a stampede degrades gracefully.
Part of the answer is deploy hygiene: do not flush the cache on deploy, and roll pods gradually.
Picture it 200 requests hitting an empty cache for one key, with and without single flight, plus jittered TTLs.
The setup: The "database" takes 50 ms and counts calls.
import asyncio, random, time
db_calls = {"n": 0}
async def slow_db(key):
db_calls["n"] += 1; await asyncio.sleep(0.05); return f"value-of-{key}"
cache = {}
async def get_naive(key):
if key in cache: return cache[key]
v = await slow_db(key); cache[key] = v; return v # ❌ everyone who misses goes to the database
locks: dict[str, asyncio.Lock] = {}
async def get_single_flight(key):
if key in cache: return cache[key]
lock = locks.setdefault(key, asyncio.Lock())
async with lock: # ✅ one loader; the rest wait for its result
if key in cache: return cache[key]
v = await slow_db(key); cache[key] = v; return v
async def burst(fn):
cache.clear(); db_calls["n"] = 0; t = time.perf_counter()
await asyncio.gather(*[fn("menu:3") for _ in range(200)]) # 200 requests arrive right after a deploy empties the cache
return db_calls["n"], time.perf_counter() - t
async def main():
for name, fn in (("naive", get_naive), ("single flight", get_single_flight)):
n, dt = await burst(fn); print(f"{name:14}: 200 requests -> {n:3} database calls in {dt:.2f}s")
ttls = [round(60 + random.uniform(-6, 6)) for _ in range(5)]
print("jittered TTLs so keys do not all expire together:", ttls)
asyncio.run(main())Make the invisible visible: Run it.
naive : 200 requests -> 200 database calls in 0.05s
single flight : 200 requests -> 1 database calls in 0.05s
jittered TTLs so keys do not all expire together: [56, 60, 57, 54, 56]What you see: The naive version made 200 database calls. With single flight it made 1, and all 200 requests finished in about the same 0.05 s. The last line shows TTLs spread around 60 s.
Why: Everyone waited for the same answer instead of asking the same question 200 times. The speed is unchanged; the load on the database dropped by 200 times.
Naive
Every miss loads.
if key not in cache:
cache[key] = await db_load(key) # ❌ x200
return cache[key]Correct
One loader per key.
async with locks[key]:
if key not in cache:
cache[key] = await db_load(key) # ✅ x1The shift: Collapse identical concurrent work into one execution and share its result.
Land it I stop stampedes with single flight per key, jittered TTLs, optional stale-while-revalidate and warm-up, and I protect the database with limits so a miss storm degrades instead of collapsing.
- "How does single flight work across many pods?"
With a short Redis lock per key, so that exactly one request across all pods loads the value while the others wait. The lock is taken with
SET lock:menu:3 token NX PX 5000: NX means "only if it does not exist", and PX 5000 gives it a 5-second life.- Winner: the request whose SET succeeds loads from the database, writes the value to the cache with its TTL, and releases the lock, but only if the token is still its own.
- Waiters: the others see the lock is taken, wait 50 ms, and read the cache again, a few times.
- Crash: if the winner dies, the lock expires after 5 seconds by itself, so nobody waits forever.
The token matters: if the winner is slow and its lock expires, a second request takes a new lock, and the first must not delete that one on release.
Without a distributed lock, a per-process
asyncio.Lockper key still limits each pod to one query per key. With 10 pods that is 10 queries instead of 200, which is usually enough to protect the database, and it needs no Redis round trip. I start there and add the Redis lock only if 10 is still too many.- "What is stale-while-revalidate?"
Stale-while-revalidate gives each entry two expiry times. The soft expiry says "this value is getting old", and the hard expiry says "this value must not be served any more".
Before the soft expiry, requests get the cached value. Between soft and hard, the next request still gets the old value immediately, and also starts one background refresh, guarded by a lock so only one request refreshes. After the refresh, the cache holds a new value with new expiries. Only past the hard expiry does a request have to wait for the database.
Take a menu with a soft expiry at 60 seconds and a hard expiry at 300 seconds. At minute 61 the first request returns the old menu in a millisecond and triggers one query. Everyone else in that moment also gets the old menu. The database sees one query, not a burst, and users never wait.
The trade-off is that users may see data up to a few minutes old. For menus that is acceptable, for stock counts or balances it is not. I store the soft expiry inside the cached value, next to the data.
- "Why did my earlier user cache send 40 queries rather than 100?"
Because the cache in Q51 had no lock, so the first burst of requests all missed together and ran the query before any of them stored a result. The numbers were an example of that race at small scale.
The sequence is simple. A hundred requests arrive within a few milliseconds. Each looks in the empty cache, finds nothing, and starts the user lookup. The first query takes, say, 15 ms to return. During those 15 ms, every request that arrived has already missed, so each runs its own query.
The ones arriving after the first result is stored hit the cache. The count of queries is the number that arrived before the first result landed, which is why it can be 40 and not 100: the load decides it.
It is the same pattern as the deploy stampede, only smaller. The cache only helps for requests that arrive after the first value is stored.
- Fix: a per-key lock so that later requests wait for the first result.
- Test: fire 100 concurrent requests at an empty cache and assert one query.
- "How do I rehearse it?"
With a load test that empties the cache under traffic, while I watch database queries per second. A stampede protection that has never been tested is a hope, not a safeguard.
- Steady load: run a realistic request mix at a steady rate, enough to keep the cache warm, and record the baseline for database queries per second and p99 latency.
- Empty the cache: flush Redis, or restart the pods, in the middle of the run.
- Read the graph: compare the spike in database queries with the baseline.
If the baseline is 200 queries per second and the spike reaches 2,000, the protection is missing or not working: that is a tenfold spike, and a pool of connections sized for the baseline will time out (Q61).
With single flight, jittered TTLs and warm-up, the spike should stay within perhaps two or three times the baseline and settle in seconds. I would repeat the test after every change to the caching code, and run it in staging, never first in production.
The pass criterion is written down in advance: a number for peak queries per second and for error rate.
Q72. "What is an idempotency key, and how do you implement one for POST /orders?"
Reveal answer
Strong answer An idempotent operation has the same effect whether done once or many times. POST is not idempotent by nature: sending it twice can create two orders. An idempotency key is a unique token the client generates per logical attempt (a UUID) and sends in an Idempotency-Key header; the server remembers the result of the first request with that key and returns it for every retry.
Implementation. A table idempotency_keys(key PK, customer_id, request_hash, response_json, created_at). On POST /v1/orders: look up the key; if found and the request hash matches, return the stored response (replay); if found with a different hash, reject (422 in the canonical app, some APIs use 409); if not found, do the work and insert the key row in the same transaction as the order, so both exist or neither. The key is scoped by customer so users cannot collide. Keys expire after 24 hours or so.
Concurrent duplicates (two retries at the same instant) are settled by the unique constraint on the key: one insert wins and the other gets an integrity error, then reads the winner's stored response (Q73).
The canonical app replays with status 200 and an Idempotent-Replayed: true header.
Picture it Three calls with the same key: first try, retry with the same body, and same key with a different body.
The setup: A FastAPI route with a key table; the order insert and the key insert share one transaction.
import asyncio, hashlib, json, httpx
from fastapi import FastAPI, Header, HTTPException, Response
from sqlalchemy import create_engine, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
with engine.begin() as c:
c.execute(text("create table orders (id integer primary key autoincrement, total_cents integer)"))
c.execute(text("create table idempotency_keys (key text primary key, request_hash text, response_json text)"))
app = FastAPI()
@app.post("/v1/orders", status_code=201)
def create(body: dict, response: Response, idempotency_key: str = Header()):
h = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
with Session(engine) as s, s.begin(): # one transaction for lookup + insert
row = s.execute(text("select request_hash, response_json from idempotency_keys where key=:k"), {"k": idempotency_key}).first()
if row:
if row.request_hash != h: raise HTTPException(422, "Idempotency-Key reused with a different body")
response.status_code = 200; response.headers["Idempotent-Replayed"] = "true"
return json.loads(row.response_json)
oid = s.execute(text("insert into orders(total_cents) values (:t)"), {"t": body["total_cents"]}).lastrowid
out = {"id": oid, "total_cents": body["total_cents"]}
s.execute(text("insert into idempotency_keys values (:k,:h,:r)"), {"k": idempotency_key, "h": h, "r": json.dumps(out)})
return out
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
k = {"Idempotency-Key": "abc-123"}
for label, body in (("first try", {"total_cents": 450}), ("retry, same body", {"total_cents": 450}), ("same key, new body", {"total_cents": 999})):
r = await c.post("/v1/orders", json=body, headers=k)
print(f"{label:18} {r.status_code} replayed={r.headers.get('idempotent-replayed')} {r.json()}")
with engine.connect() as cx: print("orders in table:", cx.execute(text("select count(*) from orders")).scalar())
asyncio.run(main())Make the invisible visible: Run it.
first try 201 replayed=None {'id': 1, 'total_cents': 450}
retry, same body 200 replayed=true {'id': 1, 'total_cents': 450}
same key, new body 422 replayed=None {'detail': 'Idempotency-Key reused with a different body'}
orders in table: 1What you see: The first call returned 201 and created order 1. The retry returned the same order id with 200 and Idempotent-Replayed: true. Reusing the key with a different body was refused with 422. The table held one order.
Why: Two identical POSTs produced one order, which is the same result Part B measured. The request hash catches the client bug of reusing a key for something else.
Naive
Every POST creates.
@router.post("/orders", status_code=201)
def create(body: OrderCreate):
return svc.create(body) # ❌ 2 ordersCorrect
Key plus stored response.
@router.post("/orders", status_code=201)
def create(body: OrderCreate,
key: str = Header()):
return svc.create(body, key) # replayThe shift: Retrying a request must return the original outcome, not repeat the action.
Land it I make create endpoints idempotent with a client-supplied key, a stored request hash and response written in the same transaction as the order, and a unique constraint as the final arbiter.
- "Why store a hash of the request?"
To tell a real retry from a client bug. The key says "this is the same attempt", but the hash says whether the content is also the same. Both together define a true retry.
Take a client that reuses the key
abcfor two different orders by mistake, perhaps from a stuck UI state. Without a hash, the server finds the key, returns the first order's response, and the second order is silently never created. The customer believes they ordered two meals and gets one. With a hash of the request body stored next to the key, the second request has the same key and a different hash, and the server answers 422 (in the canonical app) instead of hiding the problem.- Same key, same hash: a retry, so replay the stored response.
- Same key, different hash: a bug, so reject with 422.
- New key: a new request, so do the work.
I hash a canonical form of the body (for example JSON with sorted keys) so that harmless differences such as key order do not look like different requests.
- "Who generates the key?"
The client generates it, once per user action, and reuses it on every retry of that action. A UUIDv4 is fine because it only needs to be unique and hard to guess within the customer's scope.
The server cannot invent it, because the server cannot know that two requests mean the same intent. From the server's side, two identical POST bodies could be two real orders of the same meal, or one order sent twice. Only the client knows which.
The precise rule is "one key per action, not per HTTP attempt". When a user taps "place order", the app creates the key and stores it with the pending cart. If the request times out, the retry sends the same key. If the user taps place order again, after the first one finished and the cart was cleared, that is a new action and it gets a new key.
- Create: when the user taps the button.
- Persist: with the pending order, so an app restart reuses it.
- Retire: after success or when the user cancels.
- "How long do I keep keys?"
Long enough to cover the longest time a client may keep retrying, which is commonly 24 hours. After that, a scheduled job deletes older rows so the table stays small.
The number follows from the retry behaviour. If a mobile app retries with backoff for a few minutes, an hour would do. Clients that queue requests offline and send them when the network returns may be late by hours or a day. Payment providers use similar windows, and 24 hours is a common choice, though you should check any provider's own documentation.
The cost of keeping keys is small. A row with a key, a hash and a response is maybe 1 to 2 KB. At 100,000 orders a day, 24 hours of keys is 100,000 rows, about 100 to 200 MB, which is trivial for PostgreSQL with an index on the key.
The trade-off is stated in the API documentation. A retry that arrives after the window cannot be recognised, so it may create a duplicate order. For that reason the window should be longer than any retry policy the client really uses, and the documentation should say what it is.
- "Which status for the replay?"
Either choice is fine if it is documented. Some APIs return the original status code again, 201 Created, for a replay, so the client cannot tell a replay from a first success and does not need to. The canonical app returns 200 and adds a header,
Idempotent-Replayed: true.The reasoning for 200 is honesty. 201 means "I created a new resource just now". On a replay, nothing was created: the order already existed. Answering 200 with the stored body, and marking it with the header, lets a client that cares, for logging or analytics, know this was a replay. A client that does not care reads the same body and gets the same order id.
- Replay with 200 plus header: precise; clients need to accept both 200 and 201 as success.
- Replay with the original 201: simplest for clients; the response hides that it was a replay.
The important rule is consistency: the same body for the same key, always. A conflicting body with the same key returns 422, not a replay. Whatever the choice, put it in the OpenAPI document so that client developers know which success codes to handle.
Q73 · Scenario. "Mobile clients retry POST /orders and create duplicate orders. Fix it end to end."
Reveal answer
Strong answer Mobile networks drop responses: the client sends the request, the server creates the order, the response is lost, the app retries, and a second order appears. The fix spans client, API and database.
Client: generate one idempotency key per "place order" tap, persist it with the pending cart, and reuse it on every retry with backoff (and jitter). API: require the Idempotency-Key header on POST /v1/orders (400 or 422 if missing), and implement Q72.
Database: a unique constraint on the key (scoped by customer) is the real guard, because two retries can arrive at the same instant, both pass an "already seen?" lookup, and race to insert. The loser catches IntegrityError, reads the stored order and returns it as a replay.
Downstream: pass the same key to the payment provider so a retried charge is also deduplicated, and publish the order event once through the outbox (Q75).
Also return a clear result on timeouts: if the client times out, it retries with the same key; the server answers with the existing order, whether it finished or is still in progress (a 409 with Retry-After for an in-flight duplicate is another option).
Picture it Five identical requests with the same key arriving at the same time.
The setup: A UNIQUE(key) column on orders; each handler waits 10 ms so all five pass any "seen?" check before inserting.
import asyncio, httpx, hashlib, json
from fastapi import FastAPI, Header, Response
from sqlalchemy import create_engine, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
with engine.begin() as c:
c.execute(text("create table orders (id integer primary key autoincrement, key text unique, total_cents integer)"))
app = FastAPI()
@app.post("/v1/orders", status_code=201)
async def create(body: dict, response: Response, idempotency_key: str = Header()):
await asyncio.sleep(0.01) # both retries get past any "already seen?" lookup
try:
with engine.begin() as c: # the UNIQUE(key) constraint is the real guard
oid = c.execute(text("insert into orders(key,total_cents) values (:k,:t)"), {"k": idempotency_key, "t": body["total_cents"]}).lastrowid
return {"id": oid}
except IntegrityError: # the loser reads the winner's order
with engine.connect() as c:
oid = c.execute(text("select id from orders where key=:k"), {"k": idempotency_key}).scalar()
response.status_code = 200; response.headers["Idempotent-Replayed"] = "true"; return {"id": oid}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
rs = await asyncio.gather(*[c.post("/v1/orders", json={"total_cents": 450}, headers={"Idempotency-Key": "mobile-77"}) for _ in range(5)])
print("status codes :", sorted(r.status_code for r in rs))
print("order ids :", {r.json()["id"] for r in rs})
with engine.connect() as cx: print("orders stored:", cx.execute(text("select count(*) from orders")).scalar())
asyncio.run(main())Make the invisible visible: Run it.
status codes : [200, 200, 200, 200, 201]
order ids : {1}
orders stored: 1What you see: One request got 201 and four got 200 (replays). All five returned the same order id, and exactly one order was stored.
Why: The unique constraint decided the winner, and the four losers recovered by reading the winner's row. No Python lock was needed, so it also works across many pods.
Naive
Check then insert.
if not exists(key): # ❌ two can pass
create_order(key)Correct
Insert, catch, read.
try:
create_order(key) # UNIQUE(key)
except IntegrityError:
return existing(key) # ✅ the loser readsThe shift: Let the database pick the single winner, and make losing a normal, handled outcome.
Land it I fix duplicate orders with a client-generated key reused on retries, a unique constraint as the arbiter, replay of the stored result, and the same key passed to payment and event publishing.
- "Why not a lock in Python?"
Because a Python lock only works inside one process. With several uvicorn workers and several pods, two retries of the same request can land on two different processes. Each process has its own lock object, so neither sees the other, and both proceed to create an order.
A lock in Python also disappears when the process restarts or crashes, and it cannot cover the time between the order insert and the commit in another process.
A distributed lock, for example in Redis, could cover several processes. But it adds a new moving part with its own failure modes: lock expiry, clock issues, and a Redis outage. And it would still need a database constraint for correctness, because a lock can expire in the middle of a slow operation.
The database already is the shared referee. A unique constraint on the key, scoped by customer, is enforced for every connection, in every process, across restarts. One insert wins and the other gets an
IntegrityError, which the service turns into a replay. That is simpler and safer than any lock, so I use the constraint as the guard and add locks only for performance, never for correctness.- "What if the first request is still running when the retry arrives?"
The unique constraint on the key still decides, and I can choose whether the second request waits or is told to come back. There are two designs.
- Key written at the end: the key row is inserted in the same transaction as the order. While the first request is still running, no key row is visible. The retry starts its own work and tries to insert the same key. One of the two inserts fails on the unique constraint. The loser reads the winner's stored response and returns it as a replay. No duplicate order exists.
- Processing row first: the service inserts a key row with status "processing" and commits at once. A retry that arrives sees it and returns 409 with
Retry-After, so the client waits a moment and retries.
The first design is simpler and does a little duplicate work under a race. The second avoids duplicate work and adds a state to manage: a "processing" row left behind by a crash must expire, otherwise the key is stuck forever.
I start with the first, and move to the second if the work is expensive.
- "What about payment, is it idempotent?"
Payment is idempotent only if I make it so. If the order is created once but the payment call is made twice, the customer is charged twice, and an order-level key does not help, because the payment provider knows nothing about it.
So the key travels downstream. I pass the same idempotency key, or a reference derived from the order id, to the payment provider in the header or field that it documents for this purpose. Most major providers support one; check the provider's documentation for the exact name and how long they remember keys.
The provider then does for us what we do for our clients. A retried authorisation with the same key returns the first authorisation's result, not a second charge.
- Same key on retry: the provider replays the result.
- Derive it from the order: for example
order-812-auth, so that it is stable if we retry from a background job. - Store the provider's id: on the order, in the same transaction as the status change.
Without this, even a perfect order endpoint can still double-charge.
- "How do I test this?"
With three tests, each aimed at one failure: concurrent duplicates, the conflict case and the replay response.
- Concurrent identical requests: fire, say, five identical POSTs with the same key at the same moment, with
asyncio.gatheragainst the ASGI app. Assert that the database holds exactly one order and that all five responses carry the same order id. - Different body, same key: send the same key with another body and assert 422.
- Replay marker: a sequential retry returns 200 with
Idempotent-Replayed: trueand the stored body.
The concurrency test must run on the real database engine. As in Q63, SQLite serialises writers, which can hide a race. On PostgreSQL the unique constraint is really tested.
One more case worth a test: the client times out and the server had in fact finished. Simulate it by sending the request, ignoring the response and sending it again. The second call must return the existing order, not create a new one.
Together, those tests describe the contract in executable form.
- Concurrent identical requests: fire, say, five identical POSTs with the same key at the same moment, with
Q74. "Optimistic locking with a version column in SQLAlchemy."
Reveal answer
Strong answer Optimistic locking assumes conflicts are rare. It does not lock rows; it detects a conflicting write at update time. Each row has a version number. A writer reads the row (version 1), and when it updates it includes WHERE id = :id AND version = 1 and sets version = 2. If someone else updated first, the version is no longer 1, zero rows match, and the writer knows its data was stale.
SQLAlchemy does this with __mapper_args__ = {"version_id_col": version}. The ORM adds the version to every UPDATE's WHERE clause, increments it, and raises StaleDataError if the row count is wrong. The service catches it and returns 409 or 412, or retries by reloading and re-applying the change.
Use it for user-edited records with low contention (order notes, profile edits, a restaurant's menu) and with If-Match ETags over HTTP (Q104). Use pessimistic locking (SELECT ... FOR UPDATE) or atomic updates when contention is high or the invariant is a counter (stock, Q63).
Optimistic locking prevents lost updates; it does not prevent an invalid state change by itself, so keep the state machine checks too.
Picture it Two sessions load the same order; one commits first, the other tries to commit a conflicting change.
The setup: version_id_col on an Order model; session A sets "preparing", session B sets "cancelled".
from sqlalchemy import create_engine, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
from sqlalchemy.orm.exc import StaleDataError
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
status: Mapped[str] = mapped_column(String(20))
version: Mapped[int] = mapped_column(default=1)
__mapper_args__ = {"version_id_col": version}
engine = create_engine("sqlite://"); Base.metadata.create_all(engine)
with Session(engine) as s: s.add(Order(id=1, status="placed")); s.commit()
a, b = Session(engine), Session(engine) # two requests load the same order
oa, ob = a.get(Order, 1), b.get(Order, 1)
print("both loaded version", oa.version)
oa.status = "preparing"; a.commit(); print("A committed, version now", oa.version)
ob.status = "cancelled"
try: b.commit()
except StaleDataError as e: print("B failed:", type(e).__name__, "|", str(e)[:105]); b.rollback()
print("final status:", Session(engine).get(Order, 1).status)Make the invisible visible: Run it.
both loaded version 1
A committed, version now 2
B failed: StaleDataError | UPDATE statement on table 'orders' expected to update 1 row(s); 0 were matched.
final status: preparingWhat you see: A committed and the version became 2. B's UPDATE matched 0 rows and raised StaleDataError. The stored status stayed preparing: B's change did not silently overwrite A's.
Why: Part B saw the same StaleDataError. B can now reload, look at the new state, and decide whether its cancellation still makes sense.
JPA
@Version field.
// illustrative
@Version
private long version; // -> lock exceptionSQLAlchemy
version_id_col.
version: Mapped[int] = mapped_column(default=1)
__mapper_args__ = {"version_id_col": version}
# StaleDataError on conflictThe shift: The two ORMs implement the same idea with the same keyword: a version number in the WHERE clause.
Land it I use a version column for low-contention edits, turn StaleDataError into 409 or 412 with a reload hint, and use atomic updates or row locks for hot counters.
- "How does this connect to
If-Match?" The version column becomes the ETag, and the HTTP header
If-Matchcarries the version the client last saw. That moves the check from the database layer to the protocol, so a client learns about a conflict before it sends anything damaging.The flow: a GET returns the order with
ETag: "3". The client edits and sends PATCH withIf-Match: "3". The server loads the order, compares its stored version, and if it is not 3, answers 412 Precondition Failed without attempting the update. If it matches, the update runs, withversion_id_colas the second line of defence against a race between the check and the write, and the response carriesETag: "4".- 412: "the precondition you gave is no longer true", the correct code for a failed If-Match.
- 428: optional; return it if the header is required and missing.
- 409: still used for business conflicts such as an illegal state change.
The client's response to 412 is to GET again, show the user the current data, and let them merge.
- "Should the service retry on
StaleDataError?" It depends on whether the change still makes sense after the reload. I retry for changes that commute, and I return 409 for decisions that depend on what the user saw.
A change commutes when order does not matter, for example appending a note to an order. If someone else changed the order in the meantime, I reload, add my note again, and try the update. Two or three attempts are usually enough, and each attempt is cheap.
A decision does not commute. Take "cancel this order", which the user chose because the screen showed status "placed". If the kitchen moved it to "preparing" in the meantime, a silent retry would cancel an order that is already being cooked. The user must see the new state and decide again, so the service returns 409 and a clear message.
- Commutative: reload, reapply, retry up to three times, then 409.
- State-dependent: never auto-retry; return 409.
A loop without a limit is a trap: under heavy contention it spins, which is a reason to use pessimistic locking.
- "When is pessimistic locking better?"
Pessimistic locking is better when conflicts are frequent or when the critical section has side effects that cannot simply be repeated. Optimistic locking assumes conflicts are rare, so its cost is paid only when they happen. That assumption fails for hot rows.
Suppose 50 requests per second update the same row, such as a counter. With optimistic locking, most attempts hit a stale version, fail and retry, and the retries conflict again. Work is wasted, latency climbs, and the system can enter a retry storm. With
SELECT ... FOR UPDATE, requests queue on the row and each succeeds in turn, so no work is thrown away.- Hot counters: prefer an atomic UPDATE (Q63), or a lock.
- External effects inside the section: if the step charges a card or sends an email, retrying it is not free, so take the lock first.
- Rare edits: keep optimistic.
The cost of a lock is waiting, and the risk is a deadlock when several rows are locked in different orders. I keep the locked section short, lock rows in a fixed order, and set a lock timeout.
- "Does it protect bulk updates?"
No. The ORM's version check works only for changes that go through the ORM unit of work. A statement such as
session.execute(update(Order).where(...).values(...)), or a bulk update, goes straight to the database and bypasses the mapper's automaticAND version = :vclause.This surprises people who expect "the model has a version column, so everything is protected". In reality, the protection is a feature of one code path.
If a bulk or Core update must respect the version, I include the condition myself and increment the column in the same statement:
version in a Core updateresult = session.execute( update(Order) .where(Order.id == oid, Order.version == seen) .values(status="ready", version=Order.version + 1) ) if result.rowcount == 0: raise StaleOrder()The row count tells me whether I won. Other writers, such as a script or another service updating the table with plain SQL, also need to follow the same convention, or the version no longer means anything. I document the rule next to the model.
Q75. "How do you publish an "order created" event without a dual write?"
Reveal answer
Strong answer A dual write means writing to two systems (the database and Kafka) in one request without a shared transaction. If the database commit succeeds and the Kafka send fails, the event is lost; if the send succeeds and the commit fails, you published an order that does not exist. No amount of try/except fixes it, because a crash can land between the two writes.
The fix is the transactional outbox. In the same database transaction that inserts the order, insert a row into an outbox table (topic, payload, created_at, sent). Commit once: the order and its event exist together or not at all. A separate relay then reads unsent outbox rows and publishes them to Kafka, marking them sent. The relay may crash and resend, so the guarantee is at least once, and consumers must be idempotent (dedupe on the event id).
Relay options: a polling process (simple), or change data capture (Debezium reads the database log and publishes outbox rows with no polling). Both are described in the course.
Related chapters: the pattern in E7 · Microservices, outbox and relaying it with CDC in E17 · Kafka, outbox with CDC.
Picture it One failed order that rolls back with its event, one successful order, and a relay that publishes once.
The setup: SQLite; place_order writes the order and the outbox row in one transaction; the relay runs twice.
import json
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
engine = create_engine("sqlite://")
with engine.begin() as c:
c.execute(text("create table orders (id integer primary key, total_cents integer)"))
c.execute(text("create table outbox (id integer primary key autoincrement, topic text, payload text, sent integer default 0)"))
def place_order(oid, fail=False):
with Session(engine) as s, s.begin(): # ONE transaction: order row + event row
s.execute(text("insert into orders values (:i, 450)"), {"i": oid})
s.execute(text("insert into outbox(topic,payload) values ('orders.created', :p)"), {"p": json.dumps({"order_id": oid, "total_cents": 450})})
if fail: raise RuntimeError("payment step failed")
try: place_order(1)
except RuntimeError: pass
try: place_order(2, fail=True)
except RuntimeError: print("order 2 failed -> both rows rolled back together")
published = []
def relay(): # a separate process polls the outbox (or CDC reads the log)
with Session(engine) as s, s.begin():
for r in s.execute(text("select id, topic, payload from outbox where sent=0 order by id")).all():
published.append((r.topic, r.payload)); s.execute(text("update outbox set sent=1 where id=:i"), {"i": r.id})
relay(); relay() # second run finds nothing new
with engine.connect() as c:
print("orders:", c.execute(text("select id from orders")).scalars().all(), "| outbox rows:", c.execute(text("select count(*) from outbox")).scalar())
print("published:", published)Make the invisible visible: Run it.
order 2 failed -> both rows rolled back together
orders: [1] | outbox rows: 1
published: [('orders.created', '{"order_id": 1, "total_cents": 450}')]What you see: The failed order left no order and no event, because both rows were rolled back together. The successful order produced one event. The second relay run found nothing new, so the event was published exactly once from this relay.
Why: The event is now part of the data, committed atomically with it. Publishing becomes a retryable background job instead of a risky step in the request.
Naive
Two writes, no shared fate.
session.commit() # order saved
producer.send(topic, ev) # ❌ crash here = lostCorrect
Event row in the same commit.
with session.begin():
session.add(order)
session.add(Outbox(topic=T, payload=ev))
# a relay publishes laterThe shift: Make the event a row in the same transaction, and publish it afterwards.
Land it I never write to the database and Kafka in one request; I write the event to an outbox table in the same transaction and relay it, accepting at-least-once and idempotent consumers.
- "Does the outbox guarantee ordering?"
Within one relay, yes per order, and across orders, no, and none is needed. The relay reads unsent rows ordered by id and publishes them in that order, which is the insert order. If the Kafka message is keyed by the order id, all events for one order go to the same partition, and Kafka keeps order within a partition. So "placed" is seen before "preparing" for order 812.
Across different orders there is no global order. Events for order 812 and order 813 may arrive in either sequence at a consumer, and that is fine, because no business rule depends on it.
Two cautions. First, ordering holds only if one relay instance publishes at a time, or if each relay handles a distinct set of keys. Several relays reading the same rows without coordination can reorder events. Second, a failed publish must be retried before moving on, or the next event could overtake it.
- One reader per key range: or one relay with a lock.
- Key by order id: in the Kafka producer.
- Consumers: tolerate duplicates and apply a version or sequence number if they need to detect an out-of-order event.
- "How do consumers cope with duplicates?"
Every event carries a unique id, and consumers record the ids they have processed, or make their effect idempotent, so a repeat changes nothing. Duplicates are the price of never losing an event, and the outbox's at-least-once guarantee makes them certain to occur sometimes: the relay publishes, crashes before marking the row sent, and publishes again on restart.
- Processed-ids table: the consumer inserts the event id into a table with a unique constraint in the same transaction as its own work. If the insert fails on the constraint, it is a duplicate and the work is skipped.
- Idempotent upserts: if the effect is "set this order's status to ready", repeating it is harmless without any table.
- Naturally idempotent effects: avoid "add 1 to a counter"; send the new total or use the dedupe table.
The dedupe table needs cleaning, so I keep ids for a time longer than the longest realistic redelivery, such as 7 days.
The same thinking applies to our own idempotency keys (Q72). Everything in a distributed flow should be safe to repeat.
- "Polling relay or Debezium?"
I start with polling and move to Debezium when the load or latency requires it. The two differ in simplicity, delay and what you must run.
- Polling relay: a small process that runs
SELECT ... WHERE sent = false ORDER BY id LIMIT 100every few hundred milliseconds, publishes, and marks rows sent. It is simple, easy to debug and needs nothing new. The cost is a steady query load on the database and a delay of up to one polling interval. - Debezium (change data capture): reads PostgreSQL's write-ahead log and publishes outbox rows to Kafka with low latency and no polling queries. The cost is an operational component: Kafka Connect, replication slots to watch, and connector upgrades.
A replication slot that is not consumed makes PostgreSQL keep its log files, so a stuck connector can fill the disk. That is an operational risk worth planning for.
At a few hundred events per second and a latency budget of a second, polling is fine. I would switch when the polling interval becomes the latency problem or the query load is visible in the database graphs.
- Polling relay: a small process that runs
- "How do I clean the outbox?"
By deleting or archiving rows that have been sent, on a schedule, or by partitioning the table by day. Left alone, the outbox only grows, since every order adds rows, and the relay's query has to skip over more and more old rows.
The simple version is a nightly job:
DELETE FROM outbox WHERE sent = true AND created_at < now() - interval '3 days', in batches of a few thousand rows to avoid long locks. Keeping three days gives time to investigate a problem and to replay events if a consumer lost some.The better version at high volume is partitioning by day. Then cleaning means dropping the partition of a day that is old enough, which is nearly instant and leaves no dead rows for VACUUM to handle.
- Index: a partial index on
id WHERE sent = falsekeeps the relay's query fast even when the table is large. - Monitor: the count of unsent rows and the age of the oldest one; a growing number means the relay is stuck.
The size of the unsent backlog is the metric I would alert on.
- Index: a partial index on
Q76. "Where should business logic live — endpoint, service or model?"
Reveal answer
Strong answer In the service. The endpoint should only translate HTTP: parse and validate input, call the service, and map the result or exception to a response. The service holds rules (check stock, compute totals, allowed state transitions, idempotency) and owns the transaction. Repositories hold queries. Models hold data, plus small invariants that belong to one object.
Why not the endpoint: a rule written there cannot be reused by a background job, a CLI or a message consumer, and testing it needs an HTTP request. Why not "fat models" (the Active Record style of Django): SQLAlchemy models are plain mapped classes tied to a session, and rules that touch several objects or call external systems do not belong on a single row object. Why not scattered: the same rule in three places will diverge.
Signs that logic is in the wrong place: an endpoint longer than ~15 lines, session.query in a router, HTTPException raised from a service (services should raise domain errors, and the HTTP layer maps them), or tests that need a database to check a price calculation.
The benefit is testability: a service built on a fake repository tests business rules in microseconds.
Picture it A service with no FastAPI or database import, tested with a fake repository.
The setup: OrderService.create_order reserves stock and totals the price through a repository interface.
from dataclasses import dataclass
class OutOfStock(Exception): ...
@dataclass
class Item: id: int; stock: int; price_cents: int
class FakeRepo:
def __init__(self, items): self.items = {i.id: i for i in items}; self.saved = []
def reserve(self, item_id, qty):
it = self.items[item_id]
if it.stock < qty: return False
it.stock -= qty; return True
def price(self, item_id): return self.items[item_id].price_cents
def save_order(self, total): self.saved.append(total); return len(self.saved)
class OrderService: # no FastAPI import anywhere in here
def __init__(self, repo): self.repo = repo
def create_order(self, lines: list[tuple[int, int]]):
total = 0
for item_id, qty in lines:
if not self.repo.reserve(item_id, qty): raise OutOfStock(item_id)
total += self.repo.price(item_id) * qty
return self.repo.save_order(total), total
repo = FakeRepo([Item(1, 5, 300), Item(2, 0, 120)])
svc = OrderService(repo)
print("good order ->", svc.create_order([(1, 2)]))
try: svc.create_order([(2, 1)])
except OutOfStock as e: print("out of stock ->", type(e).__name__, "item", e.args[0])
print("this ran with no HTTP, no database, no framework")Make the invisible visible: Run it.
good order -> (1, 600)
out of stock -> OutOfStock item 2
this ran with no HTTP, no database, no frameworkWhat you see: The service created an order and totalled 600 cents (two items at 300). A sold-out item raised OutOfStock. The whole thing ran with no HTTP, no database and no framework.
Why: Because the rule lives in a plain class, the quickest tests exercise it directly. Only a handful of API tests then need the full stack.
Naive
Rules inside the endpoint.
@router.post("")
def create(body: OrderCreate, db=Depends(s)):
if db.get(Item, ...).stock < q: # ❌
raise HTTPException(409)Correct
Endpoint delegates.
@router.post("")
def create(body: OrderCreate,
svc: Svc = Depends(get_service)):
return svc.create_order(body)The shift: The endpoint knows HTTP; the service knows the business.
Land it I keep business rules and transactions in services that raise domain errors, so they can be reused outside HTTP and tested in microseconds with fake repositories.
- "Is this overkill for a small service?"
-
Not overkill, as long as the service layer is allowed to be small. For a five-endpoint service it can be one function per use case in a file called
services.py, with no classes, no interfaces and no dependency-injection framework.The reason I still want it is the line between HTTP and rules. The moment a rule such as "an order needs at least one line" or "a delivered order cannot be cancelled" sits in a router, a background job or a test has to fake an HTTP request to reach it.
A function costs ten lines and buys me a place to put the transaction. I promote it to a class only when it starts carrying state or several collaborators, for example a repository, a payment client and a clock that tests want to replace.
What I refuse to do is skip the layer because the service is small. Small services grow, and moving rules out of routers later is the expensive refactor.
- "Where does validation belong?"
-
There are two kinds of validation and they live in different places, because they need different information.
- Shape validation: types, ranges, lengths, "quantity between 1 and 20", "email looks like an email". It needs only the request body, so Pydantic does it at the boundary and FastAPI returns 422 before my code runs.
- Business validation: "the restaurant is open", "stock is available", "this status change is legal". It needs data from the database and it changes when policy changes, so it lives in the service.
The test I use is simple: if answering needs a database read or the clock, it is not a Pydantic validator. A validator that queries the database runs before the transaction starts, so the answer can be stale by the time the order is written. Putting the business check inside the service means it runs in the same transaction as the stock update, and it can be unit-tested with a fake repository.
- "Should the service return Pydantic models or ORM objects?"
-
The service should return domain results, either ORM objects or small plain dataclasses, and the router maps them to the response model. I would not return Pydantic response models from the service.
The reason is direction of dependency. The response model is the HTTP contract: field names, hidden fields, formats the mobile app relies on. If the service builds it, then a change to the contract, such as renaming
total_centsin version 2 of the API, forces a change in business code, and the service can no longer be reused by a worker or a CLI that has no response at all.In FastAPI the mapping is cheap. With
response_model=OrderOutandfrom_attributesturned on in the model config, the router can return the ORM object and FastAPI converts and filters it.One caution: do not hand out ORM objects after the session has closed, or lazy-loaded fields will fail. Load what the response needs inside the service.
- "What about "anemic" domain models?"
-
An anemic model is one that holds only data, with all behaviour in services. I do not treat that as a sin, but I do move behaviour onto the model when it concerns one object and needs no outside help.
A good example is
order.can_transition_to(status). It reads only the order's own current status and a small table of allowed moves, such as placed to accepted and accepted to preparing. Putting it on the model means every caller, whether router, service or test, asks the same question the same way, and it can be tested without a database.The line I draw is "who does it need to look at". Anything that needs another aggregate (the restaurant's opening hours), a query (current stock) or I/O (a payment call) goes in the service, because a mapped SQLAlchemy class is tied to a session and should not reach out to the world.
So: small invariants on the model, workflows in the service, and no argument about purity.
Q77 · Scenario. "An endpoint makes three external calls one after another (300 ms each). Make it faster."
Reveal answer
Strong answer Sequential awaits add up: 3 × 300 ms = 900 ms. If the calls do not depend on each other, run them concurrently so the total is about the slowest one, 300 ms. In async code: asyncio.gather(a(), b(), c()) or, better in modern Python, asyncio.TaskGroup, which cancels the other tasks if one fails and raises the errors together.
Details that matter. The calls must be genuinely async (an async client, not blocking calls). Each call needs its own timeout (and the endpoint an overall deadline), otherwise one slow call holds the request. Decide per call what a failure means: required (fail the request) or optional (degrade: use a default, skip loyalty points). gather(..., return_exceptions=True) lets you collect failures and degrade. Bound concurrency if the number of calls grows (a semaphore), so one request cannot flood a partner.
If calls depend on each other, restructure what you can (prefetch, parallelise independent parts) or cache results that rarely change (menu data). For sync endpoints (def), use a thread pool executor for the same effect.
Beyond that: ask whether the endpoint should do all three calls inline at all, or whether some can move to the background.
Picture it Three 300 ms calls run sequentially, with gather, with a TaskGroup, and with one failing optional call.
The setup: asyncio.sleep stands in for a network call.
import asyncio, time
async def call(name, ms):
await asyncio.sleep(ms / 1000); return name
async def sequential():
return [await call("menu", 300), await call("pricing", 300), await call("loyalty", 300)]
async def concurrent():
return await asyncio.gather(call("menu", 300), call("pricing", 300), call("loyalty", 300))
async def with_taskgroup():
async with asyncio.TaskGroup() as tg: # a failure cancels the siblings
ts = [tg.create_task(call(n, 300)) for n in ("menu", "pricing", "loyalty")]
return [t.result() for t in ts]
async def partial(): # tolerate a failing optional call
async def bad(): await asyncio.sleep(0.05); raise TimeoutError("loyalty down")
r = await asyncio.gather(call("menu", 300), bad(), return_exceptions=True)
return [x if not isinstance(x, Exception) else f"degraded({x})" for x in r]
async def main():
for fn in (sequential, concurrent, with_taskgroup, partial):
t = time.perf_counter(); r = await fn(); print(f"{fn.__name__:15} {time.perf_counter()-t:.2f}s {r}")
asyncio.run(main())Make the invisible visible: Run it.
sequential 0.90s ['menu', 'pricing', 'loyalty']
concurrent 0.30s ['menu', 'pricing', 'loyalty']
with_taskgroup 0.30s ['menu', 'pricing', 'loyalty']
partial 0.30s ['menu', 'degraded(loyalty down)']What you see: Sequential: 0.90 s. gather and TaskGroup: 0.30 s. With a failing optional call and return_exceptions=True, the endpoint still answered in 0.30 s with a degraded entry for the failed one.
Why: Waiting overlaps, so total time becomes the longest wait rather than the sum. The partial case shows the design decision: what does the user see when the optional call fails?
Naive
One after another.
menu = await get_menu(rid)
price = await get_pricing(rid)
loyalty = await get_loyalty(uid) # 900 msCorrect
Together, with timeouts.
async with asyncio.TaskGroup() as tg:
m = tg.create_task(get_menu(rid))
p = tg.create_task(get_pricing(rid))
l = tg.create_task(get_loyalty(uid))The shift: Independent waits can overlap; only dependent steps must queue.
Land it I run independent calls concurrently with a TaskGroup, give each its own timeout, decide which ones may degrade, and bound the concurrency.
- "
gatherorTaskGroup?" -
TaskGroup, in Python 3.11 and later, for most cases. It gives structured concurrency: the group does not finish until every task inside it has finished, and if one task raises, the others are cancelled and the errors arrive together as anExceptionGroup.Plain
gatherbehaves differently. By default, if one awaitable raises,gatherre-raises that error to you but leaves the others running in the background, which can leak work. Withreturn_exceptions=Trueit waits for all and hands back results and exception objects mixed in one list.A small run on this machine shows the difference.
q77_gather_vs_taskgroup.pyruns offlinesequential: 0.9 s gather: 0.3 s TaskGroup failed after 0.05 s: partner downMy rule:
TaskGroupwhen all three calls are required, since a failure should stop the rest quickly.gather(return_exceptions=True)when each call is optional and I want to degrade call by call. - "What if the calls use a sync library?"
-
Move each sync call off the event loop and let threads overlap them. In an
async defendpoint I wrap each call inrun_in_threadpool(from Starlette) and gather them. Or I make the endpoint a plaindefand use aThreadPoolExecutorinside it.Threads work for this because waiting on a network socket releases Python's lock, so three 300 ms calls in three threads still finish in about 300 ms.
The limit is the pool. FastAPI and AnyIO share a default pool of 40 threads for all requests. If every request uses three threads for 300 ms, about 13 requests at once fill the pool and the next ones queue. A fourth call from another endpoint can then wait behind them for reasons unrelated to its own work.
So I use threads as a bridge for a library that has no async version, and I set a timeout on every call. Where the calls are slow and frequent, I switch to an async client such as httpx, which needs no threads at all.
- "How do I stop one slow call hurting the whole request?"
-
Give every call its own timeout, give the endpoint an overall deadline, and decide ahead of time what each failure means.
Tail latency is the reason. When I wait for three calls in parallel, the request is as slow as the slowest one. Suppose each call is slower than 1 second one time in a hundred. The chance that at least one of three is slow is about 3 in 100, so the combined request has three times the slow-request rate of any single call. Average speed hides this; the worst call decides.
Concretely I wrap each call in
asyncio.timeout(0.8)and configurehttpx.Timeoutwith separate connect and read limits. Around the whole group I add one deadline of, say, 1.5 seconds.Then I mark each call required or optional. If loyalty points time out, I return the order without them and log it. If the price lookup times out, I fail with 503 and
Retry-After. - "Should this be in the request at all?"
-
Often no. If the response does not depend on a call's result, the request should not wait for it.
I sort the three calls by one question: does the client need this answer in the response body? A price lookup does. A loyalty-points update and an analytics event do not. The customer cares that the order exists, not that points were added within the same 300 ms.
For the second kind there are two options. A
BackgroundTasksjob runs after the response is sent and is fine for cheap, best-effort work. It is lost if the process crashes. For anything that must happen, I write an event to an outbox table in the same transaction as the order and let a relay process deliver it, so the work survives restarts and can be retried.The result is a faster endpoint and a smaller blast radius. The fastest call is the one the request never waits for, and a failing partner can no longer fail the order.
Q78. "Who owns the commit in a service method — the endpoint, the service or the dependency?"
Reveal answer
Strong answer The service. The transaction boundary is the business operation, so the code that knows what the operation is should write with session.begin(): around it. The endpoint does not commit (it does not know the steps), and the dependency does not commit (it runs after the endpoint returned).
The yield-dependency timing is the decisive reason. On FastAPI 0.141, teardown after a successful endpoint runs after the response is sent. A commit there that fails (constraint violation, serialization failure) cannot change the response: Part B measured that a failed commit in teardown still returned 200. The client believes the order exists and it does not. A commit inside the service happens before the endpoint returns, so a failure becomes a normal 409 or 503.
So: the dependency opens and closes the session, the service commits or rolls back, repositories never commit, and nested service calls take the session and do not commit.
Picture it The service commits inside with session.begin(). A conflict raised in the service rolls back the earlier insert, and the endpoint reports 409.
The setup: stock has quantity 1. The service inserts an order, then does a conditional stock decrement; a second identical request finds none.
import asyncio, httpx
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
with engine.begin() as c:
c.execute(text("create table orders (id integer primary key, total integer)")); c.execute(text("create table stock (item integer primary key, qty integer check (qty >= 0))"))
c.execute(text("insert into stock values (1, 1)"))
def get_session():
s = Session(engine)
try: yield s
finally: s.close() # the dependency only opens and closes
class OrderService:
def __init__(self, s: Session): self.s = s
def create(self, qty: int):
with self.s.begin(): # the service owns the transaction
self.s.execute(text("insert into orders(total) values (450)"))
r = self.s.execute(text("update stock set qty = qty - :q where item = 1 and qty >= :q"), {"q": qty})
if r.rowcount == 0: raise HTTPException(409, "out of stock") # raising rolls back the insert above
return {"ok": True} # commit already happened before this line
app = FastAPI()
@app.post("/orders")
def create(qty: int, s: Session = Depends(get_session)): return OrderService(s).create(qty)
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
for qty in (1, 1):
r = await c.post(f"/orders?qty={qty}")
with engine.connect() as cx: n = cx.execute(text("select count(*) from orders")).scalar()
print(f"qty={qty} -> {r.status_code} {r.json()} | orders in table: {n}")
asyncio.run(main())Make the invisible visible: Run it.
qty=1 -> 200 {'ok': True} | orders in table: 1
qty=1 -> 409 {'detail': 'out of stock'} | orders in table: 1What you see: The first request returned 200 and left one order. The second returned 409, and the table still had one order: the insert made before the failed stock update was rolled back with it.
Why: The decision to commit or roll back sits in the one place that knows whether the business operation succeeded, and it happens before the response is created.
Spring
Annotation on the service.
// illustrative
@Service class OrderService {
@Transactional
Order create(...) { ... }
}FastAPI
Block in the service.
class OrderService:
def create(self, ...):
with self.session.begin():
... # commit here, before returningThe shift: In both frameworks the service method is the transaction; FastAPI makes the boundary a visible block.
Land it I let the service own the commit with a begin() block, so failures become proper HTTP errors, and the dependency only opens and closes the session.
- "Why not commit in the endpoint?"
-
It works, and plenty of small apps do it, but it spreads a rule across the code base and invites a quiet bug.
The bug is the accidental double transaction. Say an endpoint calls
order_service.create()and thenloyalty_service.add_points(), each of which commits. Now there are two transactions. If the second fails, the order exists with no points, and nobody chose that. If the endpoint commits once at the end instead, every service call inside shares one transaction, but now the endpoint needs to know which steps belong together, and that is business knowledge.The repetition is a smaller cost: every endpoint carries the same commit and rollback lines, and one forgotten commit means a 201 response with nothing written.
Putting
with session.begin():inside the service method matches the transaction to the business operation. One operation, one transaction, and the endpoint stays an HTTP translator. - "What if one endpoint needs two services in one transaction?"
-
Write a higher-level method, a use case, that owns the single transaction and calls both services inside it. The inner services take the session as an argument and never commit.
The structure looks like this in words:
- Use case:
place_order_and_award_points(session, ...)openswith session.begin():once. - Inner calls: it calls
OrderService.create_order(session, ...)andLoyaltyService.add_points(session, ...). Both only add or update rows. - Outcome: if either raises, the whole
begin()block rolls back and neither change is stored. If both finish, one commit covers both.
The rule to enforce in review is "only the outermost method begins a transaction". A service that can be called alone and also from a use case should accept the session and leave the commit to its caller. That is the same reason repositories never commit.
- Use case:
- "What about read endpoints?"
-
Read endpoints need no commit. They run a query and return rows, and when the dependency closes the session at the end of the request, SQLAlchemy releases the connection and rolls back the open read-only transaction, which does nothing harmful.
One thing to check is that the session really is closed. A read that begins an implicit transaction and never closes it holds a pooled connection, and with a pool of, say, ten, ten forgotten sessions block every other request. The yield dependency with
finally: session.close()prevents that.When a read endpoint runs several queries that must agree, such as an order and its lines and its payment status, I put them in one transaction. With PostgreSQL's default isolation level, READ COMMITTED, each statement sees the latest committed data, so two queries can see different states. For a stronger snapshot I raise isolation to REPEATABLE READ for that transaction. Most list endpoints do not need it.
- "Does autobegin change this?"
-
Yes, and it is worth knowing so it does not surprise you. SQLAlchemy 2.x sessions autobegin: the first time you use the session, for a query or a flush, it starts a transaction without being asked.
Here is what that means after
with session.begin():finishes. The block commits and ends that transaction. If any later code touches the same session, for example reading an attribute that needs a refresh, the session quietly begins a new transaction and holds a connection.It is harmless provided the session is short-lived. Because the dependency opens one session per request and closes it in
finally, anything that autobegan after the commit is rolled back and the connection returns to the pool.There is one trap. Calling
session.begin()while an autobegun transaction is already active raises an error. So I do not run a read before thebegin()block in the same session. I run reads inside the block, or I open the block first.
Q79. "Soft delete versus hard delete in an API."
Reveal answer
Strong answer A hard delete removes the row. A soft delete keeps the row and marks it (deleted_at timestamp or is_deleted flag), and every query must exclude marked rows.
Choose hard delete when the data has no value after removal, or when the law requires erasure (privacy requests): then really remove it, including backups on their schedule. Choose soft delete when you need undo, audit, referential integrity with historical records (orders that reference a deleted menu item), or sync to other systems that need to learn about the deletion. For orders and money, often neither: use a status (cancelled) and keep the record forever.
Costs of soft delete: every query needs WHERE deleted_at IS NULL (forgetting it leaks deleted data; enforce it in the repository or with a SQLAlchemy global criteria); unique constraints break (a deleted "biryani" blocks creating a new "biryani") unless you use a partial unique index over live rows; tables grow; and privacy rules still apply to soft-deleted personal data.
API design: DELETE /v1/menu-items/{id} returns 204 (idempotent: a second delete returns 404 or 204, documented), and a deleted resource returns 404 (or 410 Gone).
Picture it A soft-deleted row blocking a re-creation, then the same flow with a partial unique index.
The setup: SQLite supports partial indexes like PostgreSQL does. The first index covers all rows; the second only live ones.
from sqlalchemy import create_engine, text
from sqlalchemy.exc import IntegrityError
engine = create_engine("sqlite://")
with engine.begin() as c:
c.execute(text("create table menu_items (id integer primary key, restaurant_id int, name text, deleted_at text)"))
c.execute(text("create unique index uq_item on menu_items(restaurant_id, name)")) # naive unique
c.execute(text("insert into menu_items values (1, 3, 'biryani', null)"))
c.execute(text("update menu_items set deleted_at = '2026-11-24' where id = 1")) # soft delete
try: c.execute(text("insert into menu_items values (2, 3, 'biryani', null)"))
except IntegrityError: print("naive unique index: re-creating a soft-deleted name FAILS")
with engine.begin() as c:
c.execute(text("drop index uq_item"))
c.execute(text("create unique index uq_item_live on menu_items(restaurant_id, name) where deleted_at is null")) # partial index
c.execute(text("insert into menu_items values (2, 3, 'biryani', null)"))
print("partial unique index: re-creating works; live rows:", c.execute(text("select id from menu_items where deleted_at is null")).scalars().all(),
"| all rows:", c.execute(text("select count(*) from menu_items")).scalar())Make the invisible visible: Run it.
naive unique index: re-creating a soft-deleted name FAILS
partial unique index: re-creating works; live rows: [2] | all rows: 2What you see: With a normal unique index, re-creating a soft-deleted name failed. With a unique index limited to rows WHERE deleted_at IS NULL, the new row was accepted, and the table held two rows with one of them live.
Why: The deleted row still exists, so the database still sees it. The partial index tells the database to enforce uniqueness only among live rows.
Hard delete
The row is gone.
DELETE FROM menu_items WHERE id = 1;
-- no undo, no audit, no clashSoft delete
The row is marked.
UPDATE menu_items SET deleted_at = now()
WHERE id = 1;
-- every query: WHERE deleted_at IS NULLThe shift: Soft delete keeps history at the price of a filter on every query and care with uniqueness.
Land it I hard-delete when data has no future value or must be erased, soft-delete when undo or audit needs it with a partial unique index, and model orders with statuses instead of deletes.
- "How do I make sure nobody forgets the filter?"
-
Put the filter in exactly one place and make bypassing it hard, then prove it with tests.
- One entry point: every read goes through the repository's base query, which already includes
deleted_at IS NULL. There is no public method that builds a menu-item query any other way. - Or a global filter: SQLAlchemy's
with_loader_criteria, attached to the session, adds the condition to every ORM select for that class automatically, including in joins and relationship loads. - A test: soft-delete an item, then call the list and get endpoints and a search endpoint and assert that it is absent. Add the same check for any new route.
The global filter is stronger, but it can surprise people, such as an admin screen that needs deleted rows. I give that screen a named method that explicitly opts out. The goal is that leaking deleted data requires a deliberate line of code, not a forgotten one.
- One entry point: every read goes through the repository's base query, which already includes
- "What about GDPR and erasure?"
-
Soft delete is not erasure. Under privacy law such as GDPR, a person can ask you to erase their personal data, and a row that is merely marked deleted still holds the name, email and address.
What I do is separate personal data from business facts. For a customer erasure I run a job that overwrites the personal fields, for instance name to "deleted user", email to a random placeholder, phone and address to null, and keeps the order rows with their totals and dates, because the restaurant and the tax office still need those. Those rows are now anonymous rather than personal.
Three details matter. The job must reach every copy, which means search indexes, caches and exports. Backups age out on their own schedule, so I write that schedule down and tell the requester. And I record that the erasure happened, without recording the data.
I also document retention periods up front, so the answer to "how long do you keep it" already exists.
- "404 or 410 for a deleted resource?"
-
I use 404, and I would accept 410 where it adds value. Both are defensible; the thing that hurts is mixing them.
404 Not Found says nothing about history. It is the simplest answer, it matches what the API says for an id that never existed, and it avoids revealing that something was once there. That is also why it pairs well with ownership checks, where leaking existence is a risk.
410 Gone says "this existed and was removed on purpose, do not ask again". That is useful to crawlers, which stop re-requesting the URL, and to sync clients that need to tell "deleted" from "never heard of it" so they can remove their local copy.
For QuickBite I would use 404 for orders, and 410 for public menu items that mobile apps cache offline. Either way, the choice goes into the API documentation and into the Problem Details
type, so clients can rely on it. - "Is DELETE idempotent?"
-
Yes, in the HTTP sense. Idempotent means that repeating the request leaves the server in the same state as sending it once. After one DELETE or ten, the resource is gone. The response is allowed to differ.
The usual behaviour is 204 on the first call and 404 on the second, because the resource no longer exists to be deleted. That is correct and many APIs do it. The trap is a client that treats the 404 as a failure and retries forever or shows an error after a network retry that really did succeed the first time.
Some APIs return 204 both times so that retries are trivial. That is friendlier to clients, at the cost of not telling a caller that the id was wrong from the start.
My choice for mobile-facing endpoints is 204 both times when the id was valid for this caller. I document it, and I tell clients to treat 404 on a retried DELETE as success. Q110 covers retries in general.
Q80 · Design. "Design QuickBite's order-creation flow: validation, stock, payment, idempotency and the event."
Reveal answer
Strong answer The flow, in order, with the reason for each step. 1 Validate: Pydantic checks shape (lines 1 to 50, qty limits, discriminated payment, address). 2 Authenticate and authorise: token validated, orders:write scope, customer id from the token, never from the body. 3 Idempotency: look up the Idempotency-Key (customer-scoped); replay on the same hash, 422 on a different hash. 4 Price: the server loads prices and computes total_cents; client prices are ignored.
5 Payment authorisation (external, slow): call the provider with a timeout, passing the idempotency key, before opening the database transaction, so no connection is held during the call. 6 One transaction: conditional stock decrements in a fixed item order, insert order and lines (captured prices), insert the idempotency record, insert the outbox event.
Any failure (409 out of stock) rolls everything back, and a compensating step voids the authorisation. 7 Respond: 201 with Location and OrderOut. 8 After commit: the relay publishes orders.created; consumers (kitchen, notifications) are idempotent.
Failure policy: validation 422; business conflict 409 with a Problem body; payment declined 402 or 409; dependency timeout 503 with Retry-After; unknown errors 500 with a request id. Observability: request id on every log line, spans around payment and DB, a metric for orders created and failures by reason.
Capturing payment before stock would charge for unavailable food; reserving stock before payment risks holding stock for failed payments. The order above authorises first and decrements inside one transaction, then captures later (on acceptance), which is the common compromise.
Picture it The whole flow, compact and runnable on SQLite: idempotent replay, price lookup, a payment step outside the transaction, atomic stock, order, idempotency record and outbox in one commit.
The setup: Two items with stock 2 and 1. The payment stub declines totals above 1,000 cents.
import hashlib, json
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
with engine.begin() as c:
for ddl in ("create table menu_items (id integer primary key, stock integer, price_cents integer)",
"create table orders (id integer primary key autoincrement, customer_id int, total_cents int, status text, payment_ref text)",
"create table idempotency_keys (key text primary key, request_hash text, response_json text)",
"create table outbox (id integer primary key autoincrement, topic text, payload text)",
"insert into menu_items values (1, 2, 300), (2, 1, 150)"): c.execute(text(ddl))
class OutOfStock(Exception): ...
class PaymentDeclined(Exception): ...
def authorize(customer_id, cents): # external call: done BEFORE the transaction, with a timeout in real life
if cents > 1000: raise PaymentDeclined()
return f"pay_{customer_id}_{cents}"
def create_order(customer_id, key, lines): # lines = [(item_id, qty)]
h = hashlib.sha256(json.dumps(lines).encode()).hexdigest()
with Session(engine) as s: # 1. idempotency lookup
row = s.execute(text("select request_hash, response_json from idempotency_keys where key=:k"), {"k": key}).first()
if row: return json.loads(row.response_json), "replayed"
total = sum(s.execute(text("select price_cents from menu_items where id=:i"), {"i": i}).scalar() * q for i, q in lines) # 2. server computes price
ref = authorize(customer_id, total) # 3. payment authorisation, no DB connection held
with Session(engine) as s, s.begin(): # 4. one transaction: stock, order, key, event
for i, q in sorted(lines):
if s.execute(text("update menu_items set stock = stock - :q where id=:i and stock >= :q"), {"q": q, "i": i}).rowcount == 0:
raise OutOfStock(i) # rolls everything back; a real system also voids the authorisation
oid = s.execute(text("insert into orders(customer_id,total_cents,status,payment_ref) values (:c,:t,'placed',:p)"), {"c": customer_id, "t": total, "p": ref}).lastrowid
out = {"id": oid, "total_cents": total, "status": "placed"}
s.execute(text("insert into idempotency_keys values (:k,:h,:r)"), {"k": key, "h": h, "r": json.dumps(out)})
s.execute(text("insert into outbox(topic,payload) values ('orders.created', :p)"), {"p": json.dumps(out)})
return out, "created"
print(create_order(7, "k1", [(1, 1), (2, 1)]))
print(create_order(7, "k1", [(1, 1), (2, 1)])) # retry with the same key
for label, args in (("sold out", (8, "k2", [(2, 1)])), ("declined", (8, "k3", [(1, 4)]))):
try: create_order(*args)
except (OutOfStock, PaymentDeclined) as e: print(label, "->", type(e).__name__)
with engine.connect() as c:
print("stock:", c.execute(text("select id, stock from menu_items")).all(), "| orders:", c.execute(text("select count(*) from orders")).scalar(), "| outbox events:", c.execute(text("select count(*) from outbox")).scalar())Make the invisible visible: Run it.
({'id': 1, 'total_cents': 450, 'status': 'placed'}, 'created')
({'id': 1, 'total_cents': 450, 'status': 'placed'}, 'replayed')
sold out -> OutOfStock
declined -> PaymentDeclined
stock: [(1, 1), (2, 0)] | orders: 1 | outbox events: 1What you see: The first call created order 1 (450 cents). The retry with the same key returned the same order as a replay. A sold-out item raised OutOfStock and a too-large total raised PaymentDeclined. At the end: one order, one outbox event, and stock decremented only for the successful order.
Why: Every step has one job and one failure mode. The one transaction at step 6 is the only place where several tables must change together.
Naive
Everything inline, in order.
charge(card, total) # ❌ before stock
db.add(order); db.commit()
kafka.send(event) # ❌ dual writeCorrect
Idempotent, atomic, evented.
ref = authorize(total, key) # outside the tx
with s.begin():
reserve(); add(order); add(outbox)The shift: Slow external steps happen outside the transaction; every database effect and the event happen inside one.
Land it I would validate, authorise, check the idempotency key, price on the server, authorise payment outside the transaction, then commit stock, order, key and outbox event together and publish afterwards.
- "What if the payment is authorised but the transaction fails?"
-
Void the authorisation, and also run a safety net that does not depend on that void succeeding.
The direct fix is an
exceptpath. If the transaction fails after payment was authorised, the code immediately calls the provider's void endpoint, passing the same idempotency key so a repeated void does nothing extra. If the process crashes at that exact moment, the except path never runs, so I need the second layer.The safety net is a reconciliation job. Every few minutes it lists authorisations older than, say, ten minutes, uses the stored idempotency key as the reference, checks whether an order exists for it, and voids the ones with no order. Providers also expire unused authorisations on their own, after days, which is the last line of defence.
Both the void and the job must be idempotent: voiding an already voided authorisation returns success. A customer then sees at worst a temporary hold on their card, never a charge.
- "Why authorise before the transaction instead of inside it?"
-
Because a database transaction is a scarce resource and an external call is slow and unpredictable.
Work it out with numbers. Say the payment provider answers in 1.5 seconds. If the call sits inside the transaction, each order holds a pooled connection, plus row locks on stock, for 1.5 seconds.
With a pool of 10 connections, only about 10 / 1.5 = 6 to 7 orders per second can be processed at all, and every other query in the app waits in the pool queue. If the provider has a bad day and answers in 10 seconds, the pool is exhausted in seconds and unrelated endpoints, such as reading a menu, start timing out.
Locks make it worse: another customer ordering the same dish waits for the first customer's payment call.
Authorising first has one cost. If the transaction then fails, for example out of stock, I must void. A void is a cheap, idempotent call, and it happens rarely compared to successful orders. The trade is clearly worth it.
- "How do I handle the restaurant rejecting the order later?"
-
Treat it as a normal state change that triggers money movement through the same outbox pattern, not as a special case in the request path.
- Transition: the restaurant calls
PATCH /v1/orders/{id}with statusrejected. The service checks the move is legal (placed to rejected) and writes the new status. - Event: in the same transaction it inserts an
orders.rejectedoutbox event. Either both are stored or neither is. - Refund: a payment consumer reads the event, voids the authorisation if it was never captured, or refunds it if it was, using the order id as the idempotency key.
This design means a crash between the status change and the refund cannot lose the refund, because the event is already stored and the relay retries until delivered. Notifications to the customer ("the restaurant could not accept your order") are another consumer of the same event.
- Transition: the restaurant calls
- "What would I add for scale?"
-
I would only add things I had measured a need for, and I would say that out loud first. If an interviewer wants a list, this is my order.
- Reads first: cursor pagination and short-lived caching of menus. Reads outnumber orders by far.
- A queue after acceptance: the order endpoint stores the order and publishes an event, and kitchen routing consumes it at its own pace, so a slow restaurant system cannot slow order creation.
- Hot stock rows: if one popular dish becomes a lock bottleneck, split its stock into several counters (shards) and sum them, or reserve in Redis then reconcile.
- Load tests: including bursts of duplicate idempotency keys and a slow payment provider, because those are the failures that matter.
Each addition costs operational complexity, so each needs a number behind it, such as p99 latency or pool wait time.
10 · DrillSecurity, Errors and API Behaviour — Q81–Q115
These thirty-five questions cover what separates a working API from one you can safely put on the internet: who is calling, what they may touch, what the client sees when something fails, and how HTTP itself is meant to be used. Senior rounds treat these as judgement questions. They want to hear the specific check, the specific status code and the specific header, not a general promise to be secure.
Every answer is written to be said aloud. Say yours first, then reveal. All code ran on FastAPI 0.141.1, Pydantic 2.13, PyJWT 2.14 and Python 3.12; the scripts are in code/e20-python-api/E/. The running example is the QuickBite orders API from section 06.
These questions test whether you separate three jobs that beginners blur together: proving who the caller is, deciding what they may do, and keeping the browser from being turned against its own user.
Q81. "OAuth2 password flow or validating tokens from an identity provider — which do you implement, and why?"
Reveal answer
The real test Whether you say "my API only validates tokens; a dedicated identity provider issues them" and can name the one case where the password flow is acceptable.
Strong answer There are two different jobs hiding in the word "auth". Issuing tokens means checking passwords, handling reset flows, multi-factor prompts, social login and refresh tokens. Validating tokens means checking a signature and a few claims on every request.
An API should do only the second job. Issuing is a product in itself, and every piece of it (password hashing, rate limiting login attempts, breach detection, MFA) is a place to get security wrong. Keycloak, Auth0, Cognito or Entra already do it and are audited for it.
So in QuickBite the API is a resource server: it receives Authorization: Bearer ..., verifies the token against the identity provider's public keys, and trusts the claims inside. FastAPI's OAuth2PasswordBearer only reads the header and adds a login box to /docs. It does not check anything.
The password flow shown in the FastAPI tutorial is acceptable for a prototype, an internal tool with one fixed user table, or a test environment where you want a token without an identity provider. It is also deprecated in the current OAuth 2.0 security guidance, because the app sees the user's password.
Picture it The two dependencies look the same in code, but they put different things into the OpenAPI document that every client reads.
The setup: A tiny app with one endpoint behind each dependency. We print the security scheme FastAPI generates.
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBearer, OAuth2PasswordBearer
app = FastAPI()
password_flow = OAuth2PasswordBearer(tokenUrl="/token") # teaching example: docs login box
bearer_only = HTTPBearer() # production: just validate tokens
@app.get("/a")
def a(token: str = Depends(password_flow)): return {"token_len": len(token)}
@app.get("/b")
def b(creds=Depends(bearer_only)): return {"scheme": creds.scheme}
schemes = app.openapi()["components"]["securitySchemes"]
for name, s in schemes.items():
print(name, "->", s)
print("paths:", sorted(app.openapi()["paths"]))Make the invisible visible: What the generated contract says.
OAuth2PasswordBearer -> {'type': 'oauth2', 'flows': {'password': {'scopes': {}, 'tokenUrl': '/token'}}}
HTTPBearer -> {'type': 'http', 'scheme': 'bearer'}
paths: ['/a', '/b']What you see: OAuth2PasswordBearer advertises a password flow with a tokenUrl, so Swagger UI shows a username and password form that posts to your own /token. HTTPBearer advertises only "send a bearer token", which is all a resource server should claim.
Password flow in your API
Your service owns user passwords and mints tokens itself.
@app.post("/token")
def login(form: OAuth2PasswordRequestForm):
user = db.find(form.username)
if not verify(form.password, user.hash):
raise HTTPException(400)
return {"access_token": make_jwt(user)}Validate only
The identity provider mints tokens; the API only checks them.
bearer = HTTPBearer()
def current_user(creds = Depends(bearer)):
claims = verify_token(creds.credentials)
return User.from_claims(claims)The shift: Stop being the login system and become a checker of tokens somebody else signed.
Land it I implement token validation in the API and leave token issuing to an identity provider; the password flow is for demos and tests only.
- "So when would you build your own token endpoint?"
-
Only when there is no identity provider and the cost of adding one is higher than the risk, such as a small internal tool for a dozen people. Even then I build it with open eyes.
The minimum bar is this. Passwords are hashed with a slow algorithm, Argon2 or bcrypt, never plain SHA-256. Login attempts are rate limited per account and per IP. Tokens are short-lived, five to fifteen minutes. And the login response never says whether the username or the password was wrong.
I would also keep the boundary clean. All token validation sits in one dependency,
get_current_user, that reads a key source from settings. Endpoints depend on that and nothing else.That design pays off later. When the company adopts Keycloak or Entra, I replace the key source with the provider's published public keys and delete the login endpoint. No route changes, because routes only ever saw a validated
User. - "What does the API need from the identity provider to validate tokens?"
-
Three things, all public information. The API never needs a secret from the provider to check a token.
- Issuer: the exact
issstring the provider puts in tokens, for example a URL for a Keycloak realm. I compare it for equality. - Audience: the identifier registered for my API, which must appear in
aud. This stops a token minted for another service being replayed here. - Public keys: a JWKS (JSON Web Key Set) document published at a well-known URL, normally listed in the provider's discovery document.
PyJWT's
PyJWKClientdownloads the JWKS, caches it, and picks the right key using the token'skidheader.The nice consequence is rotation without a deploy. The provider adds a new key, new tokens carry the new
kid, my client misses its cache, refetches once, and carries on. I still keep the algorithm allow-list in my own settings, never taken from the token. - Issuer: the exact
- "What do the other flows look like for QuickBite?"
-
Each client type gets the flow built for it, and the API stays the same in all of them.
The mobile app and the browser app are public clients, which cannot keep a secret. They use the authorization code flow with PKCE. The user logs in on the provider's own page, the app gets a short one-time code, and it swaps that for tokens. PKCE adds a random proof the app created at the start, so a stolen code is useless to anyone else.
Services such as rider dispatch calling the orders API have no user. They use the client credentials flow: the service sends its own id and secret (or a signed assertion) to the provider and gets a token whose
subis the service itself.From the orders API's point of view nothing changes. It sees a bearer token with
iss,aud,subandscope, validates it the same way, and runs the same scope checks. That is the benefit of being a pure resource server. - "Is a JWT the only token format?"
-
No. There are two common formats and the choice is a trade between speed and revocation.
A JWT is self-contained: the claims and signature are inside, so the API validates it locally in microseconds with no network call. The cost is that I cannot cancel it before
exp. If a rider is fired at 10:00 and the token lives until 10:12, it works for twelve more minutes unless I add extra machinery.An opaque token is just a random string. The API sends it to the provider's introspection endpoint, which answers "active: true, sub, scope" or "active: false". Revocation is instant, but every request costs a network round trip, so I cache the answer for a few seconds, which softens revocation slightly.
My default for a high-volume customer API is short-lived JWTs of five to fifteen minutes with revocable refresh tokens. I switch to opaque tokens, or add a small deny-list, where instant revocation matters more than latency, for example admin tools.
Q82. "How do you validate a JWT correctly? List every check."
Reveal answer
Strong answer A JWT is three base64 parts: header, claims, signature. Anyone can read the first two. The signature is the only thing that says the issuer wrote them, so validation is a list of checks, and skipping any one of them opens a hole.
- Parse the header safely: read
algandkidfrom the header only to pick a key. Never usealgto decide how to verify. - Algorithm allow-list: pass
algorithms=["RS256"]from your own configuration. A token that says anything else is rejected. - Signature: verify it with the key found by
kid(JWKS) or the configured public key. - Expiry and not-before:
expmust be in the future andnbf, if present, in the past. Allow a few seconds of clock leeway, not minutes. - Issuer:
issequals the identity provider you trust. - Audience:
audcontains your API's identifier, so a token minted for another service cannot be replayed against yours. - Required claims: insist that
exp,iss,audandsubexist. Withoutrequire, a token with noexpnever expires. - Scopes and roles: after the token is valid, check that it grants what this endpoint needs. That is authorisation, not validation, and it returns 403, not 401.
Any failure of the first seven returns 401 with a WWW-Authenticate: Bearer header, and the log records the reason, never the token.
Picture it One RS256 key pair, one valid token and seven broken ones, each broken in exactly one way. The exception names are what your logs and tests will show.
The setup: A generated 2048-bit RSA key. The verifier is the same function every time; only the token changes.
import time, jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization as ser
def keypair():
k = rsa.generate_private_key(public_exponent=65537, key_size=2048)
return (k.private_bytes(ser.Encoding.PEM, ser.PrivateFormat.PKCS8, ser.NoEncryption()),
k.public_key().public_bytes(ser.Encoding.PEM, ser.PublicFormat.SubjectPublicKeyInfo))
priv, pub = keypair()
other_priv, _ = keypair()
ISS, AUD, now = "https://id.quickbite.example", "quickbite-api", int(time.time())
good = {"sub": "7", "iss": ISS, "aud": AUD, "iat": now, "exp": now + 300}
def verify(token):
return jwt.decode(token, pub, algorithms=["RS256"], audience=AUD, issuer=ISS,
options={"require": ["exp", "iss", "aud", "sub"]})
def sign(claims, key=priv): return jwt.encode(claims, key, algorithm="RS256", headers={"kid": "k1"})
cases = {
"valid": sign(good),
"expired": sign({**good, "exp": now - 60}),
"not yet valid": sign({**good, "nbf": now + 600}),
"wrong audience": sign({**good, "aud": "other-api"}),
"wrong issuer": sign({**good, "iss": "https://evil.example"}),
"no exp claim": sign({k: v for k, v in good.items() if k != "exp"}),
"wrong signing key": sign(good, other_priv),
"garbage": "not.a.jwt",
}
for name, tok in cases.items():
try:
verify(tok); print(f"{name:18} -> accepted (sub={verify(tok)['sub']})")
except jwt.PyJWTError as e:
print(f"{name:18} -> {type(e).__name__}: {e}")Make the invisible visible: The real result of running it.
valid -> accepted (sub=7)
expired -> ExpiredSignatureError: Signature has expired
not yet valid -> ImmatureSignatureError: The token is not yet valid (nbf)
wrong audience -> InvalidAudienceError: Audience doesn't match
wrong issuer -> InvalidIssuerError: Invalid issuer
no exp claim -> MissingRequiredClaimError: Token is missing the "exp" claim
wrong signing key -> InvalidSignatureError: Signature verification failed
garbage -> DecodeError: Invalid header paddingWhy: Each check maps to a distinct exception class, and all inherit from jwt.PyJWTError. One except jwt.PyJWTError in the dependency turns every one of them into a 401, and nothing can slip through as an uncaught 500.
Spring Security resource server
Properties tell the decoder what to check.
spring.security.oauth2.resourceserver.jwt:
issuer-uri: https://id.example.com
audiences: quickbite-apiPyJWT decode
You spell the same checks in one call.
jwt.decode(token, key,
algorithms=["RS256"],
audience="quickbite-api",
issuer="https://id.example.com",
options={"require": ["exp", "iss"]})The shift: Spring hides the checks behind configuration; in Python you write them, so you must remember every one.
Land it I check the algorithm against an allow-list, then signature, exp, nbf, iss, aud and required claims, and only then look at scopes.
- "Why pass
requirewhenexpis checked automatically?" -
Because PyJWT only checks a claim if it is present. A token with no
expat all has nothing to check, so it passes and never expires. That makes a missing claim a silent hole rather than an error.The
requireoption closes it. Withoptions={"require": ["exp", "iss", "aud", "sub"]}, a token lacking any of them raisesMissingRequiredClaimErrorbefore the other checks matter. The "no exp claim" case in the output above fails for exactly this reason, and only because we asked.The same logic holds for
audandiss. If a token carries no audience, and you pass an audience to compare, PyJWT does raise, but I would not rely on remembering every library rule. Writing the required list in one place documents the contract: this API refuses tokens without these four claims.The principle is to fail closed. A security check that passes when its input is missing is a bug waiting for a forged token to find it.
- "How much clock leeway is reasonable?"
-
Five to thirty seconds is plenty. I use 5, as the canonical app does, passed as
leeway=5tojwt.decode.The purpose of leeway is to forgive small differences between the identity provider's clock and mine. When both machines sync with NTP, that difference is milliseconds, and a few seconds covers an unlucky token that arrives just as it expires on one side.
Large leeway is quietly harmful. Ten minutes of leeway turns a 5-minute token into a 15-minute one, which is three times the exposure window after a leak, and nobody notices because nothing fails.
If tokens are rejected in production for "not yet valid", I do not raise the leeway first. I fix the clock, since a drifting server has other problems too, such as wrong log timestamps and failing TLS checks. Leeway is a bandage for jitter, not for broken time sync.
- "How do you avoid fetching the key set on every request?"
-
By creating one key client for the whole process and letting it cache.
PyJWKClient(url, cache_keys=True, lifespan=3600)keeps fetched keys for an hour, so most requests need no network call at all.Where it is created matters more than the settings. A client built inside the dependency would be new on every request, with an empty cache, so every call would hit the provider. I make it once, either in an
lru_cachefunction or in the lifespan handler, and reuse it.There is also an abuse case. When a token has an unknown
kid, the client refetches the key set, because the provider may have rotated. An attacker can send tokens with randomkidvalues, one refetch each, and make my API hammer the provider.So I limit refetches, for example one per minute at most, and answer 401 for unknown
kidvalues in between. A cached negative result is fine. - "What do you log when a token is rejected?"
-
Only things that help me investigate and nothing that could be replayed. For a rejected token I log the exception class name, the
kidand the request id.The exception class tells me the reason:
ExpiredSignatureErrormeans a client with a stale token,InvalidAudienceErrormeans a misconfigured caller,InvalidSignatureErrormeans something suspicious. Thekidshows whether the caller used a key I know. The request id lets me follow the request across logs.I never log the token. Until it expires, a token is a working password, and logs are read by far more people and systems than the database is. The canonical
security.pylogsreason=ExpiredSignatureErrorand nothing more.Also avoid logging the exception's message text, since some library messages include claim values. I log them at warning level, and alert on a burst: a sudden jump in invalid signatures is worth a page, while a trickle of expired tokens is normal.
Q83 · Scenario. "Tokens signed with alg: none, or HS256 with the public key, were accepted. Explain the bug and fix it."
Reveal answer
The real test Whether you know that the attacker controls the header, so the server must never let the header choose the algorithm.
Strong answer A JWT header carries "alg". Two famous attacks abuse a server that believes it. In the first, the attacker sets alg to none, which means "unsigned", and sends an empty signature. A library that obeys the header skips verification.
In the second, called algorithm confusion, the server expects RS256 and holds the RSA public key, which anyone can download. The attacker signs a token with HS256 using those public-key bytes as the shared secret. A server that lets the header choose HS256 then verifies the HMAC with the same bytes and accepts the forgery.
Both bugs have one root: the verifier took the algorithm from the untrusted token. The fix is to take it from your own configuration: algorithms=["RS256"]. A token that claims anything else is rejected before any signature maths runs.
Modern PyJWT adds a second wall. It refuses to use a PEM public key as an HMAC secret, which is why the hand-built forgery below fails even in the naive code. Do not lean on that. The real incident in our story was a line that skipped verification altogether, and that accepts every forged token.
Picture it We build both forged tokens by hand (PyJWT itself refuses to create the HS256 one), then try three verifiers.
The setup: A real RSA key. none_tok has an empty signature. hs_tok is an HMAC-SHA256 over the public-key PEM.
import base64, hashlib, hmac, json, time, jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization as ser
k = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pub = k.public_key().public_bytes(ser.Encoding.PEM, ser.PublicFormat.SubjectPublicKeyInfo)
b64 = lambda b: base64.urlsafe_b64encode(b).rstrip(b"=").decode()
claims = {"sub": "1", "role": "admin", "exp": int(time.time()) + 300}
# forged token 1: header says alg none, no signature at all
none_tok = b64(b'{"alg":"none","typ":"JWT"}') + "." + b64(json.dumps(claims).encode()) + "."
# forged token 2: HS256, "secret" = the PUBLIC key bytes (which everybody can download)
head = b64(b'{"alg":"HS256","typ":"JWT"}'); body = b64(json.dumps(claims).encode())
sig = hmac.new(pub, f"{head}.{body}".encode(), hashlib.sha256).digest()
hs_tok = f"{head}.{body}.{b64(sig)}"
print("--- naive 1: verify_signature=False (the 'temporary' line) ---")
for name, t in [("alg none", none_tok), ("HS256+pubkey", hs_tok)]:
print(f"{name:13} -> role={jwt.decode(t, options={'verify_signature': False})['role']}")
print("--- naive 2: algorithm taken from the token header, PyJWT 2.14 ---")
for name, t in [("alg none", none_tok), ("HS256+pubkey", hs_tok)]:
alg = jwt.get_unverified_header(t)["alg"] # ❌ TRAP: the attacker chooses the algorithm
try:
print(f"{name:13} -> role={jwt.decode(t, None if alg == 'none' else pub, algorithms=[alg])['role']}")
except Exception as e:
print(f"{name:13} -> {type(e).__name__}: {e}")
print("--- fixed: allow-list from OUR config ---")
for name, t in [("alg none", none_tok), ("HS256+pubkey", hs_tok)]:
try:
jwt.decode(t, pub, algorithms=["RS256"]); print(name, "accepted")
except jwt.PyJWTError as e:
print(f"{name:13} -> {type(e).__name__}: {e}")Make the invisible visible: Naive code against the allow-list fix.
--- naive 1: verify_signature=False (the 'temporary' line) ---
alg none -> role=admin
HS256+pubkey -> role=admin
--- naive 2: algorithm taken from the token header, PyJWT 2.14 ---
alg none -> InvalidSignatureError: Signature verification failed
HS256+pubkey -> InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.
--- fixed: allow-list from OUR config ---
alg none -> InvalidAlgorithmError: The specified alg value is not allowed
HS256+pubkey -> InvalidAlgorithmError: The specified alg value is not allowedWhat you see: With verify_signature=False both forgeries become role=admin. Letting the header pick the algorithm is stopped by PyJWT 2.14, but only by a built-in guard. The allow-list rejects both with InvalidAlgorithmError before looking at a signature.
Naive: header decides
The attacker picks the algorithm.
alg = jwt.get_unverified_header(t)["alg"]
# ❌ TRAP: attacker-controlled
jwt.decode(t, key, algorithms=[alg])
# or the "temporary" shortcut:
jwt.decode(t, options={
"verify_signature": False})Correct: config decides
One algorithm, from your settings.
ALGS = settings.jwt_algorithms()
# ✅ from our config, ["RS256"]
jwt.decode(t, key,
algorithms=ALGS,
audience=AUD, issuer=ISS,
options={"require": ["exp"]})The shift: Trust the key you configured, never the algorithm the token announces.
Land it The fix is an algorithm allow-list from my own settings, plus a test that sends an alg-none token and an HS256-with-public-key token and expects 401.
- "How do I stop this from coming back?"
-
Turn the two attacks into permanent tests, then add review rules that catch the cause rather than the symptom.
- Regression tests: keep the forged tokens as test cases (the script above is the template): one with
alg: none, one HS256 signed with the public key bytes, one expired, one with the wrong audience. Each must return 401. The day someone "simplifies" the decode call, the build fails. - Search rules: grep for
verify_signature,verify=Falseandalgorithms=taken from a variable that comes from the token. Make hits a mandatory review comment. - Single door: only one function in the code base may decode tokens, so there is one place to inspect.
I treat any
options=dictionary that turns checks off as a red flag in review. Skipping verification in a debug path is how this incident started, and debug paths ship. - Regression tests: keep the forged tokens as test cases (the script above is the template): one with
- "Why is RS256 preferred to HS256 for an API?"
-
Because of who can forge. HS256 is symmetric: the same secret signs and verifies. So every service that can check a token can also create one. With five APIs sharing the secret, a leak from the weakest of them lets an attacker mint a valid admin token for all five.
RS256 is asymmetric. The identity provider holds the private key and signs. Each API holds only the public key, which is useless for signing. If one API is breached, the attacker learns nothing that lets them issue tokens.
There is a second benefit, which is operational. Public keys can be published openly at a JWKS URL, so rotation needs no secret distribution. Sharing an HS256 secret across teams needs a secure channel and a coordinated change.
HS256 still has a place. Inside one trusted service that both signs and verifies its own tokens, and in tests where a shared secret is convenient, it is fine and slightly faster. For anything crossing a service boundary I choose RS256 or ES256.
- "Is
alg: noneever legitimate?" -
The JWT specification defines it, for contexts where integrity is guaranteed some other way, such as a token carried inside an already signed envelope. For an API bearer token that is never the case. Nothing else vouches for the token, so unsigned means forgeable.
The practical consequence is simple. Because
noneis not in my allow-list,algorithms=["RS256"], a token that saysnoneis rejected before any signature maths. I do not need extra code that looks for the string.The real danger was never the existence of
none. It was libraries that, in the past, trusted the token's header to choose the algorithm, so an attacker could picknoneand skip verification. Current libraries refuse it by default, but my own configuration should still say which algorithms are allowed rather than depending on a default. - "What about the
kidheader, can it be abused too?" -
Yes, and it is an old class of bug. The
kidheader comes from the sender, so it is untrusted input like any other field, and it should never be pasted into anything that interprets it.Examples that have gone wrong in real systems: a server that builds a file path from
kidto read the key, which allows path traversal such as../../dev/null(an empty file as the "key"); and a server that putskidinto a SQL query to look up a key, which allows SQL injection.The safe pattern is a dictionary lookup. At startup, or when refreshing the JWKS, I load the known keys into a map from
kidto key. A token'skidis only ever used as the map key. If it is not there, I refetch once under the rate limit described earlier, and otherwise answer 401.No file paths, no queries, no string building. Treat the header as a lookup label, never as a command.
Q84. "How do you implement get_current_user and role or scope checks as dependencies?"
Reveal answer
Strong answer Build authentication and authorisation as two layers of dependency. get_current_user reads the bearer header, validates the token and returns a small frozen User object. It answers "who is calling?" and raises 401 when it cannot.
require_scope("orders:write") is a factory: a function that returns a dependency. That dependency depends on get_current_user, checks the scope and raises 403. It answers "may this caller do this?".
An endpoint declares what it needs in its signature, so the requirement is visible in the code, in the OpenAPI document and in the tests. Because FastAPI caches a dependency per request, get_current_user runs once even when three layers depend on it.
Keep roles out of endpoint bodies. A line like if user.role == "admin" inside fifty endpoints is fifty places to forget. Resource ownership ("is this your order?") is a third check and belongs in the service or repository, which Q91 covers.
Picture it A small app with the exact structure of the canonical app/security.py, driven through five requests.
The setup: HS256 with a test secret so the demo needs no key files. One endpoint needs orders:read, one needs orders:write.
from dataclasses import dataclass
from typing import Annotated
import jwt
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.testclient import TestClient
SECRET = "test-secret-at-least-32-bytes-long-ok"
bearer = HTTPBearer(auto_error=False)
@dataclass(frozen=True)
class User:
id: int; role: str; scopes: frozenset
def get_current_user(creds: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)]) -> User:
if creds is None:
raise HTTPException(401, "missing token", headers={"WWW-Authenticate": "Bearer"})
try:
c = jwt.decode(creds.credentials, SECRET, algorithms=["HS256"], options={"require": ["exp", "sub"]})
except jwt.PyJWTError:
raise HTTPException(401, "invalid token", headers={"WWW-Authenticate": "Bearer"})
return User(int(c["sub"]), c.get("role", "customer"), frozenset(c.get("scope", "").split()))
def require_scope(scope: str):
def check(user: Annotated[User, Depends(get_current_user)]) -> User:
if scope not in user.scopes:
raise HTTPException(403, f"missing scope {scope}")
return user
return check
app = FastAPI()
@app.get("/v1/orders")
def list_orders(user: Annotated[User, Depends(require_scope("orders:read"))]): return {"customer": user.id}
@app.patch("/v1/orders/1")
def patch(user: Annotated[User, Depends(require_scope("orders:write"))]): return {"ok": True}
def tok(scope, exp=9999999999): return jwt.encode({"sub": "7", "scope": scope, "exp": exp}, SECRET, "HS256")
c = TestClient(app)
for label, headers, path, m in [
("no header", {}, "/v1/orders", "get"),
("bad token", {"Authorization": "Bearer abc"}, "/v1/orders", "get"),
("read scope", {"Authorization": f"Bearer {tok('orders:read')}"}, "/v1/orders", "get"),
("read, PATCH", {"Authorization": f"Bearer {tok('orders:read')}"}, "/v1/orders/1", "patch"),
("write, PATCH", {"Authorization": f"Bearer {tok('orders:read orders:write')}"}, "/v1/orders/1", "patch")]:
r = getattr(c, m)(path, headers=headers)
print(f"{label:13} {m.upper():5} {path:14} -> {r.status_code} {r.json()} {r.headers.get('www-authenticate', '')}")Make the invisible visible: Five requests, five different outcomes.
no header GET /v1/orders -> 401 {'detail': 'missing token'} Bearer
bad token GET /v1/orders -> 401 {'detail': 'invalid token'} Bearer
read scope GET /v1/orders -> 200 {'customer': 7}
read, PATCH PATCH /v1/orders/1 -> 403 {'detail': 'missing scope orders:write'}
write, PATCH PATCH /v1/orders/1 -> 200 {'ok': True} Why: Missing or broken token gives 401 with WWW-Authenticate: Bearer. A good token without the scope gives 403, because the caller is known but not allowed. Mixing those up makes clients retry a login that can never help.
Spring Boot
Method security reads an annotation.
// illustrative
@PreAuthorize("hasAuthority('SCOPE_orders:write')")
@PatchMapping("/v1/orders/{id}")
Order patch(@PathVariable long id,
@RequestBody Patch p) { ... }FastAPI
The requirement is a parameter.
@router.patch("/{order_id}")
def patch(order_id: int,
user: Annotated[User, Depends(
require_scope("orders:write"))]):
...The shift: The rule moves from an annotation checked by a proxy to a parameter checked by the dependency graph.
Land it Authentication is one dependency that returns a User, authorisation is a factory that wraps it, and ownership lives in the service.
- "Why return 401 for a bad token but 403 for a missing scope?"
-
Because the two answers tell the client to do different things. 401 means "I do not know who you are", so the right reaction is to get a fresh token, which usually means logging in again. 403 means "I know exactly who you are, and the answer is no".
A client that gets 403 must not loop through the login screen. A new token would carry the same scopes, so the same request would fail again. It should show "you do not have permission" or ask the user to request access.
If I mixed them up, mobile apps would behave badly: logging users out when they hit a forbidden screen, or showing a permission message for an expired session.
With a 401 I also send
WWW-Authenticate: Bearer, as the output shows. The HTTP specification requires that header on a 401, and some clients and libraries use it to decide how to authenticate. A 403 does not need it, since authenticating again would not help. - "How would you check a role as well as a scope?"
-
I add a sibling factory in the same
security.py:require_role("admin"), built exactly likerequire_scope. It depends onget_current_userand raises 403 if the role is missing.My preference, though, is to check scopes inside the API and treat roles as coarse grouping at the identity provider. A scope names a capability, such as
orders:refund. A role such as "support agent" is a bundle of scopes that the provider expands into the token. Then the API checks one vocabulary and never needs a table of "which roles may refund".The reasoning is change. When policy says support agents may now also cancel orders, I change the role's bundle in the provider and the API needs no deploy. If endpoints hard-code
role == "support", every such change touches code in many places.I keep
require_rolefor the few cases that really are coarse, such as an admin-only router. - "What if a scope depends on the data, such as restaurant staff updating only their own restaurant's orders?"
-
That is a data-dependent rule, so a static scope cannot express it. A token cannot say "staff of restaurant 5 may update order 881", because it does not know that order 881 belongs to restaurant 5.
- Authenticate and check capability: the dependency requires
restaurant:orders:updateand returns aUsercarryingrestaurant_idfrom the token. - Load the resource: the service fetches the order.
- Compare: if
order.restaurant_id != user.restaurant_id, raise a domain error that maps to 404 (or 403 if existence is not secret).
The better form puts the owner filter in the repository query, so a foreign order is simply not found. I keep this logic in one function so that every route touching orders goes through it. Spread across routes, one forgotten check is a data leak (Q91).
- Authenticate and check capability: the dependency requires
- "How do you test it without real tokens?"
-
I use two kinds of tests, because they answer different questions.
For most tests auth is background noise, so I bypass it.
app.dependency_overrides[get_current_user] = lambda: User(id=1, role="customer", scopes=[...])makes the endpoint see a fake user and skips token parsing. These tests are fast and focus on business behaviour. The override is removed after each test by a fixture.For the security code itself I use real tokens. A token factory fixture signs JWTs with a test key pair, and settings point the app at the matching public key. A small group of tests sends tokens through the whole stack: valid, expired, wrong audience, wrong algorithm, missing scope, and expects 401 or 403 with the right headers.
Both are needed. Overrides alone mean the validation code is never exercised, and real tokens everywhere make every test slower and noisier. A handful of full-stack security tests plus overrides elsewhere is a good balance.
Q85. "Cookies and sessions versus bearer tokens for a browser app."
Reveal answer
Strong answer A browser can hold a credential in two places. A cookie is attached by the browser automatically to every request to that site. A bearer token is stored by your JavaScript (memory or storage) and attached by your code in an Authorization header.
Automatic attachment is the whole story. It makes cookies convenient, because no script touches the secret, and it makes them dangerous in one specific way: a malicious page can make the browser send your cookie to your API. That attack is CSRF, cross-site request forgery. A header the page's own script must add cannot be forged by another site, so bearer tokens are immune to CSRF.
Bearer tokens have the opposite weakness. If an attacker injects JavaScript into your page (XSS), the script can read a token from storage and send it away. A cookie marked HttpOnly cannot be read by script at all.
For a browser app served by the same company I prefer a server-side session in an HttpOnly, Secure, SameSite cookie, plus a CSRF token on state-changing requests. For mobile apps and service calls there is no browser, so bearer tokens are right.
Picture it The cookie flags decide most of the safety. Here is what a login response should set, and what a forged cross-site POST is stopped by.
The setup: A login endpoint sets the session cookie; the orders endpoint requires both the cookie and a CSRF header.
from fastapi import FastAPI, Response, Cookie, Header, HTTPException
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/login")
def login(resp: Response):
resp.set_cookie("session", "opaque-random-id", httponly=True, secure=True,
samesite="lax", max_age=3600, path="/")
return {"ok": True}
@app.post("/v1/orders")
def create(session: str | None = Cookie(None), x_csrf: str | None = Header(None)):
if session is None: raise HTTPException(401)
if x_csrf != "expected-csrf-token": # cookie-based auth needs a CSRF defence
raise HTTPException(403, "csrf check failed")
return {"created": True}
c = TestClient(app, base_url="https://testserver")
r = c.post("/login")
print("Set-Cookie:", r.headers["set-cookie"])
print("POST with cookie only ->", c.post("/v1/orders").status_code)
print("POST with cookie + token ->", c.post("/v1/orders", headers={"X-CSRF": "expected-csrf-token"}).status_code)Make the invisible visible: The real response header and two POSTs.
Set-Cookie: session=opaque-random-id; HttpOnly; Max-Age=3600; Path=/; SameSite=lax; Secure
POST with cookie only -> 403
POST with cookie + token -> 200Why: HttpOnly hides it from scripts, Secure keeps it off plain HTTP, SameSite=Lax stops the browser from sending it on most cross-site POSTs. The CSRF header is the second wall: another site cannot read your token to copy it into a header, so the second POST fails with 403.
Bearer in storage
Script holds the secret and adds the header.
// illustrative
const t = localStorage.getItem("jwt");
fetch("/v1/orders", {
headers: {Authorization: "Bearer " + t}
});
// ❌ XSS can read localStorageCookie session
Browser holds it; script cannot read it.
resp.set_cookie("session", sid,
httponly=True, secure=True,
samesite="lax", max_age=3600)
# ✅ XSS cannot read it
# needs a CSRF check on POSTThe shift: Choose which attack you would rather defend: stolen tokens through XSS, or forged requests through CSRF.
Land it For a browser app I use an HttpOnly Secure SameSite session cookie with a CSRF token, and keep bearer tokens for mobile and service-to-service calls.
- "Does SameSite=Lax make CSRF tokens unnecessary?"
-
It removes the most common attack but not every variant, so I keep a CSRF token as well. The reasons are specific.
SameSite=Laxtells the browser to withhold the cookie on cross-site sub-requests such as images, iframes and fetch calls, and on cross-site POST forms. But it still sends the cookie on top-level navigations that use safe methods, like clicking a link to your site. If any state-changing action works on GET, Lax does not protect it.It also covers "same site", not "same origin". A sibling subdomain such as
blog.quickbite.examplecounts as same site, so an XSS hole there can send authenticated requests to your API. And some older browsers ignore the attribute.My position is layers. Lax as a strong first wall, plus a CSRF token or a required custom header on every POST, PATCH, PUT and DELETE, plus an
Originheader check. Never allow state changes on GET. - "Where do you keep sessions if you run twenty pods?"
-
In a shared store such as Redis, never in process memory. With twenty pods behind a load balancer, a request can land on any of them, and a session held in one pod's memory is invisible to the other nineteen, so users would look logged out about 95 percent of the time.
The design is small. At login the server creates a random 128-bit id (
secrets.token_urlsafe(16)or longer), storessession:<id>in Redis with the user id and an expiry (TTL), and sets the cookie to the id alone. On each request, the dependency reads the cookie and looks the id up.The cookie carries no data, so nothing in it can be tampered with, and revocation is a single
DEL. Logging out a fired rider takes effect on their next request, which is something a JWT cannot do.The costs are one Redis call per request and Redis becoming a dependency. I run it replicated, and decide whether to fail closed when it is down (usually yes for sessions).
- "Can a single page app use a cookie against a different domain?"
-
Only with care, and I try to avoid the situation. A cross-domain cookie needs four settings to line up.
- Server CORS:
allow_credentials=Trueand the exact origin listed, since a wildcard is not allowed with credentials. - Browser code:
fetch(url, {credentials: "include"}), or the cookie is not sent. - Cookie attributes:
SameSite=None; Secure, because a different site means a cross-site request. - Third-party cookie rules: some browsers block or limit cross-site cookies regardless, so this can break for some users.
The cost is that
SameSite=Noneswitches off the browser's CSRF protection, so the CSRF token becomes mandatory.The simpler design is one site: serve the frontend at
app.quickbite.exampleand the API under/apion the same host through a gateway. Same origin means no CORS, a Lax or Strict cookie, and fewer ways to fail. - Server CORS:
- "What is the "backend for frontend" pattern?"
-
It is a small server-side component that sits between the browser and the APIs and keeps the OAuth tokens on the server. The browser gets only an HttpOnly session cookie. It never sees an access token or a refresh token.
The flow: the user logs in through the BFF, which runs the authorization code flow with the identity provider and stores the tokens in its session. When the browser calls
/api/orders, the BFF reads the session cookie, attaches the access token and forwards the call to the orders API. It also refreshes tokens when they expire.The security gain is that an XSS attack can still make requests as the user while the page is open, but cannot steal a token to use elsewhere, later, or from another machine. That is what current OAuth guidance for browser apps recommends when protection must be strong.
The costs are one more component to run and scale, and a CSRF defence for the cookie. For a banking or admin app I accept that. For a low-risk site it can be too much.
Q86. "API keys for service-to-service calls: storage, rotation and comparison."
Reveal answer
Strong answer An API key is a long random string that identifies a calling service, not a person. Treat it like a password with three rules.
Storage: generate at least 32 random bytes with secrets.token_urlsafe, show the raw key to the owner once, and store only a SHA-256 hash. A fast hash is fine here, unlike for human passwords, because the key already has 256 bits of randomness and cannot be guessed offline.
Comparison: hash the presented key and compare with hmac.compare_digest. It takes the same time whether the first or the last byte differs, so an attacker cannot learn the key one byte at a time by timing responses.
Rotation: support two active keys per client. Issue the new key, let the client deploy it, then deactivate the old one. A prefix such as qb_ makes leaked keys easy to find with secret scanners, and a key id lets you look up the record by id before comparing.
Picture it The whole scheme in twenty lines, including a rotation.
import hashlib, hmac, secrets
def new_key(prefix="qb"):
raw = f"{prefix}_{secrets.token_urlsafe(32)}"
return raw, hashlib.sha256(raw.encode()).hexdigest() # show raw ONCE, store only the hash
store = {} # key_id -> {"hash":..., "active": bool}
raw1, h1 = new_key(); store["billing-1"] = {"hash": h1, "active": True}
print("issued:", raw1[:8] + "...", "| stored hash:", h1[:16] + "...")
def check(presented: str) -> str | None:
digest = hashlib.sha256(presented.encode()).hexdigest()
found = None
for kid, rec in store.items(): # compare every record, no early exit
if rec["active"] and hmac.compare_digest(rec["hash"], digest):
found = kid
return found
print("valid key ->", check(raw1))
print("wrong key ->", check("qb_" + "x" * 43))
raw2, h2 = new_key(); store["billing-2"] = {"hash": h2, "active": True} # rotation: add new first
print("both active ->", check(raw1), check(raw2))
store["billing-1"]["active"] = False # then retire the old one
print("after rotation ->", check(raw1), check(raw2))Make the invisible visible: Issue, check, rotate.
issued: qb_Pfuxr... | stored hash: 64f1a676d25c76ce...
valid key -> billing-1
wrong key -> None
both active -> billing-1 billing-2
after rotation -> None billing-2Why: The database never holds a usable key, so a database leak does not leak access. During the overlap both keys work; after the old one is switched off, only the new one does.
Naive
The raw key is stored and compared with ==.
KEYS = {"billing": "qb_secret"}
def check(k):
# ❌ TRAP: stored raw, timing leak
return KEYS["billing"] == kCorrect
Hash stored; constant-time compare.
def check(k):
d = sha256(k.encode()).hexdigest()
# ✅ only the hash is stored
return hmac.compare_digest(
stored_hash, d)The shift: A leaked database must not equal leaked access, and a comparison must not leak how close the guess was.
Land it I store only a SHA-256 hash of a long random key, compare with compare_digest, and allow two active keys per client so rotation never needs a flag day.
- "Why is SHA-256 acceptable for keys when it is not for passwords?"
-
Because the two secrets have very different amounts of randomness, and the slow hashes exist to fix a problem keys do not have.
A human password such as "Biryani2024!" comes from a small, predictable set. An attacker who steals the hash table can test billions of guesses per second with a fast hash, so we use deliberately slow algorithms, Argon2 or bcrypt, to cut that to thousands per second.
An API key made from 32 random bytes has 2^256 possible values. There is nothing to guess, so a slow hash would add cost to every request and no security.
So SHA-256 is enough. Its job here is just to make sure that a stolen database does not hand over working keys, since the raw key cannot be recovered from the hash.
The rule: the key must come from
secrets.token_urlsafe(32). A key a person chose is a password and needs a slow hash. - "Should I send keys in the URL?"
-
No, never in the URL. A URL is copied to far more places than a header is. Web servers and load balancers write it to access logs, browsers store it in history, proxies and CDNs log it, and it appears in the
Refererheader when the user follows a link to another site.Consider the path from one log line: someone with read access to the access logs, which are usually widely shared for debugging, can copy the key and call the API as that client. The key then lives as long as the logs do.
Headers are not logged by default. I send the key in
X-API-Keyor inAuthorization: Bearer ..., which most gateways know to mask.The same rule applies to tokens, session ids and reset links. If a link must carry a secret, as an email reset link does, it should be single-use and short-lived, so that a logged copy has little value.
- "When would you pick mutual TLS or signed tokens over API keys?"
-
When the number of services grows and static keys become the weak point. Keys are copied into config files, CI variables and laptops, they rarely expire, and rotating a hundred of them by hand does not happen.
- Mutual TLS: both sides present certificates, so each proves its identity at connection time. Inside a Kubernetes service mesh the certificates are issued and renewed automatically, often every day or so, so there is nothing for people to rotate.
- Signed short-lived tokens: a service gets a token from the identity provider with the client credentials flow. It carries scopes and expires in minutes, which a static key cannot do.
API keys still fit well for partner integrations with a handful of customers, where giving each a certificate or an OAuth client would be heavy. My rule of thumb: keys for a few external partners, tokens or mTLS for many internal services.
- "How do you detect a leaked key?"
-
By designing the key so that leaks are easy to spot and cheap to survive, since I cannot prevent every one.
First, prefix the keys, for example
qb_live_. Secret scanners in GitHub and similar tools can then be told to look for that prefix in repositories, so a key committed by mistake is flagged within minutes.Second, record usage. Every call logs the key id (never the key itself), the source IP and the route. A key that was used from a data centre in another country at 3 a.m. stands out, and I alert on a key suddenly seen from a new IP range or at ten times its normal rate.
Third, have a practiced response. Because each client may hold two active keys, I issue a new one, ask the client to deploy it and deactivate the old one. For a confirmed leak the same steps run in hours rather than weeks. Practicing it once before an incident is what makes it work.
Q87. "What is CORS, what does it protect, and what does it not protect?"
Reveal answer
Strong answer Browsers apply the same-origin policy: a script from https://evil.example may send a request to your API, but it may not read the response unless your API says so. CORS (cross-origin resource sharing) is the set of response headers by which your API tells the browser which other origins may read it.
For "simple" requests the browser sends the call and checks Access-Control-Allow-Origin afterwards. For anything else (JSON bodies, an Authorization header, PUT or DELETE) it first sends a preflight: an OPTIONS request asking "may I send this method with these headers?". Only if the answer allows it does the real request go out.
CORS protects the user's browser from letting one site read another site's data using the user's credentials. It does not protect your server. curl, a mobile app, a script on another server ignore CORS completely. It is not authentication, so every endpoint still needs real token checks.
Never combine allow_origins=["*"] with credentials. Browsers refuse that pairing, and echoing back whatever origin arrives defeats the purpose.
Picture it What the middleware actually sends for an allowed origin, a stranger, and a request with no Origin header at all.
The setup: One allowed origin, https://app.quickbite.example, credentials on, 600-second preflight cache.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.testclient import TestClient
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["https://app.quickbite.example"],
allow_methods=["GET", "POST"], allow_headers=["Authorization", "Content-Type"],
allow_credentials=True, max_age=600)
@app.get("/v1/orders")
def orders(): return []
c = TestClient(app)
def show(title, r):
print(f"--- {title}: {r.status_code}")
for k, v in r.headers.items():
if k.startswith("access-control") or k == "vary": print(f" {k}: {v}")
pre = {"Access-Control-Request-Method": "GET", "Access-Control-Request-Headers": "authorization"}
show("preflight, allowed origin", c.options("/v1/orders", headers={"Origin": "https://app.quickbite.example", **pre}))
show("preflight, other origin", c.options("/v1/orders", headers={"Origin": "https://evil.example", **pre}))
show("simple GET, allowed origin", c.get("/v1/orders", headers={"Origin": "https://app.quickbite.example"}))
show("simple GET, no Origin (curl)", c.get("/v1/orders"))Make the invisible visible: Real headers from four requests.
--- preflight, allowed origin: 200
vary: Origin
access-control-allow-methods: GET, POST
access-control-max-age: 600
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type
access-control-allow-credentials: true
access-control-allow-origin: https://app.quickbite.example
--- preflight, other origin: 400
vary: Origin
access-control-allow-methods: GET, POST
access-control-max-age: 600
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type
access-control-allow-credentials: true
--- simple GET, allowed origin: 200
access-control-allow-credentials: true
access-control-allow-origin: https://app.quickbite.example
vary: Origin
--- simple GET, no Origin (curl): 200What you see: The allowed origin gets access-control-allow-origin echoed back and vary: Origin. The stranger gets a 400 and no allow-origin header, so the browser blocks the read. The curl-style request with no Origin sails through with no CORS headers, because CORS only concerns browsers.
Spring Boot
A global configuration bean.
// illustrative
registry.addMapping("/v1/**")
.allowedOrigins("https://app.example")
.allowedMethods("GET", "POST")
.allowCredentials(true);FastAPI
Starlette's middleware.
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example"],
allow_methods=["GET", "POST"],
allow_credentials=True)The shift: Same headers, same browser rule; remember it is a browser courtesy, not a firewall.
Land it CORS tells browsers which sites may read my responses; it protects users from other sites, not my API from callers, and it is never a substitute for authentication.
- "Why does the browser send a preflight at all?"
-
Because some requests could do damage on servers that were never designed for cross-site calls, and the browser wants the server to opt in before sending them.
Think of a DELETE request with a custom
Authorizationheader. Before CORS existed, no web page could send that to another site. If browsers sent it straight away and checked the answer afterwards, an evil page could trigger deletions on any API the user was logged into, and CORS would only hide the response, not stop the damage. So for these "non-simple" requests the browser first sends anOPTIONSrequest asking "may I send DELETE with these headers from this origin?".A simple form POST, a GET, or a POST with a plain content type, was already possible from any page before CORS, so adding a preflight would not make it safer. Those skip it.
The price is an extra round trip on every JSON POST. I cache the answer with
max_age, for example 600 seconds, so the browser asks once per origin and path. - "Why can't I use
*with credentials?" -
Because it would defeat the purpose. The point of the credentials rule is that a response containing someone's private data must be readable only by origins you trust.
The reasoning goes like this. A cookie makes the request authenticated as the user. If the server answered
Access-Control-Allow-Origin: *to credentialed requests, any site the user visits could call your API with their cookie and read the reply, such as their order history. That is the exact attack that the same-origin policy was built to stop.So the specification says that with credentials the browser refuses a wildcard, and the server must name one specific origin and send
Access-Control-Allow-Credentials: true.The wrong fix is to echo back whatever
Originarrives. That is a wildcard in disguise and gives the same exposure. In FastAPI I list exact origins inallow_origins, or a fully anchored regex for preview deployments. - "Do I need CORS if the frontend and API share one domain?"
-
No. CORS only matters when a page on one origin calls an API on another. An origin is the scheme, host and port together. If the frontend is at
https://app.quickbite.exampleand the API is athttps://app.quickbite.example/api, they share an origin and the browser applies no cross-origin check.A gateway or reverse proxy makes this easy: it serves the static frontend at
/and forwards/api/*to the FastAPI app. The browser sees one site.The gains reach beyond skipping a middleware. Cookies need no
SameSite=None, so the browser's CSRF protection stays on. There are no preflight requests, which saves a round trip per JSON call. And there is no allow-list to keep in sync with frontend hosts.I still keep the CORS middleware disabled rather than loosened. If no cross-origin caller exists, the safest configuration is that no origin is allowed.
- "Where should CORS be configured, gateway or app?"
-
In exactly one place. If both the gateway and the app add CORS headers, the response can carry two copies, for example
Access-Control-Allow-Origin: https://a.example, https://a.example. Browsers treat that as invalid and block the response, and the error looks like a CORS failure that "should not happen".Which one to pick depends on who owns the list of allowed origins. If the API team owns it and it changes with each frontend deploy, put it in the app with
CORSMiddleware, where it is versioned with the code and covered by tests. If a platform team owns many APIs and wants one policy, put it in the gateway and switch it off in the app.The same rule applies to other cross-cutting settings, such as compression, security headers and rate limits. When two layers do the same job, they interfere.
I write the choice in the runbook, so that someone debugging a CORS error at night knows which layer to open first.
Q88 · Scenario. "The browser shows CORS errors but curl works. Diagnose."
Reveal answer
The real test Whether you check the status code behind the error before touching the CORS settings.
Strong answer curl works because it never asks CORS questions. The error message mentions CORS, but the cause is often something else that happens to leave out the CORS headers. I work through four suspects in order.
- Look at the real status: open the Network tab, ignore the console message, and read the status of the failed request. A 500 from an unhandled exception is returned by Starlette's outermost layer without CORS headers, so the browser reports "CORS error" for what is really a server bug.
- Check the Origin: compare the page's exact origin (scheme, host and port) with the allow-list.
http://localhost:5173andhttp://127.0.0.1:5173are different origins. - Check the preflight: an
OPTIONSthat returns 400 means the method or a request header is not allowed. A custom header such asIdempotency-Keymust be inallow_headers. - Check redirects: a redirect (for example from
/v1/ordersto/v1/orders/) is not allowed after a preflight, and a redirect to http from https is blocked as well.
Picture it The same middleware, five different requests, and the allow-origin header each one gets back.
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.testclient import TestClient
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["https://app.quickbite.example"],
allow_methods=["GET"], allow_headers=["Authorization"])
@app.get("/v1/orders")
def ok(): return []
@app.get("/v1/boom")
def boom(): raise RuntimeError("bug")
@app.get("/v1/teapot")
def teapot(): raise HTTPException(418, "short and stout")
@app.get("/v1/slash/")
def slash(): return []
o = {"Origin": "https://app.quickbite.example"}
c = TestClient(app, raise_server_exceptions=False)Make the invisible visible: Real behaviour on FastAPI 0.141.1.
200 route : 200 ACAO = https://app.quickbite.example
HTTPException 418 : 418 ACAO = https://app.quickbite.example
unhandled 500 : 500 ACAO = None
missing slash : 307 Location = http://testserver/v1/slash/ ACAO = https://app.quickbite.example
preflight DELETE : 400 Disallowed CORS method
preflight bad hdr : 400 Disallowed CORS headersWhat you see: A normal 200 and an HTTPException both carry the header. The unhandled RuntimeError returns 500 with no allow-origin header. The two preflights fail with plain-text reasons, Disallowed CORS method and Disallowed CORS headers, that the browser console never shows you but curl does.
Why: The fix for the third case is an exception handler for Exception (see Q95) so that errors travel through the normal response path, and the fix for the others is the allow-list. Replay the preflight with curl and the Origin and Access-Control-Request-* headers to see the plain-text reason.
What the browser tells you
One vague message for four causes.
Access to fetch at 'https://api...' from
origin 'https://app...' has been blocked
by CORS policy: No 'Access-Control-Allow-
Origin' header is present on the response.What curl tells you
The real status and reason.
$ curl -i -X OPTIONS .../v1/orders \
-H 'Origin: https://app.example' \
-H 'Access-Control-Request-Method: GET' \
-H 'Access-Control-Request-Headers: \
idempotency-key'
HTTP/1.1 400 Bad Request
Disallowed CORS headersThe shift: Stop reading the browser's summary and replay the exact preflight yourself.
Land it I look at the actual status first, because a 500 or a redirect shows up as a CORS error, then I replay the preflight with curl to see the exact reason.
- "Why does an unhandled 500 lack CORS headers?"
-
Because Starlette wraps the whole application in
ServerErrorMiddleware, and it sits outside every middleware you add, includingCORSMiddleware.When an endpoint raises an exception that nothing handles, the exception travels outward through your middleware stack. Your CORS middleware is inside, so the exception passes through it without producing a response, and CORS never gets a chance to add headers. At the outer edge
ServerErrorMiddlewarebuilds the plain 500 response and sends it, with noAccess-Control-Allow-Origin. The browser then reports a CORS error, and the real problem, a server bug, hides behind it.The fix is a handler registered with
@app.exception_handler(Exception). The exception is now turned into a normal 500 response inside the stack, so it passes back out through the CORS middleware, which adds its headers.It is one more reason for a catch-all handler. The user sees a real error message and the developer sees the real status in the console.
- "How do I allow several origins, including preview deployments?"
-
Use an exact list for production hosts and a regular expression for the pattern of preview hosts.
allow_origins=["https://app.quickbite.example"]covers the main site, andallow_origin_regex=r"https://pr-\d+\.preview\.quickbite\.example"covers every pull-request preview.The danger is a loose pattern. Take
.*quickbite.*. It matcheshttps://quickbite.evil.exampleandhttps://evil.example/?quickbitedepending on how it is applied, so an attacker registers a matching domain and your API trusts it.Anchor the whole pattern, escape the dots, and constrain every part: the scheme, the exact domain suffix and a digits-only or letters-only segment where variable. The middleware uses a full match, but I still write
^...$so that the intent is plain.I add a test with three hostile origins, such as a look-alike suffix and a different scheme, and assert that none of them gets an allow header.
- "Which response headers can JavaScript read?"
-
Only a short safelist, unless the server adds the others in
expose_headers. By default, JavaScript on a cross-origin page can readCache-Control,Content-Language,Content-Length,Content-Type,Expires,Last-ModifiedandPragma, and nothing else.The headers an API wants to give the client are exactly the ones outside it:
Locationafter a 201,ETagfor conditional requests,Retry-Afterafter a 429, andX-Request-IDfor support. The browser receives them but hides them from the script. The code readsresponse.headers.get("Location")and getsnull, although the header appears in the Network tab.That mismatch, visible in DevTools but missing in code, is the classic symptom.
The fix is
CORSMiddleware(..., expose_headers=["Location", "ETag", "Retry-After", "X-Request-ID"]). I keep the list in one constant and add a test that checks the exposed names. - "Does CORS affect WebSockets?"
-
No, and that surprises people. The browser does not apply CORS to WebSocket handshakes. A page on any site can open a WebSocket to your server, and the browser attaches the user's cookies to the handshake.
What the browser does send is an
Originheader with the page's origin. It is the server's job to read that header during the handshake and refuse unknown origins. If it does not check, any website can talk to the endpoint as the logged-in user. This is called cross-site WebSocket hijacking, and it is the usual way a WebSocket endpoint ends up open to everyone.In FastAPI I read
websocket.headers.get("origin"), compare it with my allow-list, and callawait websocket.close(code=1008)before accepting if it does not match.I also do not rely on cookies alone. A token sent in the first message, or a short-lived ticket obtained over HTTPS and passed in the connection, gives a second proof that the request is intended.
Q89. "Spring Security's filter chain versus FastAPI security dependencies."
Reveal answer
Strong answer Spring Security is a chain of servlet filters that runs before your controller. Filters authenticate the request, build a SecurityContext stored in a thread-local, and an authorisation filter decides yes or no using URL patterns or method annotations. Security is applied around your code by configuration.
FastAPI has no equivalent filter chain. Security is ordinary dependencies: a function that reads the header and returns a User. Nothing is global; each endpoint lists what it needs, and a router can add a dependency to every route under it. There is no thread-local to read, because the user is a function argument.
The Python way is more explicit and easier to test: override one dependency and the endpoint sees a fake user. The cost is that nothing is secure by default. A route you forget to protect is open, so I put the authentication dependency on the router (or on the app) and make public routes the exception.
Security(dep, scopes=[...]) is Depends plus scope information that lands in the OpenAPI document, so Swagger shows which scopes each route needs.
Picture it The scope-aware version, which records the required scopes in the contract.
The setup: A dependency that receives SecurityScopes and compares them with what the caller was granted. The demo "token" is just a comma-separated scope list.
oauth2 = OAuth2PasswordBearer(tokenUrl="token", scopes={"orders:read": "Read orders", "orders:write": "Create orders"})
def current_user(scopes: SecurityScopes, token: Annotated[str, Depends(oauth2)]):
granted = set(token.split(",")) # demo: the "token" is just a list of scopes
missing = [s for s in scopes.scopes if s not in granted]
return {"granted": sorted(granted), "required": scopes.scopes, "missing": missing}
app = FastAPI()
@app.get("/orders")
def read(u: Annotated[dict, Security(current_user, scopes=["orders:read"])]): return u
c = TestClient(app)
print(c.get("/orders", headers={"Authorization": "Bearer orders:read"}).json())
print(c.get("/orders", headers={"Authorization": "Bearer orders:write"}).json())Make the invisible visible: Real output, including the OpenAPI entry.
{'granted': ['orders:read'], 'required': ['orders:read'], 'missing': []}
{'granted': ['orders:write'], 'required': ['orders:read'], 'missing': ['orders:read']}
openapi security: [{'OAuth2PasswordBearer': ['orders:read']}]Why: The scopes a route needs appear in security in the OpenAPI document, so generated clients and docs know them. The second call shows the dependency receiving required and granted lists and computing missing.
Spring Security
Central configuration, chain of filters.
// illustrative
http.authorizeHttpRequests(a -> a
.requestMatchers("/healthz").permitAll()
.requestMatchers(POST, "/v1/orders")
.hasAuthority("SCOPE_orders:write")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt());FastAPI
Dependencies on routers and routes.
router = APIRouter(
prefix="/v1/orders",
dependencies=[Depends(get_current_user)])
@router.post("")
def create(u: User = Depends(
require_scope("orders:write"))): ...The shift: Spring secures by URL pattern from one place; FastAPI secures by what each route declares, so a forgotten declaration means an open route.
Land it Spring wraps my code in a filter chain by configuration; FastAPI makes security a normal parameter, which is more testable but secure only where I remembered to declare it.
- "How do you make FastAPI secure by default?"
-
Move from "protected by configuration" to "protected by structure", and test that the structure holds.
- Dependency at the app level:
FastAPI(dependencies=[Depends(get_current_user)])makes every route require a valid user unless it opts out. Or I attach it to each router withAPIRouter(dependencies=[...]). - Public routes on their own router:
/healthzand/readyzlive in a router without the dependency, so being public is a visible decision. - A walking test: a test iterates
app.routesand fails if a route is neither in an explicit public allow-list nor depends on the authentication function.
The test is what turns "I hope nobody forgot" into a build failure. A new endpoint added by a colleague in a hurry fails CI unless it is protected or consciously listed as public.
- Dependency at the app level:
- "Is there a FastAPI equivalent of
@PreAuthorizewith expressions?" -
Not as a built-in expression language, and I am not sure I would want one. Spring's
@PreAuthorize("hasRole('ADMIN') and #id == principal.id")is powerful but its rules live in strings that are checked at runtime.The FastAPI equivalent is a dependency factory written in plain Python.
require_scope("orders:write")checks a capability.require_role("admin")checks a coarse group.require_owner(Order)can load the resource from the path id, compare it with the user and raise 404 or 403.Because they are ordinary functions, they have properties the string expressions lack. The IDE finds and renames them, type checkers see their signatures, and a unit test can call them directly with a fake
User. They also compose: an endpoint lists several of them in its parameters, and FastAPI runs them all, sharing one cachedget_current_user.The trade-off is that I write and maintain these helpers myself.
- "Where does Spring's
SecurityContextthread-local go?" -
It disappears, and in its place the current user becomes an explicit function argument. In Spring, deep code may call
SecurityContextHolder.getContext()and find the user from a thread-local variable. FastAPI has no thread-local, because async code runs many requests on one thread and thread-locals would mix them up.So the dependency returns a
Userand the endpoint passes it, or just its id, down to the service:service.create_order(session, user.id, payload). Everything the function depends on is visible in its signature.If a deep layer truly needs the user, such as an audit logger, a
ContextVarset by the dependency works, because it is isolated per task in asyncio. I still prefer passing arguments. Hidden global state makes tests fragile, and it breaks in a background job, which has no request and therefore no user to find.The rule I follow: pass what you need, and use a
ContextVaronly for cross-cutting concerns like request ids in logs. - "What does Spring give that FastAPI does not?"
-
Mainly a large body of mature, audited security code that has years of production use. Spring Security gives session fixation protection, a CSRF filter, method security, OAuth2 login and resource-server support, password encoders, remember-me, and sensible secure-by-default headers, all tested together.
In FastAPI I assemble the same capabilities from smaller pieces: PyJWT, an OAuth client library, Starlette's session middleware, a few helper functions of my own. Each piece is good, but the combination, and its gaps, are mine to review. A mistake in how I wire them together is not covered by anyone's audit.
That is a real cost, and for some systems it decides the question. If the product is security-heavy, such as banking or a platform with complicated access rules, and the team already knows Spring, staying on the JVM is a strong argument.
For a typical API behind an identity provider, where the API only validates tokens, the gap is small, and FastAPI's explicitness is an advantage.
Q90. "How do you rate-limit a FastAPI application?"
Reveal answer
Strong answer Rate limiting protects you from a buggy client retry loop, a scraper and a password-guessing attacker. The first place to do it is outside the application: the load balancer, API gateway or CDN already sees every request, runs in fast native code and protects all pods at once.
In-app limiting is still useful for rules that need business knowledge, such as "five failed logins per account per ten minutes" or "100 order creations per customer per hour". With several pods the counters must live in a shared store, normally Redis, using an atomic increment with an expiry. Counters in process memory only limit one pod's slice.
The usual algorithm is a token bucket: each client has a bucket that refills at a steady rate up to a burst size, and each request removes a token. When the bucket is empty, return 429 Too Many Requests with a Retry-After header saying how many seconds to wait.
Libraries such as slowapi wrap this pattern (it is not installed on the course machine, so I describe it rather than run it). The core is small enough to write and test, as the demo shows.
Picture it A token bucket as a dependency, with a fake clock so the output is exact. Rate is 2 requests per second, burst is 3.
import math, time
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.testclient import TestClient
class TokenBucket:
def __init__(self, rate, burst, clock=time.monotonic):
self.rate, self.burst, self.clock, self.state = rate, burst, clock, {}
def take(self, key):
now = self.clock(); tokens, last = self.state.get(key, (self.burst, now))
tokens = min(self.burst, tokens + (now - last) * self.rate)
if tokens >= 1:
self.state[key] = (tokens - 1, now); return 0
self.state[key] = (tokens, now); return math.ceil((1 - tokens) / self.rate)
fake_now = [0.0]
bucket = TokenBucket(rate=2, burst=3, clock=lambda: fake_now[0]) # 2 req/s, burst of 3
def limit(request: Request):
key = request.headers.get("x-api-key", request.client.host)
wait = bucket.take(key)
if wait: raise HTTPException(429, "Too Many Requests", headers={"Retry-After": str(wait)})
app = FastAPI()
@app.get("/v1/orders", dependencies=[Depends(limit)])
def orders(): return []
c = TestClient(app)
for i in range(1, 6):
r = c.get("/v1/orders"); print(f"t=0.0 request {i}: {r.status_code} Retry-After={r.headers.get('retry-after')}")
fake_now[0] = 1.0
r = c.get("/v1/orders"); print(f"t=1.0 request 6: {r.status_code} (2 tokens refilled)")Make the invisible visible: Five requests in the same instant, then one a second later.
t=0.0 request 1: 200 Retry-After=None
t=0.0 request 2: 200 Retry-After=None
t=0.0 request 3: 200 Retry-After=None
t=0.0 request 4: 429 Retry-After=1
t=0.0 request 5: 429 Retry-After=1
t=1.0 request 6: 200 (2 tokens refilled)Why: The first three use the burst. The fourth and fifth get 429 with Retry-After: 1. One second later two tokens have refilled, so the next request passes. The clock is injected, which is why the test can be written without sleeping.
In-process counter
Each pod counts alone.
HITS = {} # ❌ TRAP: per pod, lost on restart
def limit(key):
HITS[key] = HITS.get(key, 0) + 1
return HITS[key] <= 100Shared counter
All pods count in Redis.
# illustrative: redis-py
async def limit(key, n=100, sec=60):
k = f"rl:{key}:{int(time.time()//sec)}"
c = await r.incr(k) # atomic
if c == 1: await r.expire(k, sec)
return c <= nThe shift: The limit is only as real as the store behind it: shared and atomic, or it is a suggestion.
Land it I rate-limit at the gateway first, add per-customer limits in the app backed by Redis, and always answer 429 with Retry-After.
- "What should the limit key be?"
-
The key decides who is being limited, and the wrong key either punishes innocent users or lets abusers through.
My order of preference is: the authenticated customer id for logged-in routes, an API key id for partner clients, and the client IP only for anonymous routes such as login and signup. IP addresses are shared. An office, a university or a mobile carrier can put thousands of real users behind one address, and an IP-only limit would block them together.
Behind a proxy or load balancer, the socket address is the proxy's, not the client's. Reading the real IP from
X-Forwarded-Foris safe only if I trust the proxy that set it, otherwise a client can invent the header and dodge the limit. In uvicorn I turn on--proxy-headersand restrict--forwarded-allow-ipsto the proxy's address.For login I also limit per account name, since attackers rotate IPs but target one account.
- "Fixed window or token bucket?"
-
A token bucket, for most APIs, because a fixed window has a well-known gap at its edges.
A fixed window counts requests in clock slots, such as 100 per minute, reset at each minute. A client can send 100 requests at 12:00:59 and another 100 at 12:01:00. That is 200 requests in two seconds while obeying the rule, double the intended rate.
A token bucket avoids it. Each client has a bucket holding up to, say, 100 tokens, refilled at about 1.67 tokens per second (100 per minute). Each request takes one. A client can burst up to 100, but after emptying the bucket it can only continue at the refill rate. Real clients, such as an app opening a screen that fires six calls at once, produce bursts, and the bucket tolerates them.
A sliding window log or counter gives a similar smoothness with more memory. The fixed window is still acceptable for coarse rules like "5 failed logins per 10 minutes", where simplicity matters more.
- "What happens when Redis is down?"
-
I decide on purpose and write it down, because both choices hurt in different ways. The question is what a limiter failure should do: fail open (allow requests) or fail closed (block them).
Failing open keeps the API up, but for the duration of the outage nobody is rate limited. A buggy client loop or a scraper can now reach the database freely. Failing closed keeps the protection, but a Redis problem turns into a total API outage, which is a bigger blast radius than the thing being protected.
For general limits, like orders per hour, I fail open, log it, and alert, since the database has its own limits as a backstop. For login throttling and anything that guards against password guessing I fail closed, because the lost protection is the security control itself.
Either way the limiter call gets a short timeout, around 50 ms, so a slow Redis cannot slow every request.
- "How should clients react to a 429?"
-
A well-behaved client reads the response and slows down. It does not retry immediately, since that is exactly what created the problem.
- Read the header: wait for the number of seconds in
Retry-After, or a default of one second if absent. - Add jitter: wait a random extra amount, for example up to 30 percent, so that a thousand clients refused at the same moment do not all return at the same moment.
- Retry only if safe: GETs, or POSTs with an idempotency key. A blind retry of a plain POST can create a duplicate.
On my side I make this easier. I send headers such as
RateLimit-Limit,RateLimit-RemainingandRateLimit-Reseton normal responses, in the style of the IETF draft, so a client can pace itself before ever receiving a 429. I document the limits in the API guide as well. - Read the header: wait for the number of seconds in
Q91 · Scenario. "A user can read other customers' orders by changing the id in the URL. Fix it systematically."
Reveal answer
The real test Whether you fix the whole class (ownership enforced in one layer, with tests) instead of patching one endpoint.
Strong answer This is IDOR, insecure direct object reference, also called broken object-level authorisation. The endpoint checked that the caller was logged in but never checked that the order belongs to them. Changing /orders/17 to /orders/18 returns a stranger's data.
A patch on one endpoint leaves the same hole in every other endpoint that takes an id. The systematic fix has four parts.
- Put ownership in the data access: the repository's lookup always includes the caller,
WHERE id = :id AND customer_id = :user_id. There is then no method that fetches an order without an owner filter. - Return 404, not 403: for someone else's order, answer exactly as for a missing one. A 403 would confirm that order 18 exists.
- Do not rely on hard-to-guess ids: UUIDs reduce enumeration but are not authorisation. They leak through logs, emails and screenshots.
- Test the class: for every route that takes an id, a test logs in as customer A, creates a resource, then requests it as customer B and expects 404. Add it to the route checklist.
Picture it Two tiny endpoints: the naive one returns whatever id you ask for, the fixed one goes through a single owner-aware lookup.
from fastapi import FastAPI, HTTPException, Header
from fastapi.testclient import TestClient
ORDERS = {1: {"id": 1, "customer_id": 7, "total_cents": 1200}, 2: {"id": 2, "customer_id": 8, "total_cents": 900}}
app = FastAPI()
def me(authorization: str = Header()) -> int: return int(authorization.split()[-1]) # demo token = user id
@app.get("/naive/orders/{oid}")
def naive(oid: int, user: int = Header(alias="authorization")): # ❌ never looks at the owner
return ORDERS[oid]
def fetch_owned(oid: int, user_id: int):
o = ORDERS.get(oid)
if o is None or o["customer_id"] != user_id: # one rule, one place
raise HTTPException(404, "Order not found") # same answer for missing and foreign
return o
@app.get("/v1/orders/{oid}")
def fixed(oid: int, authorization: str = Header()): return fetch_owned(oid, me(authorization))
c = TestClient(app)Make the invisible visible: Customer 7 asks for orders 1 (theirs), 2 (customer 8's) and 99 (missing).
naive, customer 7 asks for order 2 : {'id': 2, 'customer_id': 8, 'total_cents': 900}
fixed, customer 7 asks for order 1: 200 {'id': 1, 'customer_id': 7, 'total_cents': 1200}
fixed, customer 7 asks for order 2: 404 {'detail': 'Order not found'}
fixed, customer 7 asks for order 99: 404 {'detail': 'Order not found'}Why: The naive endpoint hands over customer 8's row, including customer_id and the total. The fixed version answers 404 for both the foreign order and the missing one, so the two cases are indistinguishable from outside.
Naive
Id alone finds the row.
def get(self, order_id):
# ❌ TRAP: any caller, any id
return self.s.get(Order, order_id)Correct
Owner is part of the query.
def get(self, order_id, user_id):
# ✅ same 404 for foreign and missing
return self.s.scalars(select(Order)
.where(Order.id == order_id,
Order.customer_id == user_id)
).first()The shift: Authorisation stops being something each endpoint remembers and becomes part of how rows are found.
Land it I enforce ownership inside the repository query, return 404 for foreign ids, and add a cross-customer test for every route that takes an id.
- "Why 404 and not 403?"
-
Because 403 answers a question the attacker should not get answered. A 403 says "this order exists, but it is not yours". By trying ids 1 to 10,000 and watching which return 403 and which 404, an attacker learns which ids are real, how many orders exist, and roughly how fast the business is growing.
A 404 for someone else's order is identical to the answer for an id that never existed. The caller learns nothing. The canonical app does this, and its test suite asserts it: another customer's order returns 404.
It also falls out naturally from the right design. When the repository query is
WHERE id = :id AND customer_id = :user_id, a foreign order is simply not found, and the service raises the same not-found error. No separate "forbidden" branch exists to get wrong.The exception is a resource that is intentionally visible to many people, such as a shared document. There, 403 is honest and helps users, because existence is already public.
- "What about admin users who may see everything?"
-
Give admin its own explicit code path, with its own scope, and keep the owner filter everywhere else. I do not weaken the common query to let admins through.
In practice: the normal repository method,
get_for_customer(order_id, customer_id), always filters by owner. A second, separately named method,get_any(order_id), has no filter, and only an endpoint guarded byrequire_scope("orders:read_all")can reach it. A reviewer reading a route sees at a glance which kind of access it has.Every use of the unfiltered path is written to the audit log with who, which order and why (a ticket id, if the tool asks for one). Admin power then has a trail, and a stolen admin token leaves evidence.
The anti-pattern is a flag like
if user.is_admin: skip_filterinside the shared method. One refactor later, the condition is wrong for everyone. - "Can the database enforce this too?"
-
Yes. PostgreSQL has row-level security (RLS), and it works as a second wall behind the application's filter. You enable it on the table and add a policy, for example
USING (customer_id = current_setting('app.user_id')::int). After that, the database itself only returns rows matching the policy, even forSELECT * FROM orders.The app sets the variable at the start of each transaction, with
SET LOCAL app.user_id = '7'.LOCALmatters: it lasts only for that transaction, so a pooled connection cannot carry one user's identity into another request.The value is protection against forgotten filters. A new query written by a junior, an ad-hoc report, or a bug in a join cannot leak other customers' rows.
The costs: policies must be tested, the database role used by the app must not be a superuser or table owner (they bypass RLS), and it adds some complexity to migrations. I use it for multi-tenant data as a safety net, never as a replacement for the repository filter.
- "How do you find the holes that already exist?"
-
By treating it as an inventory problem first, then a test problem. IDOR rarely shows up in ordinary unit tests, because the happy path works perfectly: customer A requests customer A's order.
- List the routes: a short script walks
app.routesand prints every route with a path or body parameter that names an object, such asorder_id,restaurant_idorcustomer_id. This is the audit list. - Write the cross-customer test: for each route, create a resource as customer A, then call the route as customer B and expect 404 (or 403 where the design says so).
- Two-account manual pass: use a proxy or an authorisation scanner with two test accounts, replaying A's requests with B's token.
I put the checklist into the pull-request template, so every new route with an id gets the same test before merge.
- List the routes: a short script walks
Q92 · Design. "Design authentication and authorisation for QuickBite: customers, restaurants, riders and admins."
Reveal answer
Strong answer I start from the principals and what each may touch, then pick the mechanisms.
| Principal | Authenticates with | Scopes | Ownership rule |
|---|---|---|---|
| Customer (mobile and web) | Authorisation code + PKCE from the identity provider | orders:read, orders:write | own orders only (customer_id) |
| Restaurant staff | Same provider, "restaurant" realm | restaurant:orders:read, restaurant:orders:update | orders of their own restaurant id |
| Rider | Same provider, "rider" realm | delivery:read, delivery:update | assigned deliveries only |
| Admin | Provider with MFA, short sessions | admin:* split into narrow scopes | everything, every use audited |
| Services (dispatch, payments) | Client credentials, or mTLS inside the mesh | per-service scopes | none: they act for the platform |
The API is a pure resource server. One identity provider issues tokens. Claims carry sub, scope and the principal's restaurant or rider id. The API validates every token (Q82), turns it into a User, and each route declares a scope factory.
Scopes say what kind of thing a caller may do; ownership checks in repositories say which rows (Q91). Keep both, because scopes alone cannot tell restaurant 5's staff from restaurant 6's.
Picture it The request path, with the layer that makes each decision.
# illustrative
request ──► bearer token present? no ──► 401
──► signature, exp, iss, aud ok? no ──► 401
──► scope for this route? no ──► 403
──► row belongs to this caller? no ──► 404
──► business rule allows it? no ──► 409 / 422
──► do the work, write audit logWhy: Each failure has its own code, so a client, a log line and a dashboard can tell "needs login" from "not allowed" from "not found". Audit records for admin actions are written in the same transaction as the change.
One role string
Coarse and unauditable.
if user.role == "restaurant":
# ❌ TRAP: any restaurant,
# any restaurant's orders
return all_orders()Scope plus ownership
Capability, then row.
user = Depends(require_scope(
"restaurant:orders:read"))
# ✅ then the row filter
orders = repo.for_restaurant(
user.restaurant_id)The shift: A role names a kind of person; authorisation also needs to say which rows that person owns.
Land it I issue nothing myself: one identity provider, validated tokens, narrow scopes per principal, ownership enforced in repositories, and an audit trail for admin actions.
- "How do you handle a rider who works for two delivery companies?"
-
I would model the company as a tenant context carried in the token, not as something the client says.
Say a rider is registered with two companies, Company A and Company B. At login, or when switching accounts in the app, the user picks one context. The identity provider issues a token for that context, with a claim like
company_id=A, and each query the API runs is scoped by that signed value. Orders from Company B are invisible while the token says A.The mistake to avoid is accepting the company in a request header or body and trusting it. That is just IDOR with extra steps: the rider could write another company's id. The only trustworthy source is the signed token.
Switching context means a new token, not a changed header. The audit log records the company on every action, so a dispute over a delivery can show which context was active.
If the number of contexts per person grows, I would move to a proper organisation model at the provider instead of stretching this one.
- "How do you revoke a rider who is fired right now?"
-
A JWT cannot be pulled back before it expires, so the answer is a combination: short lifetimes, revocable refresh tokens, and a small fast deny-list for emergencies.
- Short access tokens: five minutes means the worst case is five minutes of access after a firing.
- Revoke at the provider: disabling the account stops refresh tokens working, so the rider cannot get another access token after the current one expires.
- Deny-list for instant effect: the dependency checks Redis for a key like
revoked:<sub>, set by the admin action with a TTL equal to the longest token life. If present, answer 401.
The deny-list adds one Redis lookup per request, but it holds only a handful of entries and stays tiny. Where this matters across the product, I use opaque tokens introspected with a few seconds of caching instead, which gives a revocation delay of seconds with no special code.
- "Where do service-to-service calls fit?"
-
Services use the client credentials flow, so no user is involved and the token's
subis the service itself. The dispatch service gets a token from the identity provider with scopes such asorders:read_allordelivery:update, calls the orders API with it, and the API validates it like any other token.Scopes for services should be narrow and specific. Dispatch needs to read orders and update delivery state, not to refund payments. If it is compromised, the attacker gets only that list.
Inside Kubernetes I add two network-level layers. mTLS in the service mesh proves which workload is calling, using certificates the mesh rotates automatically. A network policy then states which pods may reach the orders pods at all, so a compromised pod in an unrelated namespace cannot even open a connection.
Both layers together are stronger than either. Tokens say what the caller may do, and the network layer says who may speak to whom.
- "What would you log for audit?"
-
An audit log answers "who did what to what, when, from where, and did it work", and it must be hard to alter.
The fields I record: the actor (
suband role or scope used), the action (route and verb), the target (resource type and id), the before and after values for status changes, the time, the origin (request id and source IP) and the outcome (success, denied, error). Denials matter as much as successes, because a pattern of denied admin calls is a warning sign.Where it goes matters. I write it to an append-only table, or an event stream with restricted write access, separate from the application logs that developers can search, rotate or delete. People who administer the system should not be able to quietly edit the record of their own actions.
What I leave out: tokens, passwords, and personal fields such as phone numbers and addresses. I store ids, not content, and keep a retention period written down.
These questions test whether your API fails in a way a client can act on, an operator can trace, and an attacker learns nothing from.
Q93. "HTTPException versus custom exception handlers."
Reveal answer
Strong answer HTTPException is the quick tool. You raise it with a status and a message, and FastAPI turns it into a response. It is right for plain HTTP situations in the HTTP layer, such as "not found" or "missing header".
The weakness shows when domain code is deep inside a service. A service that raises HTTPException(409) now knows about HTTP, cannot be reused from a worker or a CLI, and spreads status codes through the business logic.
A better design: domain code raises domain exceptions (OutOfStock, RestaurantClosed) that know nothing about HTTP, and one registered handler per exception type maps them to a status and a body. The mapping lives in one file, errors.py, so the whole API's error behaviour is reviewable in one place and consistent.
Handlers also let you change the shape of built-in errors (422 validation, 404) so every error looks the same to clients, which Q94 turns into a standard.
Picture it A domain exception raised five calls deep, mapped by one handler.
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
class OutOfStock(Exception):
def __init__(self, item_id): self.item_id = item_id
app = FastAPI()
@app.exception_handler(OutOfStock)
async def out_of_stock(request, exc):
from fastapi.responses import JSONResponse
return JSONResponse({"type": "out-of-stock", "item_id": exc.item_id}, status_code=409)
@app.get("/a")
def a(): raise HTTPException(404, "Order not found") # fine: one place, one status
@app.get("/b")
def b(): raise OutOfStock(42) # domain code stays HTTP-free
def deep_service():
raise OutOfStock(7) # raised 5 calls deep, no HTTPException import
@app.get("/c")
def c(): deep_service()
cl = TestClient(app)
for p in ("/a", "/b", "/c"):
r = cl.get(p); print(p, r.status_code, r.json())Make the invisible visible: Three routes.
/a 404 {'detail': 'Order not found'}
/b 409 {'type': 'out-of-stock', 'item_id': 42}
/c 409 {'type': 'out-of-stock', 'item_id': 7}Why: /c raises OutOfStock from deep_service(), which imports nothing from FastAPI, yet the client gets a clean 409. The same function could run in a Celery task and just raise.
HTTPException in the service
Business code knows HTTP.
def reserve(item):
if item.stock < 1:
# ❌ TRAP: HTTP inside a service
raise HTTPException(409, "out")Domain error plus handler
Mapping lives in one place.
def reserve(item):
if item.stock < 1:
raise OutOfStock(item.id)
@app.exception_handler(OutOfStock)
async def h(req, exc): ... # 409 hereThe shift: Let business code say what went wrong, and let the HTTP layer decide what that means on the wire.
Land it I raise domain exceptions from services and map them to HTTP in registered handlers, so status codes live in one file.
- "Does a handler for
ExceptioncatchHTTPExceptiontoo?" -
No. FastAPI chooses the most specific handler for the exception's class, so a handler registered for a subclass beats one registered for
Exception.The lookup walks the exception's class hierarchy, called the method resolution order, from the most specific class toward
Exceptionand uses the first handler it finds. AnHTTPExceptionraised by my code finds the handler forHTTPException(or its base) first, and never reaches the catch-all.The catch-all runs for exceptions with no closer match, such as a
KeyErrorfrom a bug or a database error that nothing converted.One limit worth stating: an exception raised after the response has already started streaming cannot change the status code, because the status line was sent. The handler cannot help there; the server logs it and the connection ends early.
That is why I keep the catch-all lean: log with the request id, return a generic 500 Problem body, and nothing clever.
- "Should I use FastAPI's or Starlette's
HTTPExceptionin handlers?" -
Register your handler for Starlette's
HTTPException, which is the base class. FastAPI's ownHTTPExceptioninherits from it, so a handler on the base catches both.The reason is who raises what. Your code raises
fastapi.HTTPException. But Starlette's routing raises its ownstarlette.exceptions.HTTPExceptionfor an unknown path (404) and for a wrong method (405), before any of your code runs. If you register a handler only for FastAPI's class, those two errors skip it and come back in Starlette's default shape,{"detail": "Not Found"}, while your own errors come back as Problem Details. Clients then see two formats from one API.In code:
from starlette.exceptions import HTTPException as StarletteHTTPExceptionand@app.exception_handler(StarletteHTTPException).It is the kind of mismatch that appears only when someone mistypes a URL in production, so I add a test that requests an unknown route and checks the body shape.
- "How do I keep the default 422 shape for validation errors but still add a request id?"
-
Register a handler for
RequestValidationError, build the response body yourself, and add the request id there. FastAPI's default 422 shape,{"detail": [...]}, is only the default; the handler lets me wrap it.The error list comes from
exc.errors(). Each item has a location (loc), a message (msg) and a type, and I keep these because they are what a form needs to highlight the right field. I put them under anerrorskey next to the standard Problem fields and addrequest_id.One trap: each item also has an
inputfield that repeats the value the user sent. If the failing field was a password or a card number, the response echoes it, and then it ends up in logs, proxies and error trackers. The canonicalerrors.pydropsinputfor that reason, with a comment saying so.The status stays 422 unless the team has chosen 400, in which case I change it in this one handler.
- "Where should the HTTP status of a domain error be defined?"
-
On the exception class itself, as an attribute such as
status = 409, with a single handler registered for the base class. The canonical app does this.Look at the design this gives.
OutOfStock,RestaurantClosedandInvalidTransitioneach subclass a baseDomainErrorand declare their own status and problem type. One handler reads those attributes and builds the response. Adding a new business error then means writing one small class, with no new handler, no import inmain.pyand no edit in the mapping file.That keeps the status codes reviewable in one place: reading
errors.pyshows the entire error contract of the API.It does not mean domain code knows HTTP. The number is a plain integer attribute, a mapping hint, and the exception raises and catches the same way in a worker or a CLI. If purity matters more, the same mapping can sit in a dictionary in the HTTP layer instead; I accept the attribute for its convenience.
Q94. "What is RFC 9457 Problem Details, and how do you return it from FastAPI?"
Reveal answer
Strong answer RFC 9457 (which replaced RFC 7807) defines one JSON shape for HTTP errors, with the media type application/problem+json. The fields are type (a URI naming the kind of problem), title (short and stable), status, detail (this occurrence, in words) and instance (which request). You may add extension fields such as errors or request_id.
The benefit is that every client can parse every error the same way. Without it, one endpoint returns {"detail": "..."}, another {"error": "..."}, and the 422 returns a list of objects.
In FastAPI you register handlers for RequestValidationError, StarletteHTTPException, your domain base exception and Exception, and have all four call one problem() helper that sets the media type. The canonical app/errors.py does exactly this.
Picture it The three kinds of error, all in one shape.
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.testclient import TestClient
PROBLEM = "application/problem+json"
def problem(request, status, title, detail=None, type_="about:blank", **ext):
body = {"type": type_, "title": title, "status": status, "detail": detail, "instance": request.url.path, **ext}
return JSONResponse(body, status_code=status, media_type=PROBLEM)
class OutOfStock(Exception): pass
app = FastAPI()
@app.exception_handler(RequestValidationError)
async def on_422(request: Request, exc: RequestValidationError):
errs = [{"loc": list(e["loc"]), "msg": e["msg"], "type": e["type"]} for e in exc.errors()]
return problem(request, 422, "Validation failed", "Body or parameters are invalid.", errors=errs)
@app.exception_handler(StarletteHTTPException)
async def on_http(request: Request, exc: StarletteHTTPException):
return problem(request, exc.status_code, "HTTP error", str(exc.detail))
@app.exception_handler(OutOfStock)
async def on_stock(request: Request, exc: OutOfStock):
return problem(request, 409, "Item out of stock", "Biryani is sold out.", "https://api.quickbite.example/problems/out-of-stock")
class OrderIn(BaseModel):
qty: int = Field(gt=0)
@app.post("/v1/orders")
def create(o: OrderIn):
if o.qty > 5: raise OutOfStock()
return {"ok": True}
c = TestClient(app)
for label, r in [("validation", c.post("/v1/orders", json={"qty": 0})), ("domain", c.post("/v1/orders", json={"qty": 9})), ("no route", c.get("/nope"))]:
print(f"--- {label}: {r.status_code} {r.headers['content-type']}")
print(r.json())Make the invisible visible: A validation failure, a domain error and an unknown route.
--- validation: 422 application/problem+json
{'type': 'about:blank', 'title': 'Validation failed', 'status': 422, 'detail': 'Body or parameters are invalid.', 'instance': '/v1/orders', 'errors': [{'loc': ['body', 'qty'], 'msg': 'Input should be greater than 0', 'type': 'greater_than'}]}
--- domain: 409 application/problem+json
{'type': 'https://api.quickbite.example/problems/out-of-stock', 'title': 'Item out of stock', 'status': 409, 'detail': 'Biryani is sold out.', 'instance': '/v1/orders'}
--- no route: 404 application/problem+json
{'type': 'about:blank', 'title': 'HTTP error', 'status': 404, 'detail': 'Not Found', 'instance': '/nope'}What you see: The content type is application/problem+json in all three. The validation error carries an errors list with loc, msg and type. The domain error has a stable type URI clients can switch on. The 404 reuses the same fields with about:blank.
Default FastAPI
Three shapes for three errors.
{"detail": "Not Found"}
{"detail": [{"loc": ["body","qty"],
"msg": "...", "type": "..."}]}
{"error": "OutOfStock"}Problem Details
One shape, a media type.
{"type": ".../out-of-stock",
"title": "Item out of stock",
"status": 409,
"detail": "Biryani is sold out.",
"instance": "/v1/orders"}The shift: Clients write one error parser instead of one per endpoint.
Land it I return RFC 9457 Problem Details from every error path through one helper, with stable type URIs clients can switch on.
- "Is the
typeURI supposed to resolve to a web page?" -
It should identify the problem type, and ideally the URL leads to documentation, but clients must treat it as an opaque identifier, not as something to fetch.
The
typeis a name. For examplehttps://api.quickbite.example/problems/out-of-stocksays "this is the out-of-stock problem". Because it is a URI, it is unlikely to collide with other teams' names. Clients compare it as a string and switch on it, for instance to show a "notify me" button.If the URL is also a real page that explains the problem, how to fix it and what the fields mean, that helps developers. But the client must never depend on the page loading, since it may be offline or the docs site may move.
When there is nothing more to say than the status code, RFC 9457 gives the value
about:blank, and then the title should be the standard status phrase.The important discipline is stability. Once a
typeis published, I never rename it, because clients are coding against it. - "Should
detailbe shown to end users?" -
No,
detailis written for developers, not for end users. It describes this specific occurrence in words and may carry technical wording, such as "stock for item 12 is 0, requested 3".Showing it to customers has two problems. It is not translated or written in friendly language, and it can leak information. Worse, if someone puts an exception message into it, the response can reveal SQL fragments, file paths or other customers' data.
So the client should choose the user-facing message from the stable
type:out-of-stockmaps to "Sorry, that dish just ran out" in the customer's language. Thedetailgoes to logs and to the developer console.On the server I follow a strict rule for
detail: it may name field names, ids that belong to the caller and limits, and it must never contain stack traces, SQL, internal hostnames, or anything about another user. For 500 errors it is a fixed generic sentence plus the request id. - "How do you document the error shapes in OpenAPI?"
-
I declare them per route in the
responsesparameter, with a Pydantic model that mirrors the Problem fields.- Define the model:
Problem(type, title, status, detail, instance), with an optionalerrorslist for validation problems. - Attach it:
responses={409: {"model": Problem, "description": "Out of stock or conflicting key"}}on the route, and similarly for 422, 401, 403 and 503. - Set the media type: the real response uses
application/problem+json, and the OpenAPI entry should say the same, so generated clients parse the right thing.
The payoff is in generated clients. A TypeScript or Kotlin client built from the OpenAPI file gets a typed error object per status and the mobile team stops guessing at shapes.
To avoid repeating this on every route, I keep a shared dictionary of the common error responses and spread it into each router's
responses. - Define the model:
- "What about validation errors with many fields?"
-
Keep the standard Problem fields and add one extension member,
errors, holding an array with one entry per failing field. Each entry has a location, a message and a rule or code.For an order with two bad lines, the body would carry a title like "Validation failed", status 422, and two entries:
lines.0.quantitywith "must be at least 1", andlines.2.menu_item_idwith "field required". Nothing about the shape changes between one error and twenty.The reason is usability. A form that receives only the first error makes the user fix, resubmit, and meet the second. With the full list, the client can mark every bad field in one round trip, and the support team sees the full picture in a bug report.
I cap the array, at around 50 items, so a malicious body with ten thousand broken fields cannot produce a huge response. And, as before, I leave out the echoed input values.
Q95 · Scenario. "Unhandled exceptions return stack traces in production. Fix it."
Reveal answer
Strong answer First a correction that surprises people: by default Starlette in production does not send a stack trace. The ServerErrorMiddleware returns the plain text Internal Server Error unless debug=True. If clients see traces, someone enabled debug mode, or an exception handler is formatting str(exc) or traceback.format_exc() into the body.
The fix has two sides. For the client: a catch-all @app.exception_handler(Exception) that returns a generic Problem Details body with a status of 500 and a request id. For the operator: the same handler logs the exception with its full traceback and the same request id, so support can start from the id the customer quotes.
Also check debug is off in production settings, that /docs does not expose internal schemas you would rather keep private, and that no error message includes SQL text or file paths (database driver errors are the usual leak).
One more reason to have the handler: as Q88 showed, an unhandled error response skips the CORS middleware, so browsers report a misleading CORS failure.
Picture it The same failing endpoint with and without a catch-all handler.
import logging
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
logging.basicConfig(level=logging.ERROR, format="LOG %(levelname)s %(message)s")
log = logging.getLogger("qb")
def make(handler: bool):
app = FastAPI()
@app.get("/boom")
def boom(): return {"v": 1 / int("0")}
if handler:
@app.exception_handler(Exception)
async def catch_all(request: Request, exc: Exception):
log.error("unhandled %s on %s", type(exc).__name__, request.url.path) # full trace goes to the LOG
return JSONResponse({"title": "Internal Server Error", "status": 500, "request_id": "r-123"}, status_code=500)
return app
for handler in (False, True):
r = TestClient(make(handler), raise_server_exceptions=False).get("/boom")
print(f"handler={handler}: {r.status_code} {r.headers['content-type']} body={r.text!r}")Make the invisible visible: Real output. The first line starting with LOG is the server-side log.
LOG ERROR unhandled ZeroDivisionError on /boom
handler=False: 500 text/plain; charset=utf-8 body='Internal Server Error'
handler=True: 500 application/json body='{"title":"Internal Server Error","status":500,"request_id":"r-123"}'What you see: Without the handler the body is bare text and nothing is logged by our code. With it the client gets JSON with a request id, while the log line (in a real app with the traceback attached) goes where only operators can read it.
Leaky
Debug output or str(exc) goes to the client.
@app.exception_handler(Exception)
async def h(req, exc):
# ❌ TRAP: internals in the body
return JSONResponse({"error": str(exc),
"trace": traceback.format_exc()}, 500)Safe
Generic body, detail in the log.
@app.exception_handler(Exception)
async def h(req, exc):
log.error("unhandled", exc_info=True,
request_id=rid(req))
return problem(req, 500,
"Internal Server Error",
"Quote the request_id.")The shift: The client gets an id, the log gets the story.
Land it I register a catch-all handler that logs the full exception with the request id and returns a generic problem body, with debug off in production.
- "Will the catch-all also catch errors in middleware?"
-
Not all of them. The catch-all handler sees exceptions that arise inside the endpoint and its dependencies, but some failures happen outside its reach.
An exception raised in one of your own middlewares that sit outside the exception-handling layer, or an error that occurs while a streaming response is already being sent, escapes to
ServerErrorMiddleware. That layer writes a plain-text 500 if it still can, and then re-raises the exception so the server process logs it.The consequence is that two different places can produce a 500. My handler produces the nice Problem body, with the request id and a logged traceback. The outer layer produces plain "Internal Server Error", and the only record is in the server's own error log.
So I do not rely on handler logs alone. I keep the uvicorn error log at error level, ship it to the same log store, and alert on its contents too.
It also explains why middleware should be small and defensive. Code in the middleware layer has fewer safety nets than code in endpoints.
- "How do tests see these 500s?"
-
Starlette's
TestClient, which FastAPI uses, re-raises unhandled server exceptions into the test by default. A bug therefore fails the test with a normal Python traceback instead of returning a quiet 500, which is what you want most of the time.When a test needs to check the response itself, to prove that the catch-all returns a generic body with no traceback and includes a request id, I create the client with
TestClient(app, raise_server_exceptions=False). The exception is then turned into a response as it would in production.The canonical
conftest.pydoes this in a dedicated fixture, so the setting is opt-in and visible. The tests that follow assert three things: status 500,content-typeofapplication/problem+json, and a body that contains no word from the exception message.That last assertion is the one that catches the original problem: someone adding
str(exc)to the body "just for debugging". - "How do you alert on these?"
-
I alert on rates, not on single events, and I send the detail to a tracker.
- Metric: count responses by route and status class, for example
http_requests_total{route="/v1/orders",status="5xx"}, as Q133 builds. - Alert rule: page when the 5xx ratio on a route exceeds a threshold, say 2 percent of requests for five minutes. One 500 in a million is normal and should not wake anyone.
- Error tracker: the same catch-all handler sends the exception to Sentry or a similar tool, tagged with the request id, route and release version. The tracker groups repeats and shows which deploy introduced a new error.
The pairing works because they answer different questions. The metric tells me something is wrong now and how big it is. The tracker tells me what and where. Logs, joined by request id, tell me the story of one failing request.
- Metric: count responses by route and status class, for example
- "What if the exception message itself is safe and useful?"
-
Then it should not be a 500. A 500 means "an unexpected bug on our side", and its text must be assumed unsafe. If an error is expected and its message is useful to the client, it belongs to the domain and gets its own status.
The test I apply is "can I name this failure in advance?". If yes, such as "out of stock", "restaurant closed", or "coupon expired", it becomes a domain exception, say
CouponExpired, with a status of 409 or 422 and a stable problem type. The message is then written by me, for clients, and reviewed as part of the API contract.That keeps the two kinds of errors clean. Domain errors are logged at info or warning without a traceback, and are not counted as incidents. Unknown exceptions are 500s, logged with a traceback, counted, and paged on.
If everything is a 500, the 5xx alert is full of expected business outcomes and real bugs become impossible to see.
Q96. "Validation errors (422) versus business errors (409 or 400) — how do you map them?"
Reveal answer
Strong answer The split is about who can fix it and with what information.
422 Unprocessable Content means the request was understood but its data is invalid on its own: a quantity of zero, a malformed email, a missing field. The server can decide this by looking only at the request. FastAPI produces it automatically from your Pydantic models.
409 Conflict means the request is well-formed but conflicts with the current state: the item sold out, the order is already delivered, the restaurant is closed. The same request might succeed a minute later. Only the server's data can decide this.
400 Bad Request is for a request that cannot even be parsed (broken JSON, a corrupt cursor). Some teams use 400 for rule violations as well; the important thing is to pick a rule, document it, and keep it consistent.
A practical test: if the answer depends on a database read, it is not a validation error. Pydantic validators should never query the database.
Picture it Five requests to one endpoint, each failing differently.
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
class DomainError(Exception): status = 400
class OutOfStock(DomainError): status = 409
class RestaurantClosed(DomainError): status = 409
class UnknownItem(DomainError): status = 422
app = FastAPI()
@app.exception_handler(DomainError)
async def dom(request, exc): return JSONResponse({"error": type(exc).__name__}, status_code=exc.status)
class Line(BaseModel):
item_id: int
qty: int = Field(gt=0, le=50)
@app.post("/v1/orders")
def create(line: Line):
if line.item_id == 404: raise UnknownItem()
if line.item_id == 1: raise OutOfStock()
return {"ok": True}Make the invisible visible: Real status codes.
{'item_id': 5, 'qty': 'two'} -> 422 ['int_parsing']
{'item_id': 5, 'qty': 99} -> 422 ['less_than_equal']
{'item_id': 404, 'qty': 1} -> 422 {'error': 'UnknownItem'}
{'item_id': 1, 'qty': 1} -> 409 {'error': 'OutOfStock'}
{'item_id': 5, 'qty': 1} -> 200 {'ok': True}Why: Text instead of a number and an out-of-range number are caught by Pydantic with int_parsing and less_than_equal. An unknown menu item and an out-of-stock item are domain decisions, raised from the service as UnknownItem (422 here, because the id itself is invalid input) and OutOfStock (409, because it depends on stock right now).
Everything is 400
The client cannot tell what to do.
# ❌ TRAP: one code for all failures
if qty <= 0 or stock < qty:
raise HTTPException(400, "bad request")Mapped by cause
Retry or fix is clear.
# 422 comes from the model automatically
if item.stock < line.qty:
raise OutOfStock(item.id) # 409The shift: The status code tells the client whether to fix the data or retry later.
Land it Anything decidable from the request alone is 422, anything that depends on current state is 409, and the whole mapping is documented once.
- "Is it 422 or 400 for a failed Pydantic validation?"
-
FastAPI returns 422 by default. Many public APIs, and many older clients, expect 400 for the same situation. Neither is wrong. What hurts is mixing them inside one API.
The default comes from the HTTP standard: 422 Unprocessable Content means the server understood the format of the request but could not process its content. A missing field in valid JSON fits that exactly. 400 is the general "bad request" code and was the common choice before 422 became widely supported.
If an existing client or API gateway expects 400, I do not change every route. I register one handler for
RequestValidationErrorand set the status there. One line then moves the whole API, and the OpenAPI document needs the matching change in its declared responses.Then I keep a clean split for the rest: 400 only for a body that cannot be parsed at all, such as broken JSON, a malformed cursor, or an unreadable file. I write the rule once in the API guide and keep it.
- "Which code for "restaurant is closed"?"
-
409 Conflict. The request is perfectly valid, and the current state of the world forbids it. That state can change: the restaurant opens at 11:00, so the same request might succeed in an hour.
The status alone does not tell the app what happened, so I add a stable problem type,
restaurant-closed, and perhaps an extension field such asopens_at. The mobile app switches on the type. It can show "Spice Garden opens at 11:00" and offer a "notify me when open" button instead of a generic error.Compare the alternatives. 422 would suggest that the data in the request is wrong, so the app might highlight a field and ask the user to change input that is fine. 403 suggests the customer is not allowed, which is not the case. 503 would suggest the whole service is down.
Choosing 409 with a precise type gives the client what it needs to behave helpfully, and the support team a clear label in dashboards.
- "Can a validator check "restaurant must be open"?"
-
Technically it can, but I would not let it. A validator is the wrong place for the check, for three reasons.
First, timing. A Pydantic validator runs while the request body is parsed, before the endpoint, the service, and the transaction exist. The restaurant could close one second after validation passes and the order would still go through, so the check proves nothing durable.
Second, atomicity. In the service, the "restaurant open" check and the stock decrement run inside the same transaction, so they see one consistent view. A validator cannot share that transaction.
Third, coupling. A model that needs a database session cannot be built in a unit test, in a script or in a message consumer without one. Models should be plain data with rules based on the data in front of them.
So Pydantic checks that
restaurant_idis a positive integer. The service checks that this restaurant exists and is open now. - "What status for "order already delivered, cannot cancel"?"
-
409 with the problem type
invalid-status-transition, as the canonicalInvalidTransitionerror does. The request is fine, but the order's current state, delivered, forbids cancelling it. Nothing the client changes in the request will fix it. Only the state matters.The test I use is "if the client re-reads and decides again, can the answer change?". If the app refreshes and sees the order is already delivered, it hides the cancel button. That is the 409 pattern: the client's picture of the state was out of date, or the action was never available.
A different case is when the operation is forbidden for this caller by policy regardless of state, for example a customer trying to mark an order as delivered, which only riders may do. That is authorisation, and 403 fits better.
In the body I include the current status and the allowed transitions, so the client does not need a second call to learn what it may do.
Q97. "How do you log errors with enough context without leaking personal data?"
Reveal answer
Strong answer Good error logs answer five questions without a single secret: which request (request id), who (a customer id, not a name or email), what (route, order id), why (exception class, message) and when (timestamp). Everything else is a risk.
Rules I apply. Log structured JSON (structlog), so fields can be searched. Log identifiers, not personal data: customer_id=7 rather than a phone number. Never log tokens, passwords, card numbers, full request bodies or Authorization headers.
Enforce this by machine, not by habit. A structlog processor can redact known sensitive keys and mask email patterns inside messages before anything is written. Pair it with a rule that logs are not the place to debug with real customer payloads.
Exceptions carry traps of their own: str(exc) from a database driver may include the failing SQL and its parameter values, and a validation error may echo user input. Log the class name and your own safe fields.
Picture it A redaction processor and two log calls that would otherwise leak a phone number, an authorisation header and an email address.
import re, structlog
SENSITIVE = {"password", "authorization", "card_number", "phone", "email"}
def redact(logger, name, event):
for k in list(event):
if k.lower() in SENSITIVE: event[k] = "[redacted]"
elif isinstance(event[k], str):
event[k] = re.sub(r"[\w.+-]+@[\w-]+\.[\w.]+", "[email]", event[k])
return event
structlog.configure(processors=[redact, structlog.processors.add_log_level,
structlog.processors.JSONRenderer(sort_keys=True)],
logger_factory=structlog.PrintLoggerFactory())
log = structlog.get_logger()
log.info("order_failed", request_id="r-9f2", order_id=881, customer_id=7, error="OutOfStock",
authorization="Bearer eyJhbGciOi...", phone="+91 98765 43210")
log.warning("login_rejected", request_id="r-9f3", detail="no account for ravi@example.com")Make the invisible visible: Real JSON lines.
{"authorization": "[redacted]", "customer_id": 7, "error": "OutOfStock", "event": "order_failed", "level": "info", "order_id": 881, "phone": "[redacted]", "request_id": "r-9f2"}
{"detail": "no account for [email]", "event": "login_rejected", "level": "warning", "request_id": "r-9f3"}Why: The identifiers and the error class survive, so the line is still useful for tracing. The header and phone are replaced by a marker, and an email address hidden inside free text is masked by the pattern. Sorting keys makes the lines easy to compare in tests.
Logs everything
One line, many risks.
# ❌ TRAP: whole request in the log
log.error("order failed",
body=await request.json(),
headers=dict(request.headers))Logs identifiers
Searchable and safe.
# ✅ ids and the reason
log.error("order_failed",
request_id=rid, customer_id=u.id,
order_id=oid,
error=type(exc).__name__)The shift: Log enough to find the record, never enough to be the record.
Land it I log structured identifiers with the request id, and a redaction processor removes sensitive keys so safety does not depend on every developer remembering.
- "Isn't a customer id also personal data?"
-
Yes, under privacy law an id that points to a person is still personal data. Regulations such as GDPR call it pseudonymous data: it does not name the person, but anyone with the mapping table can identify them. So it is not free of obligations. It is, however, much lower risk than a name, phone number or email.
The practical benefit is control. If a log line says
customer_id=7, a leak of the logs reveals nothing about who 7 is without the customer table. And when a customer asks for erasure, I delete or anonymise the row in the customer table, and the old log lines become effectively anonymous.Three habits keep this honest. Short log retention, days to a few weeks rather than years, so there is little to leak or to erase. Restricted access to the log store, since it is a data store like any other. And documenting in the privacy notice that operational logs contain customer ids.
Logging ids rather than content is a risk reduction, not an exemption.
- "How do I debug a failure without the payload?"
-
I log everything about the failure except the sensitive values themselves, then use identifiers to reach the data if I truly need it.
For a validation failure I log the field locations and the rule names:
lines.0.quantity: greater_than_equal. That tells me what was wrong without storing what the user typed. I add the ids of the rows involved, such as order id and restaurant id, so I can open the records in the database under proper access controls. For large or sensitive fields, I log a length or a hash. Two requests with the same hash are identical, and I never see the content.For the rare bug that only reproduces with the real payload, I use a temporary, access-controlled capture, switched on for one customer or route, with an expiry of hours and a record of who enabled it. That is better than permanent body logging, which keeps every payload forever and is hard to audit.
- "Should I log at the endpoint or in one place?"
-
I log unexpected failures in one place, the catch-all handler, with the traceback. Expected domain errors get a single info or warning line with no traceback, and are not logged again anywhere else.
The problem with logging in every layer is duplication. If the repository logs the exception, then the service logs it again while re-raising, then the endpoint logs it a third time, one failure produces three entries. Counting "errors per hour" is now off by a factor of three, and engineers searching the logs see three tracebacks and assume three problems.
The approach I follow: lower layers raise and do not log. They add context to the exception where useful, such as the order id. The outermost handler logs once, with the request id, user id, route and traceback.
Logging at lower layers is still right when something is handled and swallowed, such as retrying a call. Then nobody above sees it, so it is logged where it is dealt with.
- "What log level for a rejected token?"
-
Warning, with the exception class only, as the canonical
security.pydoes. A rejected token is expected traffic, not a defect in my code.Think about what each level should mean. Error is for "something in my system broke and someone should look". A client sending an expired token is the system working correctly: it noticed and refused. If every expired token were an error, a mobile release with a refresh bug could flood the error log and bury real incidents.
Info would be too quiet, though. A rejected token can also be the first sign of an attack, so I want the entry visible and countable.
So the log line is at warning level, carrying the reason class, the
kidand the request id. A metric counts rejections by reason. I alert on a burst, for instance invalid signatures jumping from near zero to hundreds in a minute, since that suggests probing, while a steady background of expired tokens is ignored.
Q98 · Scenario. "A slow downstream service makes your endpoint hang for 60 seconds. Fix it."
Reveal answer
The real test Whether you set explicit timeouts on every outbound call and think about a total deadline, not just one call.
Strong answer The hang is a missing timeout. Many HTTP clients default to no limit (some libraries wait forever), and a server's own default may be 60 seconds. Every request waiting on the slow service also holds a worker slot, a database connection if you opened one, and memory, so one slow dependency turns into a full outage.
Fix it in four layers. First, an explicit timeout on every client: in httpx, Timeout(connect=1.0, read=2.0, write=2.0, pool=1.0). Four separate limits matter because a dead host fails at connect, a hung one at read, and an exhausted connection pool at pool.
Second, a deadline for the whole endpoint with asyncio.timeout(), since three calls of 2 seconds each still take 6. Third, a fallback decision: fail fast with 503 or 504, return cached data, or degrade a feature. Fourth, retries and a circuit breaker (Q99) so a failing service is not hammered.
Timeouts must also be shorter as you go down the chain: the client's timeout is longer than the gateway's, which is longer than your calls. Otherwise the caller gives up while your work continues unseen.
Picture it A "downstream" that accepts the connection and never answers, tested through a real socket, because the in-memory test transport has no network and ignores timeouts.
import asyncio, time, httpx
async def silent(reader, writer): # accepts the TCP connection, then never answers (a hung downstream)
await asyncio.sleep(5)
async def main():
server = await asyncio.start_server(silent, "127.0.0.1", 9911)
timeout = httpx.Timeout(connect=1.0, read=0.3, write=1.0, pool=1.0)
async with httpx.AsyncClient(base_url="http://127.0.0.1:9911", timeout=timeout) as c:
t = time.perf_counter()
try:
await c.get("/charge")
except httpx.TimeoutException as e:
print(f"httpx Timeout(read=0.3): {type(e).__name__} after {time.perf_counter()-t:.2f}s")
t = time.perf_counter() # one deadline for the whole endpoint, across several calls
try:
async with asyncio.timeout(0.5):
async with httpx.AsyncClient(base_url="http://127.0.0.1:9911", timeout=None) as c:
await c.get("/charge")
except TimeoutError:
print(f"asyncio.timeout(0.5) : TimeoutError after {time.perf_counter()-t:.2f}s")
server.close()
asyncio.run(main())Make the invisible visible: Per-call timeout and an overall deadline.
httpx Timeout(read=0.3): ReadTimeout after 0.34s
asyncio.timeout(0.5) : TimeoutError after 0.50sWhy: The read timeout fires after 0.3 seconds, not 60, and raises httpx.ReadTimeout, a subclass of TimeoutException. The asyncio.timeout(0.5) block cancels the whole operation at 0.5 seconds regardless of how many calls were inside it.
No timeout
Waits as long as the other side likes.
# ❌ TRAP: default / unbounded wait
async with httpx.AsyncClient(
timeout=None) as c:
r = await c.post(URL, json=body)Explicit limits
Four timeouts plus a deadline.
t = httpx.Timeout(connect=1, read=2,
write=2, pool=1)
async with asyncio.timeout(3):
r = await client.post(URL, json=b)
# client built once, timeout=tThe shift: Every wait on something you do not control gets a number.
Land it Every outbound call gets explicit connect, read and pool timeouts, the endpoint gets one overall deadline, and I decide in advance what the user sees when it fires.
- "Which status do I return when the downstream times out?"
-
It depends on who is responsible for the failure, and the two codes tell the client different things.
- 504 Gateway Timeout: my service is acting as a gateway or proxy to a specific upstream and that upstream did not answer in time. It says "the delay is upstream".
- 503 Service Unavailable: I cannot serve this right now, and trying again later may work. With a
Retry-Afterheader it tells the client how long to wait, and it fits for a breaker that is open or an overloaded dependency.
I would not use 500. A 500 says "unexpected bug in this service", which sends my own team on a wrong hunt, drowns real defects in the dashboard, and tells the client nothing about whether to retry.
Which of 503 and 504 I choose matters less than being consistent and documenting it. For QuickBite I use 503 with
Retry-After: 2for dependency timeouts, so clients use the same retry logic for all temporary failures. - "What does
asyncio.timeoutdo to the work inside?" -
It cancels the task running inside the block. The cancellation arrives inside the awaited call as
CancelledError, which gives the code a chance to clean up. When the block exits, the error surfaces outside as aTimeoutError.That gives two practical rules. First, do cleanup in
finallyblocks orasync with, not in atry/except Exception, since in modern PythonCancelledErroris not a subclass ofExceptionand ordinary handlers will not see it. Second, never swallowCancelledError. Catch it only to clean up, then re-raise, or the timeout silently stops working.The big limit is that it can only interrupt at an
await. If the code inside calls blocking functions, such astime.sleep(30)orrequests.get, in an async function, the event loop is stuck, the timeout cannot fire until that call returns, and every other request is stuck behind it too.So the timeout protects awaits, and the rule remains: no blocking calls on the event loop.
- "What about blocking clients such as
requestsin a plaindefendpoint?" -
Pass
timeout=(connect, read)on every call.requestshas no default timeout, which means a hung server can hold the call forever, and forgetting it is the most common cause of mysterious hangs.A plain
defendpoint runs in AnyIO's thread pool, which has 40 threads by default. A blocked call occupies one thread until it returns. Do the arithmetic: if a downstream hangs for 30 seconds and 40 requests arrive in that time, all 40 threads are blocked on it, and the 41st request, even for a completely different endpoint that is perfectly healthy, waits in the queue for a free thread.That is how one slow partner takes down unrelated routes. The timeout puts a ceiling on how long a thread can be held: with a read timeout of 2 seconds, those 40 threads recover within seconds.
Where slow calls are common, an async client such as httpx is the better fix, since waiting costs a small task rather than a whole thread.
- "How do I pick the numbers?"
-
I start from measured behaviour of the dependency and the time my own endpoint is allowed to take, then work backwards.
Take a worked example. The downstream normally answers in 200 ms, with a p99 of 400 ms, which means 99 requests in 100 are faster than that. My endpoint has a service level objective of finishing within 2 seconds.
- Read timeout: about twice the downstream's p99, so 800 ms. Nearly every healthy call completes, and a stuck call is cut off quickly.
- Retry: one retry of an idempotent call, after a short jittered pause of about 100 ms.
- Total budget: 800 + 100 + 800 = 1,700 ms, which fits inside the 2 seconds with a little left for my own work.
I then watch the actual timeout rate in metrics. If more than about 1 percent of calls time out, either the number is too tight or the dependency has a problem, and the metric tells me which one to examine.
Q99. "Retries and circuit breaking for outbound calls in Python."
Reveal answer
Strong answer A retry repeats a failed call, hoping the failure was momentary. A circuit breaker stops calling a service that keeps failing, so it can recover and your own workers are not tied up waiting on it. They work together: retries handle blips, the breaker handles outages.
Rules for retries. Retry only idempotent calls (GET, or POST with an idempotency key), and only on transient errors: timeouts, connection errors, 502, 503, 504, 429. Never retry a 400 or 422, which will fail the same way. Use exponential backoff with jitter so a thousand clients do not all retry at the same instant, and cap attempts at three or four. Respect Retry-After.
In Python, tenacity gives retries as a decorator. For a breaker, there are small libraries (pybreaker, aiobreaker), or write a few lines yourself, as below. A breaker has three states: closed (calls pass), open (calls fail immediately), and half-open (one trial call after a cool-down decides which way to go).
Retries multiply load. Three attempts on every call during an outage triples the traffic to a service that is already struggling, which is another reason for the breaker.
Picture it A flaky call that succeeds on the third try, and a tiny breaker that opens after three failures.
import time
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
class Flaky(Exception): pass
calls = {"n": 0}
def fake_payment_status(): # an idempotent GET: fails twice, then works
calls["n"] += 1
if calls["n"] < 3: raise Flaky("503")
return "paid"
@retry(retry=retry_if_exception_type(Flaky), stop=stop_after_attempt(4),
wait=wait_exponential_jitter(initial=0.05, max=0.5, jitter=0.05), reraise=True)
def get_status(): return fake_payment_status()
print("retry result:", get_status(), "after", calls["n"], "calls")
class Breaker:
def __init__(self, threshold=3, reset_after=0.3): self.fail, self.t, self.th, self.reset = 0, 0.0, threshold, reset_after
def call(self, fn):
if self.fail >= self.th and time.monotonic() - self.t < self.reset:
raise RuntimeError("circuit open: failing fast, no call made")
try:
r = fn(); self.fail = 0; return r
except Flaky:
self.fail += 1; self.t = time.monotonic(); raise
b = Breaker(); down = lambda: (_ for _ in ()).throw(Flaky("503"))
for i in range(1, 6):
try: b.call(down)
except Exception as e: print(f"call {i}: {type(e).__name__}: {e}")
time.sleep(0.35)
print("after cool-down:", b.call(lambda: "paid"))Make the invisible visible: Real output.
retry result: paid after 3 calls
call 1: Flaky: 503
call 2: Flaky: 503
call 3: Flaky: 503
call 4: RuntimeError: circuit open: failing fast, no call made
call 5: RuntimeError: circuit open: failing fast, no call made
after cool-down: paidWhat you see: tenacity retried twice with growing, jittered waits and returned paid on the third call. The breaker let three failures through, then answered the fourth and fifth calls instantly with no call made, and after the cool-down it allowed a trial that succeeded.
Naive loop
Hammers a struggling service.
# ❌ TRAP: fixed delay, every error
for _ in range(10):
try: return call()
except Exception:
time.sleep(1)tenacity
Backoff, jitter, limits.
@retry(
retry=retry_if_exception_type(Transient),
stop=stop_after_attempt(4),
wait=wait_exponential_jitter(initial=0.2),
reraise=True)
def get_status(): ...The shift: Retry only what is safe and transient, spread the retries out, and stop.
Land it I retry only idempotent calls on transient errors with jittered backoff and a small cap, and wrap fragile dependencies in a breaker so an outage fails fast.
- "How do I retry a POST safely?"
-
Send an
Idempotency-Keyheader, so the server can recognise a repeat of the same request and return the original result instead of doing the work twice. The order endpoint works this way.The danger without it is a timeout. The client sends a POST, the server creates the order and charges the card, but the response is lost on the way back. The client sees a timeout and retries. It cannot tell whether the first request failed or merely went unanswered, and a naive server creates a second order and a second charge.
With a key, the client generates a unique value, usually a UUID, once per logical action and sends the same value on every retry. The server stores the key with a hash of the request body. A repeat with the same key and the same body gets the stored response, and the canonical app marks it with
Idempotent-Replayed: true. A repeat with the same key and a different body gets 422.That makes retrying a POST as safe as retrying a GET.
- "Where should retries live: client library, service or gateway?"
-
In one layer only, because retries multiply across layers. If the client library makes 3 attempts, the gateway makes 3 per attempt, and the service makes 3 per call, one user action can turn into 3 x 3 x 3 = 27 calls to the struggling dependency, at the worst possible time.
Each location has strengths. A gateway or service mesh retry covers every client without changes, but it knows nothing about idempotency and cannot alter the request. An application-level retry knows which calls are safe, can add an idempotency key, read
Retry-After, and decide that a 422 should never be retried.My preference is application-level retries for outbound calls from my service, with the mesh and gateway retries switched off or limited to connection failures that never reached the server. For calls arriving from outside, the clients own their own retry policy.
Whatever I choose, it goes into the architecture notes with the layer named, so no one adds a second one by accident.
- "What is a retry budget?"
-
A retry budget is a cap on the share of traffic that may be retries, for example 10 percent of the requests sent in the last minute. When the budget is used up, further failures are not retried, and the caller fails fast.
It exists because per-request retry limits, such as "three attempts", do not stop storms. Suppose a dependency starts failing for everyone. Every request now sends up to three calls, so the load on the already struggling service triples, which makes it fail more, which creates more retries. A short blip becomes a long outage.
With a 10 percent budget, at 1,000 requests per second the service sends at most 100 retries per second, so load rises by at most 10 percent however bad the failure is. The remaining failures surface quickly, which also lets the breaker open sooner.
Envoy, Linkerd and gRPC clients offer this as a setting. In Python I would implement it with a small counter shared by the client wrapper, or leave it to the mesh.
- "What does the user see when the breaker is open?"
-
An honest answer, fast. The point of the breaker is that the user gets a result in milliseconds instead of waiting for a timeout of several seconds on a service known to be failing. What the result is depends on the feature, and I decide it per feature ahead of time.
- Cached value: for read data that changes slowly, such as the menu, return the last known copy and mark it as possibly stale.
- Degraded feature: show the menu without live stock levels, or skip loyalty points and say they will be added later.
- Fail fast: for something that cannot be faked, such as payment, return 503 with
Retry-Afterand a Problem body that the app can turn into "payments are unavailable, try again in a minute".
The part people forget is the half-open state. After the cool-down, one trial call tests recovery, and the others keep failing fast until it succeeds. Without that, either the breaker never closes or all traffic returns at once.
Q100. "Which status code for: created, accepted for later, conflict, rate limited, temporarily unavailable?"
Reveal answer
Strong answer The five answers are 201, 202, 409, 429 and 503. What makes it a senior answer is the header that goes with each.
- 201 Created: a new resource now exists. Send
Location: /v1/orders/881and return the new representation. FastAPI:status_code=201on the route. - 202 Accepted: the work is queued, not done. Return a status resource URL in
Locationand optionallyRetry-After(Q105). - 409 Conflict: the request clashes with current state, such as out of stock or a stale version. The body should say what to do.
- 429 Too Many Requests: the caller is over its limit. Always send
Retry-Afterin seconds. - 503 Service Unavailable: you or a dependency cannot serve right now. Send
Retry-Afterif you know how long. The readiness probe uses it to take a pod out of rotation.
Also know the neighbours: 200 for a successful read or update with a body, 204 for success with no body (DELETE), 304 for an unchanged conditional GET, 412 when an If-Match check fails, 422 for invalid data.
Picture it A tiny app that returns each of the code-and-header pairs.
from fastapi import FastAPI, Response, status
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/v1/orders", status_code=201)
def create(response: Response):
response.headers["Location"] = "/v1/orders/881"; return {"id": 881}
@app.post("/v1/reports", status_code=202)
def report(response: Response):
response.headers["Location"] = "/v1/reports/jobs/5"; return {"job": 5, "status": "queued"}
@app.delete("/v1/orders/{oid}", status_code=204)
def delete(oid: int): return Response(status_code=204)
@app.get("/v1/limited")
def limited(): return JSONResponse({"title": "Too Many Requests"}, 429, headers={"Retry-After": "30"})
@app.get("/readyz")
def ready(): return JSONResponse({"ready": False}, 503, headers={"Retry-After": "5"})
c = TestClient(app)
for m, p in [("post", "/v1/orders"), ("post", "/v1/reports"), ("delete", "/v1/orders/881"), ("get", "/v1/limited"), ("get", "/readyz")]:
r = getattr(c, m)(p); h = {k: v for k, v in r.headers.items() if k in ("location", "retry-after")}
print(f"{m.upper():6} {p:16} -> {r.status_code} {h} body={r.text!r}")Make the invisible visible: Five calls.
POST /v1/orders -> 201 {'location': '/v1/orders/881'} body='{"id":881}'
POST /v1/reports -> 202 {'location': '/v1/reports/jobs/5'} body='{"job":5,"status":"queued"}'
DELETE /v1/orders/881 -> 204 {} body=''
GET /v1/limited -> 429 {'retry-after': '30'} body='{"title":"Too Many Requests"}'
GET /readyz -> 503 {'retry-after': '5'} body='{"ready":false}'Why: Each response shows the status, the header a client acts on, and the body. The 204 has an empty body by definition; sending a body with 204 is a protocol violation that some proxies break on.
Everything is 200
Errors hidden in the body.
# ❌ TRAP: the client must parse the body
return {"ok": False, "error": "limit"}Honest codes
Clients and proxies understand.
return JSONResponse(
{"title": "Too Many Requests"}, 429,
headers={"Retry-After": "30"})The shift: The status line is the contract that generic clients, caches and monitors read.
Land it I use 201 with Location, 202 with a status URL, 409 for state conflicts, 429 with Retry-After and 503 for temporary unavailability.
- "When do I use 200 versus 201 for a POST?"
-
By the rule: 201 when the POST created a resource with its own URL, and 200 when the POST was an action that returned a result without creating anything you can address later.
Creating an order is 201. There is now a thing at
/v1/orders/881, and the response carriesLocation: /v1/orders/881so the client can fetch it. A POST to/v1/quotes/pricethat calculates a delivery fee and stores nothing is 200, since there is no new resource to point to. The same goes for a validation dry run or a search done by POST because the query is too long for a URL.Replays are the subtle case. When the same idempotency key is sent again, the canonical app returns the stored response with 200 and
Idempotent-Replayed: true. The client can tell that the second call did not create a second order. Some teams repeat 201 for replays, and that is also valid if documented.The status describes what this call did, so I choose the one that tells the client the truth.
- "400, 422 or 409 for a duplicate email at signup?"
-
My choice is 409 with a field-level pointer, and I accept that many teams choose 422. Both are defensible if documented.
The argument for 409 is that the data is valid on its own: the email is well-formed and the length is fine. What forbids it is state, an existing account. That matches the definition of conflict, and it is what a duplicate username returns in many well-known APIs.
The argument for 422 is form handling. Signup forms want to highlight the email field and say "already registered", and a 422 with an
errorsentry foremailfits the same shape as other field errors.There is no need to choose one over the other entirely. A 409 can carry the same
errorsarray with the field name, so the form works the same way.One security note: telling a stranger that an email is registered lets them probe for accounts. For signup I accept it, but for password reset I always answer the same way.
- "Which code when the user is blocked, not rate limited?"
-
403 Forbidden, with a specific problem type such as
account-suspended. The request is understood and the caller is known, but this account is not allowed to proceed.The difference from 429 is what the client should do. 429 means "you are going too fast, wait and try again", and the
Retry-Afterheader says how long. The condition clears itself. A suspended account will not become active by waiting, so a retry loop would just repeat the error.The problem type matters a great deal here. The app can map
account-suspendedto a screen with a support contact link, whilemissing-scopeshows "you do not have access". Without it, both look like a plain 403.On a login attempt for a suspended account, I still take care about what is revealed. After the credentials are verified, a clear message helps the honest user. Before that, I return the generic failure, so strangers cannot learn which accounts are suspended.
- "What do 502 and 504 mean for an API behind a gateway?"
-
They are the gateway codes: 502 Bad Gateway means the upstream sent an invalid response, and 504 Gateway Timeout means the upstream did not answer in time. Both are about a server that was acting as a middleman, a proxy, a load balancer or an API gateway, and its upstream.
A concrete picture: the gateway forwards a request to the orders pod. If the pod crashes mid-request and the connection resets, the gateway returns 502. If the pod accepts the request but takes longer than the gateway's timeout, say 30 seconds, the gateway returns 504. Your own code produces them too, when it proxies to another service and gets garbage or silence.
Monitor them separately from 500. A rise in 500 points at a bug in my code. A rise in 502 and 504 points at the thing behind the gateway: a crashing deployment, an overloaded service or a slow dependency. Different causes, different people to call, and different runbooks.
I chart the three on one panel with separate lines.
Q101 · Scenario. "An exception inside a BackgroundTask disappears. Why?"
Reveal answer
Strong answer It does not vanish, but it does not reach the client either. BackgroundTasks run after the response has been sent, in the same process. By the time the task fails, the client already holds a 200 or 201 and the connection is finished. There is nobody to receive an error, and no exception handler can change a response that has already gone.
The traceback goes to the server's error log (uvicorn logs it as "Exception in ASGI application"), which is easy to miss if nobody watches it. The task is not retried, and the order the client was told succeeded has no confirmation email.
The fixes follow from that. Wrap the task body in your own try/except that logs with the request and order ids and increments an error metric. For work that must happen, do not use BackgroundTasks: write an outbox row in the same transaction as the order and let a worker retry (Q127).
One testing note: TestClient waits for background tasks to finish before returning, so tests see their side effects, and with the default settings a task error is re-raised to the test, which is not what a real server does.
Picture it A real uvicorn server (started in a thread), one POST, and the log it produces.
import threading, time, httpx, uvicorn
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def send_email(order_id: int): raise ConnectionError("smtp.example:25 refused")
@app.post("/v1/orders", status_code=201)
def create(bg: BackgroundTasks):
bg.add_task(send_email, 881)
return {"id": 881}
server = uvicorn.Server(uvicorn.Config(app, port=8766, log_level="info"))
threading.Thread(target=server.run, daemon=True).start()
while not server.started: time.sleep(0.05)
r = httpx.post("http://127.0.0.1:8766/v1/orders")
print("CLIENT SAW:", r.status_code, r.json())
time.sleep(0.3); server.should_exit = True; time.sleep(0.3)Make the invisible visible: The client output and the relevant server log lines (the traceback is about 45 frames long; the middle is cut).
INFO: 127.0.0.1:58450 - "POST /v1/orders HTTP/1.1" 201 Created
ERROR: Exception in ASGI application
... (about 40 more frames from uvicorn, FastAPI and Starlette)
File "/home/iam100god/Desktop/AI_COURSE/.venv/lib/python3.12/site-packages/starlette/background.py", line 36, in __call__
File "/home/iam100god/Desktop/AI_COURSE/.venv/lib/python3.12/site-packages/starlette/background.py", line 23, in __call__
File "/home/iam100god/Desktop/AI_COURSE/code/e20-python-api/E/bg_exception.py", line 5, in send_email
def send_email(order_id: int): raise ConnectionError("smtp.example:25 refused")
ConnectionError: smtp.example:25 refused
CLIENT SAW: 201 {'id': 881}What you see: The log shows POST /v1/orders 201 Created first, then the error, in that order. The last line, printed by the client, is 201 as well: it never learned about the failure.
Fire and forget
Failure is only a log line.
def send_email(order_id):
smtp.send(...) # ❌ raises, nobody told
bg.add_task(send_email, order.id)Observed task
Failure is logged, counted, retried.
def send_email(order_id):
try: smtp.send(...)
except Exception:
log.error("email_failed", order=order_id)
METRIC.inc() # and outbox retriesThe shift: Background work has no caller to complain, so it must report its own failures.
Land it A background task runs after the response, so its exception can only reach the log; I log and count it inside the task and use an outbox for anything that must not be lost.
- "Are sync and async background tasks handled differently?"
Yes, they are handled differently, and the difference matters for how a failure looks. A plain
deftask is run in the threadpool (a pool of worker threads that Starlette keeps so blocking code does not freeze the server). Anasync deftask is awaited directly on the event loop, the single thread that serves every request in that worker.In the log you can tell them apart: the traceback of a failed sync task passes through
run_in_threadpool, while an async one does not. Both are still run after the response has been sent, so both fail silently from the client's point of view.The trap is putting blocking work, such as a slow
requests.getor a big file write, inside anasync deftask. That blocks the loop and stalls every other request on the worker, exactly the problem from Q4. The threadpool is limited too: AnyIO's default limiter allows 40 threads at once, so a flood of slow sync tasks can queue up behind each other.My rule: use
deffor blocking work,async defonly when every call inside is awaited, and log failures in both.- "What if the server is killed while the task runs?"
The task is lost, and nothing brings it back. What happens depends on how the process dies.
On a normal stop (SIGTERM, which is what a deploy or
kubectl delete podsends first), uvicorn stops taking new connections and waits for running work within its graceful-shutdown window. It logs "Waiting for background tasks to complete" while it waits. If the task finishes inside the window, nothing is lost. If the window is shorter than the task, the task is cancelled halfway.On SIGKILL, an out-of-memory kill or a crash, nobody waits at all, so the task simply stops where it was. A pod that Kubernetes kills after its grace period (30 seconds by default) is the usual real-world case.
Nothing retries a lost task, because the client already got its success response and the task is not stored anywhere. So I judge by the cost of losing it: for a confirmation email or a payment capture that cost is real, and I write an outbox row in the same transaction instead (Q127).
- "Can I make a task report errors to an error tracker?"
Yes, and it is worth doing, but it needs one extra step to be useful. There are three parts.
- Initialise the tracker: Sentry's FastAPI integration, for example, hooks the ASGI app (the standard interface between a Python server and its app), so an exception that escapes a background task is captured with its stack trace and request details.
- Add business ids: a stack trace says where the code failed, not which order. I add
logger.exception("confirmation failed", extra={"order_id": order_id})inside the task so the report can be searched by order. - Count it: I increment a metric such as
background_task_errors_totallabelled by task name, and alert when the rate is above zero for a few minutes. Trackers can drop events under load, a counter does not.
Together these turn a silent failure into a page someone sees. They still do not retry the work, so for anything that must happen I keep the outbox as well.
- "When is
BackgroundTasksa fine choice?" It is a fine choice when the work is cheap, best-effort and harmless to lose. Examples are warming a cache, writing an analytics event, deleting a temporary file or pinging a search index that will be rebuilt anyway. If the process dies in the middle, the next request or the next nightly job repairs things.
It is also convenient because there is no extra infrastructure: no queue, no worker, no deployment. The task runs in the same process, with the same imports and settings, right after the response goes out.
The test I apply is one question: "if this is lost, who notices, and what does it cost?" If the answer is "nobody", BackgroundTasks is fine. If the answer is a missing receipt, a double charge or an unhappy customer, I use an outbox row plus a worker, which retries on failure and survives restarts.
I also keep the task short. A task that runs for minutes will meet a deploy sooner or later, and the graceful-shutdown window will not cover it.
Q102 · Design. "Design the error-handling layer for a service with 40 endpoints and three downstream dependencies."
Reveal answer
Strong answer I design it as four small pieces so that endpoints contain no error formatting at all.
- One error vocabulary: a base
DomainErrorwithstatus,slugandtitle, plus subclasses such asOutOfStock(409) andOrderNotFound(404). Services raise these and nothing else. - Four registered handlers: validation (422), Starlette
HTTPException,DomainError, andException(500). All return RFC 9457 problems with the request id through one helper. - A dependency gateway per downstream: payments, maps and notifications each get one client class with explicit timeouts, retries only for idempotent calls, a circuit breaker, and an error translation: low-level
httpxerrors becomeDownstreamUnavailableorDownstreamTimeout, mapped to 503 or 504. - Observability hooks: every handler logs with the request id, bumps a counter labelled by route and problem type, and the 5xx rate pages a human.
The three downstreams do not fail alike. Payments must fail closed (no order without a charge), the menu image service can fail open (show a placeholder), notifications can be deferred to an outbox.
Picture it A small matrix is the design artefact I would put on the whiteboard.
| Dependency | Timeout and retry | When it is down | Status to client |
|---|---|---|---|
| Payments | read 3 s, retry idempotent calls twice | fail closed, no order is created | 503 + Retry-After |
| Maps / ETA | read 1 s, no retry | show the order without an ETA | 200 (degraded) |
| Notifications | queued through the outbox | order succeeds, message retried later | 201 |
Everything else is unexpected, becomes a 500 with a request id, and is logged with its traceback.
Per-endpoint try/except
Forty ways to format an error.
@router.post("")
def create(...):
try: ...
except StockError:
return JSONResponse(..., 409)
except Exception as e:
return {"error": str(e)}Layered
One mapping, forty clean endpoints.
@router.post("")
def create(body, svc=Depends(get_service)):
return svc.create_order(body)
# errors raised in svc are mapped by
# handlers registered once in errors.pyThe shift: Endpoints describe the happy path; the error layer owns everything else.
Land it Domain exceptions, four registered handlers, one gateway class per downstream with its own timeout and fallback policy, and metrics on every error type.
- "How do you test the error layer?"
I test it in layers, so each piece of the error design has a check that fails when someone changes it.
- One test per handler: build a tiny app with one route per exception type (validation,
HTTPException, a domain error, a bareException) and assert the status, theapplication/problem+jsoncontent type and the body fields:type,title,status,request_id. - One contract test per domain error: call the real route that raises
OutOfStockorOrderNotFoundand check the exact status and slug. This catches a service that stops raising the right error. - The generic 500 test: make a route raise
RuntimeError("password=hunter2")and assert the response says only "Internal Server Error" and a request id, never the exception text. Useraise_server_exceptions=FalseonTestClient, or the exception is re-raised into the test.
I also add a downstream test per gateway: a fake that times out must give 504, and one that refuses connections must give 503.
- One test per handler: build a tiny app with one route per exception type (validation,
- "How do you stop engineers from raising
HTTPExceptioneverywhere anyway?" Rules written in a wiki do not hold, so I make the build fail instead. There are two levels.
The cheap level is a review checklist and a lint rule. The rule says
HTTPExceptionmay be imported only in routers and dependencies, the HTTP edge. Ruff's banned-import setting (flake8-tidy-imports) can enforce a per-folder ban with a few lines of configuration.The stronger level is an architecture test that runs with the other tests. It imports every module in the
servicesandrepositoriespackages and walks their imports, asserting that none of them reachesfastapiorstarlette. When an engineer addsraise HTTPException(404)to a service, the test fails in CI with the file name.The reason behind the rule is that a service raising HTTP statuses cannot be reused from a worker or a command-line script, and its tests need an HTTP vocabulary they should not know. With domain errors, one handler decides the status in one place.
- "How are errors from the database mapped?"
The repository or service catches the specific database exception it understands and turns it into a domain error with a meaning. For a unique-constraint violation, SQLAlchemy raises
IntegrityError; the code looks at which constraint failed and raisesDuplicateEmailorIdempotencyConflict, which the handler maps to 409 or 422.Everything else stays a 500. A deadlock, a lost connection or a syntax error is not something the caller can fix, so the generic handler logs it with the request id and returns a safe message. Retrying a deadlock once inside the repository is reasonable, but the retry belongs in the repository, not in the handler.
Mapping a raw database error to an HTTP status inside a global handler would couple the web layer to the schema: the handler would need to know constraint names. It would also leak information, since a constraint name tells an attacker what the tables look like.
I also check the constraint name, not just the exception class, because one
IntegrityErrorcan mean a duplicate, a missing foreign key or a null.- "What about errors after streaming starts?"
Once the first bytes of a streaming response have been sent, the status line and headers are gone. The status is fixed at 200 forever, so an exception raised later cannot become a 500 and no exception handler can rewrite it.
What can happen is limited. The server can close the connection abruptly, which the client sees as a truncated body or a network error. Or, with server-sent events, it can send an in-band error event such as
event: errorwith a small payload and then end the stream, and the client code decides what to do.That is why I do the risky work before streaming begins. Authenticate, validate parameters, check that the order exists and that the user may see it, and open the database query so that a missing row is still a clean 404. Only then return the
StreamingResponse.Inside the generator I wrap the loop in
try/finallyso cleanup always runs, log the failure with the request id, and make clients treat an unfinished stream as retryable, resuming from the last event id.
These questions test whether you use HTTP the way it was designed: methods with exact meanings, caching and concurrency headers, long jobs, streams and the awkward corners of time and money.
Q103. "PUT versus PATCH semantics with Pydantic."
Reveal answer
Strong answer PUT means "replace this resource with what I send". Fields the client leaves out go back to their defaults or null. PATCH means "change only the fields I send". Fields left out stay as they are.
The classic Pydantic mistake is to implement PATCH with a model whose fields are all optional, then call model_dump(). That returns every field, with None for the ones the client never sent, and you write nulls over good data.
The fix is model_dump(exclude_unset=True). Pydantic remembers which fields were present in the input (model_fields_set), so "not sent" and "sent as null" become different. Sending {"note": null} then means "clear the note", while sending nothing means "leave it".
Additional safeguards: extra="forbid" on the patch model so a typo like tip is a 422 instead of being silently ignored, and a separate patch model that lists only the fields clients may change (never id or status history).
Picture it The bug and its fix on the same data.
from pydantic import BaseModel, ConfigDict
class Order(BaseModel):
note: str | None = None
tip_cents: int = 0
status: str = "placed"
class OrderPatch(BaseModel):
model_config = ConfigDict(extra="forbid")
note: str | None = None
tip_cents: int | None = None
stored = Order(note="no onions", tip_cents=200)
body = {"tip_cents": 300} # PATCH: only the tip
print("naive :", stored.model_copy(update=OrderPatch(**body).model_dump()).model_dump())
print("correct :", stored.model_copy(update=OrderPatch(**body).model_dump(exclude_unset=True)).model_dump())
body = {"note": None} # client wants to CLEAR the note
print("clear :", stored.model_copy(update=OrderPatch(**body).model_dump(exclude_unset=True)).model_dump())
print("PUT :", Order(**{"tip_cents": 300}).model_dump(), "<- everything not sent is reset")
try: OrderPatch(**{"tip": 5})
except Exception as e: print("typo :", e.errors()[0]["type"], e.errors()[0]["loc"])Make the invisible visible: Real output.
naive : {'note': None, 'tip_cents': 300, 'status': 'placed'}
correct : {'note': 'no onions', 'tip_cents': 300, 'status': 'placed'}
clear : {'note': None, 'tip_cents': 200, 'status': 'placed'}
PUT : {'note': None, 'tip_cents': 300, 'status': 'placed'} <- everything not sent is reset
typo : extra_forbidden ('tip',)What you see: The naive line sets note to None although the client only sent a tip. The correct line keeps no onions. The third line shows an explicit null clearing the note. PUT resets everything not sent. The typo is caught as extra_forbidden.
PATCH with model_dump()
Omitted becomes null.
data = patch.model_dump()
# ❌ TRAP: includes every field as None
for k, v in data.items():
setattr(order, k, v)PATCH with exclude_unset
Only sent fields change.
data = patch.model_dump(exclude_unset=True)
# ✅ only what the client sent
for k, v in data.items():
setattr(order, k, v)The shift: Track which fields the client actually sent, not just their values.
Land it PUT replaces, PATCH changes only sent fields, and I implement PATCH with exclude_unset on a model that forbids extra keys.
- "How do I tell "not sent" from "sent null" in the model itself?"
The model itself remembers it. Pydantic v2 keeps a set called
model_fields_setwith the names of the fields that were present in the input. A field that was sent asnullis in the set, and a field that was never sent is not.So you can call
patch.model_dump(exclude_unset=True)to get only the sent fields, or test one field with"note" in patch.model_fields_set. With input{"note": null}, the dump is{"note": None}and the service clears the note. With input{}, the dump is empty and nothing changes.The wrong approach is a magic default, such as an empty string or
-1meaning "not provided". A real client can legitimately send an empty string to clear a field, and then you cannot tell the two cases apart.One caution:
exclude_unsetonly looks at fields set by the input. If your code assignspatch.note = Nonelater, that counts as set. So I treat the patch model as read-only after parsing.- "Is JSON Merge Patch or JSON Patch better?"
They are two different formats, and what I already described is close to the first one. JSON Merge Patch (RFC 7396) says: send a partial document, fields you include are replaced, a field set to
nullis deleted, fields you omit stay. That is exactly whatexclude_unsetgives you.Its weakness is arrays. To change one item of a list you must send the whole list, and you cannot say "set this to null" for a field whose value may legitimately be null, because null means delete.
JSON Patch (RFC 6902) is a list of operations with paths, for example
[{"op": "replace", "path": "/lines/0/qty", "value": 3}]. It can edit one array element, move or test values, and it is applied atomically. The cost is a more complex client, more validation work on the server, and paths that tie clients to your internal shape.I use Merge Patch for ordinary resources, with a separate patch model that lists only editable fields, and I avoid JSON Patch unless a client really needs element-level array edits.
- "Should PUT create a resource that does not exist?"
It may, but only when the client chooses the id. If the URL is
PUT /v1/carts/abcand the client inventedabc, then "make the cart abc look like this" works whether or not it existed. It is still idempotent, because repeating it gives the same final state. The status is 201 when created and 200 or 204 when replaced.When the server chooses ids, as with order numbers, PUT-to-create makes no sense, because the client cannot know the id. Use
POST /v1/ordersto create and return 201 with aLocationheader. A PUT to an unknown id then answers 404.There is a security angle too. If PUT can create, a client can fill your table with ids it picked, collide with other users' ids, or squat on names. Check ownership and limit who may create.
Whichever you choose, write it in the API documentation, because clients guess. In QuickBite, orders are POST-created and carts could be PUT-created, and the contract says so.
- "How do you protect against lost updates between two PATCH calls?"
Without protection the last writer wins, silently. Two staff members read an order at version 3, both send a PATCH, and the second overwrites the first without either knowing. There are two common fixes.
- ETag with If-Match: the server returns
ETag: "3"on GET; the client sendsIf-Match: "3"on PATCH; if the stored version is now 4, the server answers 412 Precondition Failed (Q104). Sending no header at all can be refused with 428. - Version column: the row has an integer
version; the service runsUPDATE ... SET ..., version = version + 1 WHERE id = :id AND version = :seenand checks that one row changed. Zero rows changed means someone else won, so answer 409 or 412. - Merge rules: for fields that never conflict, such as a note versus a status, you may merge instead of refusing. I only do this when the business agrees.
I prefer the header because it works for any client and keeps the version out of the body, with the column doing the real check underneath. The key point is that the check and the write happen in one statement, not in two steps with a gap between them.
- ETag with If-Match: the server returns
Q104. "ETags and conditional requests (If-None-Match, If-Match)."
Reveal answer
Strong answer An ETag is a short identifier for a particular version of a resource, usually a hash of its content or its version number. The server sends it in the ETag header. Clients send it back in conditional headers.
If-None-Match: <etag> on a GET means "send the body only if it changed". If the tag still matches, the server answers 304 Not Modified with no body. That saves bandwidth and serialisation, and lets caches revalidate cheaply.
If-Match: <etag> on a PATCH or PUT means "apply this only if the resource is still the version I read". If someone else changed it first, the server answers 412 Precondition Failed. That is optimistic concurrency control over HTTP: no lost updates, no locks held across requests. Requiring the header can return 428 Precondition Required when it is missing.
Two details. The tag must be wrapped in double quotes. And it must change when the representation changes, including when a different field order or a changed response model would change the bytes; a version column on the row is often more stable than a hash.
Picture it One resource through a conditional GET, a good update and a stale update.
import hashlib, json
from fastapi import FastAPI, Header, HTTPException, Request, Response
from fastapi.testclient import TestClient
DB = {1: {"id": 1, "status": "preparing", "version": 3}}
app = FastAPI()
def etag_of(o): return '"' + hashlib.sha256(json.dumps(o, sort_keys=True).encode()).hexdigest()[:12] + '"'
@app.get("/v1/orders/{oid}")
def get(oid: int, response: Response, if_none_match: str | None = Header(None)):
tag = etag_of(DB[oid])
if if_none_match == tag: return Response(status_code=304, headers={"ETag": tag})
response.headers["ETag"] = tag; return DB[oid]
@app.patch("/v1/orders/{oid}")
def patch(oid: int, body: dict, response: Response, if_match: str | None = Header(None)):
if if_match is None: raise HTTPException(428, "If-Match required")
if if_match != etag_of(DB[oid]): raise HTTPException(412, "Order changed since you read it")
DB[oid].update(body, version=DB[oid]["version"] + 1); response.headers["ETag"] = etag_of(DB[oid]); return DB[oid]
c = TestClient(app)
r = c.get("/v1/orders/1"); tag = r.headers["etag"]; print("GET ->", r.status_code, tag)
r = c.get("/v1/orders/1", headers={"If-None-Match": tag}); print("GET If-None-Match ->", r.status_code, repr(r.text))
r = c.patch("/v1/orders/1", json={"status": "ready"}, headers={"If-Match": tag}); print("PATCH If-Match ->", r.status_code, r.headers["etag"])
r = c.patch("/v1/orders/1", json={"status": "picked_up"}, headers={"If-Match": tag}); print("PATCH stale tag ->", r.status_code, r.json())
r = c.patch("/v1/orders/1", json={"status": "x"}); print("PATCH no header ->", r.status_code, r.json())Make the invisible visible: Five requests, real output.
GET -> 200 "28d6af1747ef"
GET If-None-Match -> 304 ''
PATCH If-Match -> 200 "163e6183701c"
PATCH stale tag -> 412 {'detail': 'Order changed since you read it'}
PATCH no header -> 428 {'detail': 'If-Match required'}What you see: The second GET returns 304 and an empty body. The first PATCH works and returns a new tag. The second PATCH reuses the old tag and gets 412, because the first one changed the resource. Without the header the server answers 428.
Last writer wins
Two staff members overwrite each other.
@router.patch("/{id}")
def patch(id, body):
order.update(body) # ❌ silent overwriteIf-Match
The stale one is refused.
@router.patch("/{id}")
def patch(id, body, if_match=Header()):
if if_match != etag_of(order):
raise HTTPException(412)The shift: Make "I changed it based on version X" part of the request, and let the server say no.
Land it ETag with If-None-Match saves bandwidth through 304, and ETag with If-Match prevents lost updates through 412, so no lock is held between a read and a write.
- "Weak or strong ETags?"
A strong ETag, written
"abc", promises the two representations are identical byte for byte. A weak ETag, writtenW/"abc", promises only that they mean the same thing, even if the bytes differ, for example because of different whitespace or key order.Why it matters: proxies and servers may compress or re-encode a response. A gzipped body is not byte-identical to the plain one, and some servers turn a strong tag weak when they compress. For a JSON API behind such layers, weak tags are the realistic choice for GET revalidation, and
If-None-Matchuses weak comparison, so it still matches.For writes it is stricter. RFC 9110 requires strong comparison for
If-Match, so a weak tag never matches and the request fails with 412. That is the correct, safe behaviour, because you are asking "is this exactly the version I read?".My policy is simple: derive the tag from the version column, send it strong on resources that accept PATCH, and make sure the compression layer does not rewrite it. If you cannot control the proxies, test through them.
- "Where do you compute the tag cheaply?"
From a value that already exists on the row, never from the serialised response. A
versioninteger that increments on every update is the best source. Anupdated_attimestamp works too, if it has enough precision that two quick updates cannot share a value; microseconds are safer than seconds.Hashing the full JSON works but wastes the saving. You would query the row, build the response model, serialise it and hash it, and only then discover that the client already had it. With a version column, the handler reads the row (or only its version, with a tiny query), compares with
If-None-Matchand returns 304 before building any response.There is also a stability benefit. A hash changes when you rename a field in the response model or change serialisation, so every client cache goes stale after a deploy. A version number changes only when the data changes.
The canonical app supports ETag,
If-None-MatchandIf-Matchon its GET and PATCH routes, and one thing to remember is to include the tag on 304 responses too.- "Does a CDN honour these?"
Yes, as long as the response is cacheable, and the details are worth knowing. A CDN (a network of caches near the users) stores a copy and, when it expires, asks the origin.
- Revalidation: the CDN sends
If-None-Matchwith the stored tag; your server answers 304 with no body, and the CDN keeps serving its copy. The saving is the body, not the round trip. - Cache-Control decides: without
Cache-Control: max-ageors-maxage, many CDNs do not store the response at all, so the ETag is never used. - Private data: for per-user responses such as order history, send
Cache-Control: privateso shared caches never store it, or the next user could receive someone else's orders.Vary: Authorizationis a second line of defence.
I add
Cache-Controldeliberately on every GET route instead of leaving the default, and I test one cached and one private route through the real CDN.- Revalidation: the CDN sends
- "What if the client cannot send If-Match?"
Offer the same idea in the body. The client reads
"version": 3, sends it back in its update, and the service uses optimistic locking:UPDATE ... WHERE id = :id AND version = :seen. If no row matches, return 409 Conflict (or 412 if you want to mirror the header behaviour) with a problem body that says the resource changed.The semantics are the same as
If-Match: no locks are held between read and write, and the loser gets a clear error. Only the transport differs.Headers are cleaner because they work for any media type, do not pollute the schema, and let HTTP caches and tools understand the precondition. Bodies are easier for naive clients, such as simple scripts, low-code tools or some mobile libraries that make custom headers awkward.
If I must support both, I accept either and check whichever is present, and if both are present and disagree I answer 400. I document one as preferred so the API does not grow two behaviours that drift apart.
Q105. "Long-running operations: 202 Accepted plus a status resource."
Reveal answer
Strong answer When work takes longer than a client will wait (an export, a report, a refund that calls three systems), do not hold the connection. Accept the job, answer at once, and let the client check progress.
The pattern has three parts. POST /v1/exports validates the request, records a job, hands the work to a queue and returns 202 Accepted with a Location header pointing at the job. GET /v1/exports/jobs/{id} returns the state (queued, running, done or failed) and, when finished, a link to the result. A Retry-After header suggests when to ask again.
Make the POST idempotent with an Idempotency-Key so a retried request does not start a second export. Store the job in the database, not memory, so any pod can answer the status call and a restart does not erase it. And do the work in a real worker (Q126); a BackgroundTasks job disappears on a deploy.
The finished state can answer with 200 plus the result, or 303 See Other redirecting to the result URL. Failed jobs return the problem details of why.
Picture it The shape of the exchange, with a thread standing in for the worker (so the demo is short).
import time
from fastapi import BackgroundTasks, FastAPI, Response
from fastapi.testclient import TestClient
JOBS = {}
app = FastAPI()
def work(job_id):
JOBS[job_id]["status"] = "running"; time.sleep(0.2)
JOBS[job_id].update(status="done", result_url="/v1/exports/5.csv")
@app.post("/v1/exports", status_code=202)
def start(bg: BackgroundTasks, response: Response):
job_id = len(JOBS) + 1; JOBS[job_id] = {"id": job_id, "status": "queued"}
bg.add_task(work, job_id)
response.headers["Location"] = f"/v1/exports/jobs/{job_id}"; response.headers["Retry-After"] = "1"
return JOBS[job_id]
@app.get("/v1/exports/jobs/{job_id}")
def status(job_id: int): return JOBS[job_id]
c = TestClient(app)
r = c.post("/v1/exports"); print("POST ->", r.status_code, dict(location=r.headers["location"], retry_after=r.headers["retry-after"]), r.json())
print("GET ->", c.get(r.headers["location"]).json())Make the invisible visible: One POST, one poll.
POST -> 202 {'location': '/v1/exports/jobs/1', 'retry_after': '1'} {'id': 1, 'status': 'queued'}
GET -> {'id': 1, 'status': 'done', 'result_url': '/v1/exports/5.csv'}What you see: The POST answers 202 immediately with queued, a Location and a Retry-After. The poll shows done with a result_url (the test client waited for the background task; a real client would poll until it appeared).
Synchronous
The request waits, the gateway times out.
@router.post("/exports")
def export():
csv = build_csv() # ❌ 90 s, 504 at 60 s
return csv202 + status resource
Answer now, poll later.
@router.post("/exports", status_code=202)
def export(res: Response):
job = jobs.enqueue(...)
res.headers["Location"] = job.url
return jobThe shift: Separate "I accepted your request" from "your request finished".
Land it For anything longer than a few seconds I return 202 with a Location to a persisted job resource and do the work in a real worker.
- "Polling or webhooks or push?"
I start with polling because it is simple and works through every proxy and firewall. The client calls
GET /v1/exports/jobs/{id}and readsstate. The server addsRetry-After: 5and the client backs off, for example 2, 4, 8, 16 seconds up to a cap, so one slow job does not turn into a hundred requests a minute.Webhooks flip the direction: the client registers a URL, and the server calls it when the job finishes. They are good for partners, who do not want to poll, but you take on work: signing the call, retrying failures, and handling clients that are down. Always keep the status resource, because webhooks get lost.
Server-sent events or WebSocket suit a live user interface, where someone is watching a progress bar. They need connections held open and pub/sub behind the scenes (Q107, Q108).
So: polling by default, webhooks for integrations, push for human-facing screens. The status resource stays the source of truth in all three.
- "How long should I keep job records?"
Long enough for the client to fetch the result, and no longer. A common choice is 24 hours to 7 days, depending on how people use it. A nightly report that someone opens the next morning needs a day or two. A partner who collects data weekly needs a week.
The record is small, but the result file may be large. A 200 MB export kept for a year costs real storage, and it may contain personal data that the retention policy says you must not hold. So the expiry job (Q128) deletes both the row and the file, and the job resource answers 404, or 410 Gone, after that. 410 tells the client the job did exist and was removed on purpose.
Put the expiry time in the response:
"expires_at": "2026-12-02T10:00:00Z". Clients can then show it to the user and fetch before it disappears.I also keep a short audit line (who asked, when, how many rows) for longer, without the result itself, in case someone later asks "who exported the customer list?".
- "How do I cancel a running job?"
Cancel is a request, not a command, because the worker may be anywhere in its work. A workable design has three steps.
- Request:
DELETE /v1/exports/jobs/{id}(orPOST .../cancel) setsstate = cancellingin the job row and returns 202. If the job is alreadydone, answer 409 or simply 200 and leave it. - Cooperate: the worker reads the state between steps, for example after each batch of 1,000 rows, and stops when it sees
cancelling. It cleans up partial files and setscancelled. - Bound the wait: a worker inside a long database call cannot be interrupted at once. Use statement timeouts and small batches so the check happens often.
I make cancel idempotent, so a second call does no harm, and I never kill worker processes to cancel one job, since that risks half-written results and other jobs on the same worker. If the work is truly uninterruptible, the honest answer is "cancelling" until it ends.
- Request:
- "What if the client crashes after the POST and loses the job id?"
That is the scenario the idempotency key exists for. The client generates a key, for example a UUID, before the first call and stores it with the intent, not just in memory. If the POST times out, or the app crashes and restarts, it sends the same POST with the same key.
The server looks the key up in its table. If it finds an existing job for that key and an identical body, it returns the same job (the replay is a 200 with
Idempotent-Replayed: truein the canonical app). If the body differs, it answers 422, because the same key must mean the same request. If there is no match, it creates a job.Without a key the server cannot tell a retry from a new request, so it starts a second export, and for a refund or an email blast that is expensive.
As a second safety net, give the client a way to list its recent jobs,
GET /v1/exports/jobs?created_by=me, so a lost id can be recovered by looking, and keep keys for as long as the jobs, at least 24 hours.
Q106. "File upload limits, and streaming large uploads to object storage."
Reveal answer
Strong answer A file upload is a request body that can be gigabytes. Three limits protect the server: the maximum size, the allowed types, and the time it may take. Enforce them in layers: the gateway or reverse proxy first (client_max_body_size in nginx, a request size limit in the gateway), then the application.
Check Content-Length early and refuse with 413 Payload Too Large before reading anything. That header can be missing or lie (chunked uploads have none), so also count the bytes while reading and stop when the limit is crossed.
Never load a large file into memory. FastAPI's UploadFile spools to a temporary file on disk past a threshold, which is better than bytes, but still stores the whole upload on the pod's disk. For big files, read request.stream() chunk by chunk and forward each chunk to object storage as a multipart upload part.
The best design for very large files is to avoid sending them through the API at all: return a pre-signed URL so the client uploads straight to S3 or similar, then call your API with the object key. Validate the type by content (magic bytes), never by the file extension or client-sent content type.
Picture it A streaming upload endpoint with both limits, tested with three bodies.
from fastapi import FastAPI, HTTPException, Request
from fastapi.testclient import TestClient
MAX = 1024 * 1024 # 1 MiB for this demo
app = FastAPI()
@app.put("/v1/restaurants/1/menu-photo")
async def upload(request: Request):
declared = request.headers.get("content-length")
if declared and int(declared) > MAX: # cheap early refusal
raise HTTPException(413, "File too large")
received = 0
async for chunk in request.stream(): # never hold the whole file in memory
received += len(chunk)
if received > MAX: raise HTTPException(413, "File too large")
# here: forward `chunk` to object storage (multipart upload part)
return {"stored_bytes": received}
c = TestClient(app)
print("500 KiB ->", c.put("/v1/restaurants/1/menu-photo", content=b"x" * 500_000).json())
print("2 MiB (CL) ->", c.put("/v1/restaurants/1/menu-photo", content=b"x" * 2_000_000).status_code)
def gen(): # no Content-Length: chunked transfer
for _ in range(3): yield b"x" * 600_000
r = c.put("/v1/restaurants/1/menu-photo", content=gen()); print("1.8 MiB chunked ->", r.status_code, r.json())Make the invisible visible: Real status codes.
500 KiB -> {'stored_bytes': 500000}
2 MiB (CL) -> 413
1.8 MiB chunked -> 413 {'detail': 'File too large'}Why: The 500 KiB body passes and is counted chunk by chunk. The 2 MiB body is refused from its Content-Length before any byte is read. The chunked body has no length, so it is stopped by the running counter once it passes 1 MiB.
UploadFile read whole
Memory and disk both explode.
@router.post("/photo")
async def up(f: UploadFile):
data = await f.read() # ❌ all bytes in RAM
storage.put(data)Stream with a cap
Constant memory, early refusal.
async for chunk in request.stream():
seen += len(chunk)
if seen > MAX:
raise HTTPException(413)
await part.write(chunk)The shift: Treat an upload as a stream with a budget, not as a value.
Land it I cap size at the proxy and again in the app by counting streamed bytes, validate content type by bytes, and prefer pre-signed URLs so large files never pass through the API.
- "Why does
python-multipartmatter here?" It is the library FastAPI uses to read
multipart/form-data, the format a browser uses for file uploads and HTML forms. DeclaringUploadFileorForm(...)in a route needs it installed, and FastAPI raises an error at startup if it is missing. The canonical app has no form routes, so its project file does not list it.It matters for security because it is a parser that reads untrusted bytes from the internet. A bug in a parser, such as a slow-parsing or memory-hungry input, can be reached by anyone who can send a request. So pin it, update it, and put it in your dependency scanning.
Recent versions of FastAPI and Starlette added configurable limits on the number and size of form parts; check the version you run before relying on them.
Two habits help. Limit body size before parsing (proxy and middleware, Q109), and use pre-signed URLs for big files so the parser never sees them at all.
- "How do I protect against slow uploads that tie up connections?"
A slow upload is a small attack: a client that sends one byte per second holds a connection, a worker slot and some memory for hours. A few hundred of them can exhaust the server's connections without much traffic.
I defend in layers. At the proxy, set a read timeout between bytes (nginx
client_body_timeout, default 60 s) and a ceiling for the whole request at the gateway. At uvicorn,--timeout-keep-alivecloses idle keep-alive connections (default 5 s), and--limit-concurrencyrefuses new work once too many connections are open. In the app, the byte-counting loop can also check elapsed time and abort with 408 or 413.A minimum data rate is the sharper tool: some gateways drop clients below, say, 1 KB per second.
The better design avoids the problem. With a pre-signed URL, the slow client ties up the object store, which is built for it, not your API workers.
- "What about virus scanning and image processing?"
Never inside the request path. Scanning and image processing are slow, CPU-heavy and run code (decoders) on untrusted input, which is where many security bugs live.
- Quarantine: store the upload in a private bucket with no public read, and record
status = pendingin the database. The API answers 202 or 201 at once. - Process in a worker: a queued job scans with an antivirus engine, checks magic bytes, re-encodes the image (which strips hidden payloads and metadata), and writes the clean copy to the public bucket.
- Mark available: only then set
status = ready. A rejected file is deleted and the user is told.
Run the worker with the least privilege it needs, a memory limit and a timeout, so a malicious file that crashes the decoder takes down one job, not the API. The user sees a short "processing" state, which is a small price.
- Quarantine: store the upload in a private bucket with no public read, and record
- "How do resumable uploads work?"
A resumable upload splits the file into parts, so a dropped connection costs one part, not the whole file. S3 multipart upload works like this: you start an upload and get an upload id, send numbered parts (each at least 5 MiB, except the last), and then complete the upload with the list of part numbers and their tags.
The server, or S3 itself, remembers which parts arrived. After a failure, the client asks "which parts do you have?" (
ListParts), and sends only the missing ones. The tus protocol does the same over plain HTTP withHEADto read the offset andPATCHto continue from it.A 2 GB file in 8 MiB parts is 250 parts. Losing the connection at part 200 means resending one part, not 2 GB.
I let the API hand out pre-signed URLs for each part and record the upload in a table, so I do not write the protocol. Remember to add a lifecycle rule that aborts incomplete multipart uploads after a few days, because their parts cost storage and never show in a normal listing.
Q107. "WebSockets in FastAPI — when do you use them, and how do they scale?"
Reveal answer
Strong answer A WebSocket is one long-lived, two-way connection between browser and server. Use it when the server must push frequently or the client sends many small messages: a live kitchen display, chat, collaborative editing. For occasional updates, polling or server-sent events are simpler (Q108).
In FastAPI a WebSocket route is an async def that accepts the connection and loops on receive and send. Each open socket is a task on the event loop, which is cheap, so one process can hold thousands of idle connections.
Scaling is where the difficulty lies. Connections are stateful: a message for restaurant 9 must reach every tablet connected for restaurant 9, but those tablets may be connected to different pods. A manager object in one process knows only its own sockets. The standard answer is a pub/sub backbone (Redis pub/sub, NATS or Kafka): every pod subscribes to the restaurant's channel and forwards messages to its own sockets.
Other points: authenticate during the handshake (a token in a query parameter is logged by proxies, so prefer a first message or a short-lived ticket), check the Origin header yourself because CORS does not apply, send pings to detect dead peers, and set connection limits per user.
Picture it The single-process version, with a hub that tracks sockets per restaurant. This is the part you would replace with a pub/sub subscriber in production.
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.testclient import TestClient
class Hub:
def __init__(self): self.rooms: dict[int, set[WebSocket]] = {}
async def join(self, rid, ws): await ws.accept(); self.rooms.setdefault(rid, set()).add(ws)
def leave(self, rid, ws): self.rooms[rid].discard(ws)
async def publish(self, rid, msg):
for ws in list(self.rooms.get(rid, ())): await ws.send_json(msg)
hub = Hub()
app = FastAPI()
@app.websocket("/ws/restaurants/{rid}/orders")
async def live_orders(ws: WebSocket, rid: int):
await hub.join(rid, ws)
try:
while True:
msg = await ws.receive_json() # e.g. kitchen sends status updates
await hub.publish(rid, {"order": msg["order"], "status": msg["status"]})
except WebSocketDisconnect:
hub.leave(rid, ws)
c = TestClient(app)
with c.websocket_connect("/ws/restaurants/9/orders") as a, c.websocket_connect("/ws/restaurants/9/orders") as b:
a.send_json({"order": 881, "status": "preparing"})
print("tablet A got:", a.receive_json()); print("tablet B got:", b.receive_json())
print("connections left in room 9:", len(hub.rooms[9]))Make the invisible visible: Two tablets in room 9, one update.
tablet A got: {'order': 881, 'status': 'preparing'}
tablet B got: {'order': 881, 'status': 'preparing'}
connections left in room 9: 0What you see: Tablet A sends a status update; both tablets receive it, because the hub publishes to every socket in the room. When both connections close, the hub is empty. All of this only works while every tablet is connected to this one process.
One process
Hub in memory.
rooms: dict[int, set[WebSocket]] = {}
async def publish(rid, msg):
for ws in rooms.get(rid, ()):
await ws.send_json(msg)Many pods
Hub fed by a shared channel.
# illustrative
async def listener():
async for m in pubsub.listen():
for ws in rooms.get(m.rid, ()):
await ws.send_text(m.data)The shift: In memory works for one pod; to scale out, messages travel through a shared channel every pod listens to.
Land it I use WebSockets for frequent two-way traffic, authenticate at the handshake and check Origin, and scale out by fanning messages through a pub/sub system that every pod subscribes to.
- "How many connections can one worker hold?"
The honest answer is "far fewer than the idle count suggests, and you must measure". An idle socket costs roughly a few kilobytes of memory (the task, buffers, a small object). Ten thousand idle sockets might take well under a gigabyte, so tens of thousands per worker are plausible.
Real limits come from elsewhere. The operating system caps open file descriptors, one per socket, so check
ulimit -n(often 1,024 by default, which is too low). Each active connection has read and write buffers. And each message costs CPU: if 10,000 sockets each get one message a second, the event loop handles 10,000 messages a second, plus serialisation, and one slow handler delays everyone.So I load-test with the real message rate and size, watch event-loop lag, and set limits:
--limit-concurrencyin uvicorn, a per-user cap, and a maximum message size.Overload should be refused quickly with a clear close code, not turn into slow responses for everybody. Then add workers or pods before the first one is saturated.
- "What happens to sockets on deploy?"
They are dropped, and the design has to expect it. A deploy replaces pods, and every socket on an old pod closes. If every client reconnects at the same second, the new pods get a stampede.
So clients reconnect with exponential backoff and random jitter, for example waiting 1 s, 2 s, 4 s with each wait randomised by up to 50 percent, to spread the load. They send the id of the last event they saw, so the server can replay what was missed, or answer "resync" and let the client refetch the current state.
On the server side, handle SIGTERM by stopping new connections and sending close frames (code 1001, "going away") to existing ones, a few at a time, so clients reconnect to a new pod instead of waiting for a timeout. Set the pod's termination grace period longer than the drain.
I also avoid keeping important state only in the socket: anything the user must not lose lives in the database, and the socket only carries notifications about it.
- "How do load balancers treat WebSockets?"
A load balancer must be told that WebSockets are allowed, because the connection starts as an HTTP request with
Upgrade: websocketand then turns into a long-lived stream. Most modern balancers (nginx with the upgrade headers set, AWS ALB, Envoy) support it, but some old or strict ones do not.The second catch is the idle timeout. Many balancers close any connection with no traffic for 60 seconds (AWS ALB defaults to 60 s). Either raise it for the route, or have the app send pings more often than the timeout, for example every 20 to 30 seconds. Pings also detect dead peers, such as a phone that left Wi-Fi.
Sticky sessions are not needed with the pub/sub design, because any pod can serve any socket, and a message for restaurant 9 reaches every pod through the broker.
Sticky sessions would help only if state lived inside one process, which I want to avoid. For scale-in, balancers should drain connections gracefully rather than cut them.
- "WebSocket or SSE for the restaurant dashboard?"
For a restaurant dashboard that mostly receives order updates, I would pick SSE. It is a plain HTTP response that stays open and carries text events, so it passes through proxies, works with ordinary authentication headers, and the browser's
EventSourcereconnects by itself and sendsLast-Event-ID.WebSocket is the better tool when the same channel carries frequent traffic in both directions, such as a chat, a shared drawing or a game, where opening a new HTTP request for each upward message would be wasteful.
The dashboard sends commands rarely: staff press "preparing" a few times per order. Those can be ordinary
PATCHrequests withIf-Match, which are easy to authorise, retry and log. So the stream carries events down, and HTTP carries commands up.Two limits of SSE to remember. The browser allows only about six connections per host under HTTP/1.1, so many tabs can exhaust it (HTTP/2 lifts that). And SSE carries text only. If neither bites, SSE is simpler to run and to debug.
Q108 · Scenario. "A server-sent-events stream disconnects behind the load balancer every 60 seconds. Fix it."
Reveal answer
The real test Whether you recognise the idle timeout of an intermediary and answer with heartbeats and proxy settings, not application changes.
Strong answer A 60-second cut is almost always a proxy's idle timeout. The load balancer (or nginx, or a gateway) closes connections that have carried no bytes for 60 seconds, and an SSE stream with no events for a minute looks idle. 60 seconds is the common default for AWS load balancers, nginx's proxy_read_timeout and several ingress controllers.
Fix it on both sides. In the app, send a heartbeat every 15 to 30 seconds: an SSE comment line (starting with a colon) which clients ignore but proxies count as traffic. In the proxy, raise the idle timeout for this route and turn off response buffering (X-Accel-Buffering: no for nginx, proxy_buffering off), because a buffering proxy holds the events instead of passing them on.
Make the client resilient as well. The browser's EventSource reconnects automatically and sends Last-Event-ID; the server should put an id: line on each event and replay anything newer, so a reconnect loses nothing.
Also check that compression is not enabled for the stream, since gzip middleware buffers output, and that any HTTP/1.1 connection limit per browser (six per host) is not exhausted by many tabs.
Picture it A stream that emits a keep-alive comment every 0.2 seconds (a stand-in for 20 seconds) and one real event at 0.5 seconds. The client is httpx against a real uvicorn server, because the in-memory test transport buffers the whole body and never streams.
import asyncio, threading, time, httpx, uvicorn
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def events(queue: asyncio.Queue, heartbeat=0.2):
while True:
try:
ev = await asyncio.wait_for(queue.get(), timeout=heartbeat)
yield f"event: order\ndata: {ev}\n\n"
except asyncio.TimeoutError:
yield ": keep-alive\n\n" # a comment line: clients ignore it, proxies see traffic
@app.get("/v1/live/orders")
async def live():
q = asyncio.Queue(); asyncio.get_running_loop().call_later(0.5, q.put_nowait, '{"id":881,"status":"ready"}')
return StreamingResponse(events(q), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
async def main():
async with httpx.AsyncClient(base_url="http://127.0.0.1:8767", timeout=5) as c:
async with c.stream("GET", "/v1/live/orders") as r:
print(r.status_code, r.headers["content-type"])
n = 0
async for line in r.aiter_lines():
if line: print(repr(line)); n += 1
if n == 5: break
server = uvicorn.Server(uvicorn.Config(app, port=8767, log_level="error"))
threading.Thread(target=server.run, daemon=True).start()
while not server.started: time.sleep(0.05)
asyncio.run(main()); server.should_exit = TrueMake the invisible visible: The first five non-empty lines the client sees.
200 text/event-stream; charset=utf-8
': keep-alive'
': keep-alive'
'event: order'
'data: {"id":881,"status":"ready"}'
': keep-alive'What you see: Comment lines (: keep-alive) arrive while nothing happens, so the connection is never silent. The real order event arrives between them in the standard event: and data: format.
Silent stream
Dies at the idle timeout.
async def events():
while True:
ev = await queue.get() # ❌ may wait 5 min
yield f"data: {ev}\n\n"With heartbeat
Traffic every few seconds.
async def events():
while True:
try: ev = await asyncio.wait_for(
queue.get(), 15)
except TimeoutError:
yield ": keep-alive\n\n"; continue
yield f"data: {ev}\n\n"The shift: Silence looks like death to every device in the path, so say something regularly.
Land it A cut at exactly 60 seconds is an idle timeout, so I send a heartbeat comment every 15 to 30 seconds, raise the proxy timeout and disable buffering for that route, and give events ids so reconnects resume.
- "Why are comments the right heartbeat?"
Because the format says so. In server-sent events, each line has a field name before a colon:
data:,event:,id:,retry:. A line that starts with a colon has an empty field name and is a comment, which the browser's parser discards without firing any event handler.That makes it a perfect heartbeat. The server writes
: pingfollowed by a blank line every 15 to 30 seconds. It costs about eight bytes, but a proxy sees bytes flowing on the connection and resets its idle timer. Application code in the client never sees it, so there is nothing to filter and no event to ignore.A fake data event would work too, but then every client must understand it and skip it, and a client that forgets will show a bogus message to users.
Pick an interval at most half of the shortest timeout on the path. With a 60 second limit, 20 seconds leaves two missed pings before a cut.
- "Is there a library for this?"
Yes:
sse-starletteprovidesEventSourceResponse, which formats events, sends periodic pings and stops the generator when the client disconnects. It is installed on the course machine.I wrote the plain version, a
StreamingResponsewith a generator, because it makes the mechanism visible: you can see thedata:lines, the blank line that ends each event, and the heartbeat. Learning that first means you can debug the library when something goes wrong.In production I use the library for three reasons. It handles disconnect detection and cancellation correctly, which is easy to get subtly wrong. It sets headers such as
Cache-Control: no-cacheandX-Accel-Buffering: no. And its ping interval is a single argument.I still read its behaviour on shutdown, because a stream that never ends can keep the server from stopping. The fix is to listen for the shutdown signal in the generator, or to set a graceful-shutdown timeout, so deploys do not hang.
- "How do I detect that the client has gone away?"
There are two ways, and I use both. The first is to ask: inside the loop,
if await request.is_disconnected(): breakchecks whether the client closed the connection. It needs a check each cycle, so it only works if your loop wakes up regularly, which a heartbeat guarantees.The second is to let cancellation do it. When the client goes away, the server cancels the task that is running the response, and
asyncio.CancelledErroris raised at the nextawaitin your generator. You catch it, or better usetry/finally, to clean up.Cleanup is the important part. A typical stream registers a queue or a pub/sub subscription for the connection. If you do not remove it in
finally, every closed browser tab leaves one queue behind, the broker keeps pushing events into it, and memory grows until the pod is killed. That is the leak behind Q132.I test it by opening and closing 1,000 streams in a loop and checking the number of subscriptions returns to zero.
- "Why does the stream work locally but fail in production?"
Because your laptop has one hop and production has many. Locally the browser talks straight to uvicorn, so nothing buffers, compresses or times out. In production the request crosses several layers, and any of them can break a stream.
- CDN or edge: may buffer the response until it is complete, or cap how long a connection can live. Some need streaming turned on for the route.
- Load balancer: idle timeout, often 60 s, as in this scenario.
- Ingress and sidecar: nginx buffers unless
proxy_buffering offorX-Accel-Buffering: no; a service-mesh sidecar adds its own timeouts. - App middleware:
GZipMiddlewareholds output in blocks, so small events appear late.
I test through the same path as production, using
curl -Nto see events arrive one by one, and I write down each layer's timeout. A staging environment that matches the production path catches this before users do.
Q109. "Request body size limits and form-parsing limits."
Reveal answer
Strong answer By default FastAPI and Starlette do not cap the size of a JSON body. A client can send a 500 MB JSON document and the server will try to read and parse it, using memory for both the raw bytes and the parsed objects. A limit has to be added on purpose.
The cheapest protection sits in front: the reverse proxy or gateway (nginx client_max_body_size 1m, or the cloud gateway's payload limit). Inside the app, a small pure ASGI middleware checks Content-Length and also counts bytes as they are received, because chunked requests carry no length. Choose limits per route class: tiny for ordinary JSON (say 1 MB), larger and streamed for uploads.
Forms have extra dimensions. A multipart or URL-encoded form can contain thousands of fields or parts, and parsers spend time and memory on each. Recent versions of Starlette and FastAPI added configurable limits on the number of form fields, files and part sizes; check the release notes of the version you run, set them explicitly and test them, rather than assuming defaults are safe.
Also bound the data inside valid JSON: max_length on strings, max_length on lists (an order may have at most 50 lines), and nesting depth. A small 100 KB body can still hold a million tiny list items.
Picture it A body-limit middleware tested with a small body, an oversized body and a chunked body with no length.
from fastapi import FastAPI
from fastapi.testclient import TestClient
class TooLarge(BaseException): pass # BaseException: FastAPI turns a plain Exception from body reading into 400
class BodyLimit: # pure ASGI middleware
def __init__(self, app, max_bytes): self.app, self.max = app, max_bytes
async def __call__(self, scope, receive, send):
if scope["type"] != "http": return await self.app(scope, receive, send)
headers = dict(scope["headers"]); cl = headers.get(b"content-length")
if cl and int(cl) > self.max: return await self._reject(send)
seen = 0
async def counting_receive():
nonlocal seen
msg = await receive()
if msg["type"] == "http.request":
seen += len(msg.get("body", b""))
if seen > self.max: raise TooLarge()
return msg
try: await self.app(scope, counting_receive, send)
except TooLarge: await self._reject(send)
async def _reject(self, send):
await send({"type": "http.response.start", "status": 413, "headers": [(b"content-type", b"application/problem+json")]})
await send({"type": "http.response.body", "body": b'{"title":"Payload Too Large","status":413}'})
app = FastAPI()
@app.post("/v1/orders")
async def create(body: dict): return {"keys": len(body)}
app.add_middleware(BodyLimit, max_bytes=2000)
c = TestClient(app, raise_server_exceptions=False)
print("small :", c.post("/v1/orders", json={"a": 1}).status_code)
r = c.post("/v1/orders", json={"a": "x" * 5000}); print("big :", r.status_code, r.text)
def chunks(): yield b'{"a":"'; yield b"y" * 3000; yield b'"}'
print("chunked :", c.post("/v1/orders", content=chunks()).status_code, "(no Content-Length, caught while counting)")Make the invisible visible: Real output.
small : 200
big : 413 {"title":"Payload Too Large","status":413}
chunked : 413 (no Content-Length, caught while counting)What you see: The small request passes. The oversized one is refused 413 from its declared length. The chunked body, which has no Content-Length, is refused 413 when the byte counter crosses the limit.
The trap: A first version of this middleware raised a plain ValueError from the receive function. FastAPI wraps body reading in a try block and turned that into 400, so the counted case answered 400, not 413. The fix was an exception type FastAPI does not catch (the demo uses a BaseException subclass) and a catch in the middleware that sends the 413.
Unbounded
The framework reads whatever arrives.
@router.post("/orders")
async def create(body: dict):
... # ❌ any size, any depthBounded
Proxy limit, middleware, model caps.
class Lines(BaseModel):
lines: list[Line] = Field(
max_length=50)
app.add_middleware(BodyLimit, max_bytes=10**6)The shift: Put a number on every input: bytes, items, depth and time.
Land it I cap body size at the proxy and in an ASGI middleware that counts streamed bytes, set explicit form-parsing limits for my framework version, and bound list and string sizes in the models.
- "Why a pure ASGI middleware instead of
BaseHTTPMiddleware?" Because of how the two styles wrap the request.
@app.middleware("http")andBaseHTTPMiddlewarehand you aRequestand acall_nextfunction. To look at the body you would callawait request.body(), which reads the entire body into memory first. That defeats the purpose of a limit, because the memory is already spent. Replacing the body for the app afterwards is awkward, and streaming responses had known quirks with this style.A pure ASGI middleware is a class with
__call__(self, scope, receive, send). It wrapsreceive, the function the app calls to get body chunks. Each time a chunk arrives, you add its length to a counter. When the counter passes the limit, you stop and send a 413 response, and the app never sees the rest.It also adds less overhead, because there is no extra request and response object per call, and it works for HTTP and WebSocket scopes alike.
The one cost is that you write slightly lower-level code, about twenty lines, once. I also check
Content-Lengthfirst so honest oversized requests are refused before any bytes are read.- "Does uvicorn have a limit too?"
Uvicorn has a few protective settings, but none of them is a body limit.
--limit-concurrencycaps how many connections or tasks it serves at once and answers 503 beyond that.--limit-max-requestsrestarts a worker after a number of requests, which helps with leaks.--h11-max-incomplete-event-sizebounds the size of the HTTP/1.1 request line and headers, not the body.It will happily pass a 2 GB body through to your app, one chunk at a time. That is by design: a server cannot know which routes should accept big uploads.
So the limits have to come from two places. The proxy or gateway sets a generous maximum for the whole system (nginx
client_max_body_size, default 1 MB), and your middleware sets tighter, route-specific limits, such as 1 MB for ordinary JSON and much larger for upload routes that stream to object storage.Always have the proxy limit as the first line of defence, because it stops the bytes before they reach Python at all, and keep the middleware as the safety net that still works when someone calls the pod directly.
- "What status for a body that parses but breaks a model cap?"
Use two different codes, because they tell the client two different things.
- 413 Payload Too Large: the raw message is bigger than the server accepts. The client must send less data; changing the content will not help. Send it before parsing, and add
Connection: closeif the rest of the body is unread. - 422 Unprocessable Content: the message arrived in full and parsed as JSON, but the data breaks a rule, such as
max_length=50on the order lines. Pydantic produces this automatically, with an error for each broken field. - 400 Bad Request: for JSON that is not valid JSON at all.
A client developer who sees 413 knows to compress or split the upload, and one who sees 422 reads the
errorslist and fixes a field. Mixing them forces people to read the body to guess which problem they have.- 413 Payload Too Large: the raw message is bigger than the server accepts. The client must send less data; changing the content will not help. Send it before parsing, and add
- "How do I test the limit without sending 10 MB in a unit test?"
Make the limit a setting, not a constant. In the app factory, read
max_body_bytesfrom settings with a default of 1,048,576. In the test, build the app withmax_body_bytes=2000, and send a body of 2,001 bytes, which is cheap to create in memory. Assert 413. Then send 2,000 bytes and assert it passes.Test both ways the limit can trigger. One request has an honest
Content-Lengthlarger than the limit, which must be refused without reading. Another sends a body in chunks with no length (a generator passed ascontent=to the client), which must be cut off by the byte counter. A middleware tested only withContent-Lengthmisses the case that matters most.The demo does exactly that with a limit of 2,000 bytes.
The lesson applies to every limit: a timeout, a page size, a rate limit. If it is configurable, you can test the boundary in a few milliseconds instead of waiting for a real minute or sending real megabytes.
Q110. "How do you make PUT and DELETE idempotent?"
Reveal answer
Strong answer Idempotent means that doing the same request twice leaves the system in the same state as doing it once. HTTP defines GET, PUT and DELETE as idempotent and POST and PATCH as not (by default). Idempotent does not mean "same response": the second DELETE may return a different status.
PUT is idempotent when it is a true replacement: the body is the complete new state, so applying it again changes nothing. Make sure it contains no relative operations (such as "add 1 to the tip") and that server-side fields, like updated_at, are not part of what idempotence promises.
DELETE is idempotent when the end state is what counts: after the call the order is gone. The second call finds nothing. Return 204 both times (the goal is reached), or 404 the second time (both are acceptable), but pick one and document it. Do not make the second call an error that makes a retrying client think it failed.
Where you cannot get idempotence from semantics (POST create, or a PATCH with a relative change), add an Idempotency-Key and store the first result (Q72, Q73).
Picture it One PUT, one DELETE and one POST, each sent twice.
from fastapi import FastAPI, Response
from fastapi.testclient import TestClient
ORDERS = {1: {"id": 1, "note": "a"}}
app = FastAPI()
@app.put("/v1/orders/{oid}/note")
def put_note(oid: int, body: dict): ORDERS[oid]["note"] = body["note"]; return ORDERS[oid]
@app.delete("/v1/orders/{oid}", status_code=204)
def delete(oid: int):
ORDERS.pop(oid, None) # missing is fine: end state is what counts
return Response(status_code=204)
@app.post("/v1/orders")
def post(): ORDERS[len(ORDERS) + 10] = {}; return {"orders": len(ORDERS)}
c = TestClient(app)
print("PUT twice :", [c.put("/v1/orders/1/note", json={"note": "b"}).json() for _ in range(2)])
print("DELETE twice:", [c.delete("/v1/orders/1").status_code for _ in range(2)])
print("POST twice :", [c.post("/v1/orders").json() for _ in range(2)], "<- NOT idempotent")Make the invisible visible: Real output.
PUT twice : [{'id': 1, 'note': 'b'}, {'id': 1, 'note': 'b'}]
DELETE twice: [204, 204]
POST twice : [{'orders': 1}, {'orders': 2}] <- NOT idempotentWhat you see: Both PUTs return the same state. Both DELETEs return 204. The two POSTs create two different resources, so the order count grows: that is why POST needs a key.
DELETE that errors on repeat
A retry looks like a failure.
@router.delete("/{id}")
def delete(id):
row = repo.get(id) # ❌ None on 2nd call
session.delete(row) # AttributeError, 500DELETE by end state
Safe to retry.
@router.delete("/{id}", status_code=204)
def delete(id):
repo.delete_if_exists(id)
return Response(status_code=204)The shift: Describe the state you want after the call, not the action you took.
Land it PUT and DELETE are idempotent by design if they describe an end state, and for POST and relative PATCH I add an Idempotency-Key.
- "Is it better for the second DELETE to return 404?"
Both are valid, and I choose by who the callers are. 204 on every call says "the end state is reached" and never makes a retrying client think something failed. A mobile app that lost its connection and retried would see success, not an error to show the user.
404 on the second call is more informative: it says "nothing was here". Some clients like that for logging or for catching bugs where the wrong id was sent. It is also what many REST frameworks do by default.
There is a security reason to lean to 204. If the resource belongs to a user, then "not yours" and "does not exist" must look the same, as in Q91, otherwise a caller can probe for ids. Returning 204 for a delete of an unknown or foreign id, while doing nothing, leaks nothing.
My rule is to pick one, document it, and test the second call. The wrong choice is a 500 or a 409 on the repeat, because a retrying client will keep retrying a failure that is really a success.
- "How does soft delete interact with idempotence?"
A soft delete keeps the row and marks it with
deleted_at. The trap is that a naive update sets the timestamp every time. The first call sets 10:00, a retry sets 10:01, and the audit trail now says the order was deleted at 10:01, which never happened as a user action.The fix is to make the update conditional:
UPDATE orders SET deleted_at = now() WHERE id = :id AND deleted_at IS NULL. A retry matches zero rows and changes nothing. You can then read the row count: one row means "deleted now", zero means "already gone or never existed", and both map to the same response.Reads must hide soft-deleted rows, with a filter in the repository or a view, otherwise a deleted order reappears in listings and a GET after DELETE returns 200.
One more edge: a unique constraint such as email must allow a new row after the old one is soft-deleted, which in PostgreSQL means a partial unique index
WHERE deleted_at IS NULL.- "What makes a PUT non-idempotent by accident?"
Hidden side effects. A PUT body that fully describes the end state is idempotent only if the server treats it as a state to reach, not as a recipe to follow. Three common accidents:
A counter bump, such as
version += 1oredit_count += 1, changes on every repeat. Appending to a list (adding an audit line or a history row) grows it with each retry. And sending a notification, an email or a webhook each time means ten retries produce ten messages.My fix is to compare before acting. Load the current state, and if the new state equals it, return success and do nothing. If something changed, do the update, bump the version once and emit the event once, inside one transaction. The outbox row is written only when the update really changed a row.
A version number that rises on a no-op write is a quiet cousin of this bug, because it breaks ETag caching and makes
If-Matchfail for no reason. And keep timestamps such asupdated_atout of the promise: they may differ between calls without breaking idempotence.- "Are PATCH operations ever idempotent?"
Sometimes, and it depends on what the patch says, not on the verb. HTTP does not promise PATCH is idempotent, because a patch can be a relative instruction. In practice, a patch that sets fields to given values is idempotent in effect.
{"status": "ready"}applied ten times leaves the order atready. (There is one catch: if status changes are checked against allowed transitions, the second call asks for ready to ready, which the state table may reject. Decide that it is accepted as a no-op.){"qty_delta": 1}is not idempotent, since each call adds another unit.I avoid relative changes in public APIs for this reason. If a client really needs "add one", expose it as an explicit action with an idempotency key, for example
POST /v1/carts/{id}/lineswith the key header (Q72, Q73), and store the first result.A safe habit: design PATCH as "set to value", add
If-Matchso concurrent patches do not overwrite each other, and put anything that counts, adds or sends behind a POST.
Q111. "Filtering and sorting query parameters safely."
Reveal answer
Strong answer Query parameters are user input that ends up in a database query, so the two risks are injection and cost. Injection happens when a parameter is pasted into SQL. Cost happens when a client asks for something that scans millions of rows.
For filtering, declare each filter as a typed parameter: an Enum for status, int for ids, a date with limits. FastAPI then rejects anything else with 422. A list filter (?status=ready&status=placed) uses list[Status] with Query().
For sorting, never insert the client's field name into ORDER BY. Accept an Enum of allowed names and look up the real column from a dictionary you control. Allow only columns that have an index and bound the page size with le=100.
Combine with cursor pagination (Q39) so deep pages stay fast. Do not offer arbitrary field filters like ?filter=any expression; each allowed filter should be a conscious, indexed choice.
Picture it A list route with an enum filter, an allow-listed sort and a bounded page size, with two hostile requests.
from enum import Enum
from typing import Annotated
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
class SortField(str, Enum):
created_at = "created_at"; total_cents = "total_cents"
class Status(str, Enum):
placed = "placed"; ready = "ready"; delivered = "delivered"
SORT_SQL = {SortField.created_at: "orders.created_at", SortField.total_cents: "orders.total_cents"}
app = FastAPI()
@app.get("/v1/orders")
def list_orders(status: Annotated[list[Status] | None, Query()] = None,
sort: SortField = SortField.created_at, desc: bool = True,
limit: Annotated[int, Query(ge=1, le=100)] = 20):
order_by = SORT_SQL[sort] + (" DESC" if desc else " ASC") # looked up, never concatenated from input
return {"where_status_in": status, "order_by": order_by, "limit": limit}
c = TestClient(app)
print(c.get("/v1/orders?status=ready&status=placed&sort=total_cents&desc=false").json())
r = c.get("/v1/orders?sort=total_cents;DROP TABLE orders"); print(r.status_code, r.json()["detail"][0]["msg"])
r = c.get("/v1/orders?limit=5000"); print(r.status_code, r.json()["detail"][0]["msg"])Make the invisible visible: Real output.
{'where_status_in': ['ready', 'placed'], 'order_by': 'orders.total_cents ASC', 'limit': 20}
422 Input should be 'created_at' or 'total_cents'
422 Input should be less than or equal to 100What you see: The valid request becomes a controlled SQL fragment, orders.total_cents ASC, looked up from a dictionary. The injection attempt and the oversized limit are both rejected with 422 before any query is built.
Pasted into SQL
Injection waiting to happen.
# ❌ TRAP: user text inside the query
q = f"SELECT * FROM orders ORDER BY {sort}"
db.execute(text(q))Looked up
Only known columns are possible.
SORT = {SortField.created_at: Order.created_at,
SortField.total_cents: Order.total_cents}
stmt = select(Order).order_by(
SORT[sort].desc())The shift: Let the client choose among options you wrote, not write the query.
Land it Every filter is a typed, indexed parameter, sort names are looked up from an allow-list, and page size is capped.
- "How do I support multi-column sorting?"
Accept a comma-separated list of allowed names, with a minus sign for descending:
?sort=-created_at,total_cents. Each name is checked against an allow-list, never pasted into SQL.The steps are short. Split on commas, reject more than two or three keys, strip the optional minus, look each name up in a dictionary such as
{"created_at": Order.created_at, "total_cents": Order.total_cents}, and answer 422 for anything not in it. Then buildorder_by(col.desc())orcol.asc()from the real column objects.Always add a final tie-breaker on
id. Without it, rows with equal values can come back in a different order on each call, so offset pages repeat or skip rows, and cursor pagination breaks outright, since the cursor needs a total order to say "after this row".Allow only columns that have an index, ideally a composite one that matches the common sort. Multi-column sort on unindexed columns makes the database sort the whole result set in memory for every request, which is the cost risk from the main answer.
- "How do I allow text search safely?"
Treat the search text as data. Bind it as a parameter,
Order.note.ilike("%" + escaped + "%")through SQLAlchemy, ortext("... ILIKE :q")with{"q": value}, and never build the SQL string by concatenation. Escape%and_in the user's text if they should be literal.Safety from injection is not the same as being cheap. A
LIKE '%x%'with a leading wildcard cannot use a normal B-tree index, so the database reads every row. On ten million rows that is seconds, and fifty users doing it at once is an outage.The options, from least to most work: prefix search (
LIKE 'x%') with a suitable index; PostgreSQL trigram indexes (pg_trgmwith GIN) for substring matching; full-text search (tsvector) for words; or a search engine for ranking and typos.Whatever you choose, cap the length of
q(say 64 characters), require at least 2 or 3 characters, and rate-limit the route.- "What about filtering on a related table?"
Expose it as one specific, named filter, such as
?restaurant_id=5or?customer_id=12, and write the join yourself. The client never says how to join; it only says which value to filter on.Each such filter is a conscious choice with three parts. The parameter is typed (an int, not a string). The column it touches has an index, for example
orders(restaurant_id, created_at). And it is covered by a test and by anEXPLAINcheck that the query does not scan the whole table.A generic path like
?filter=restaurant.owner.country=INlets a client trigger a chain of joins you did not plan for. A three-table join that is fast on test data can be very slow on production volumes, and the client can ask for it in a loop.Also think about authorisation: a filter on a related table can leak information, for example filtering by another customer's id. The repository must still add the caller's own scope to every query, whatever filters are present.
- "What if a client needs a filter I did not provide?"
Treat it as a feature request, not as an excuse to loosen the API. The client says what question they need to answer. You decide whether it deserves a supported path.
If yes, the work is small and the same each time: add the typed query parameter, add or check the index, add a test that includes a boundary case, and update the OpenAPI description, which FastAPI generates from the code. Because each step is explicit, the review also asks "how often will this be called, and what does it cost?"
If the need is analytics, such as "all orders by any combination of fields", the right answer is often not this API at all but a reporting database or an export job (Q105), where slow queries do not share capacity with the checkout path.
The friction is the point. Open-ended filters mean you cannot predict the worst query, and the one nobody anticipated is the one that takes the database down on a Friday night.
Q112 · Scenario. "Orders show the wrong day for customers in India. Fix it in the API layer."
Reveal answer
The real test Whether you store and transmit time in UTC with offsets, and convert at the edge using the customer's zone.
Strong answer The bug usually has one of two sources. The server groups or formats orders by its own time zone (often UTC), so an order placed at 02:00 on 25 November in India (UTC+5:30) is the 24th in UTC. Or timestamps are stored or sent as naive datetimes with no offset, so the client guesses.
The rules: store instants in UTC (TIMESTAMPTZ in PostgreSQL). Send them as ISO 8601 with an offset or Z. Reject naive datetimes at the API boundary with AwareDatetime. Convert to a local zone only for display or for "day" calculations, using the customer's IANA zone (Asia/Kolkata), never a fixed offset, because offsets change with daylight saving.
For "orders on 25 November", compute the day's start and end in the customer's zone, convert both to UTC, and query a half-open range [start, end). Do not cast the stored column to a date.
Picture it One order, viewed three ways, and a day range calculated correctly.
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from pydantic import AwareDatetime, BaseModel, ValidationError
IST = ZoneInfo("Asia/Kolkata")
class OrderOut(BaseModel):
created_at: AwareDatetime # naive datetimes are rejected at the edge
stored_utc = datetime(2026, 11, 24, 20, 30, tzinfo=timezone.utc) # 02:00 on the 25th in India
print("API output (UTC, ISO 8601):", OrderOut(created_at=stored_utc).model_dump_json())
print("customer's wall clock :", stored_utc.astimezone(IST).isoformat())
print("day if we cut at UTC :", stored_utc.date(), "<- wrong day for the customer")
print("day in customer's zone :", stored_utc.astimezone(IST).date())
start = datetime(2026, 11, 25, tzinfo=IST).astimezone(timezone.utc) # 'orders for 25 Nov' as a UTC range
print("range for 25 Nov in IST :", start.isoformat(), "->", (start + timedelta(days=1)).isoformat())
try: OrderOut(created_at="2026-11-24T20:30:00")
except ValidationError as e: print("naive input :", e.errors()[0]["type"])Make the invisible visible: Real output.
API output (UTC, ISO 8601): {"created_at":"2026-11-24T20:30:00Z"}
customer's wall clock : 2026-11-25T02:00:00+05:30
day if we cut at UTC : 2026-11-24 <- wrong day for the customer
day in customer's zone : 2026-11-25
range for 25 Nov in IST : 2026-11-24T18:30:00+00:00 -> 2026-11-25T18:30:00+00:00
naive input : timezone_awareWhat you see: The API sends 20:30:00Z, an unambiguous instant. In India it is 02:00 on the 25th, but cutting by the UTC date gives the 24th. The correct range for "25 Nov in India" runs from 18:30 UTC on the 24th to 18:30 UTC on the 25th, and a naive input is rejected with timezone_aware.
Server's date
The calendar day of UTC.
# ❌ TRAP: server day, not customer day
day = order.created_at.date()
today = date.today()Customer's zone
Convert, then compare ranges.
tz = ZoneInfo(user.tz) # "Asia/Kolkata"
start = datetime.combine(d, time(), tz)
end = start + timedelta(days=1)
q = where(Order.created_at >= start,
Order.created_at < end)The shift: An instant has one value everywhere; a calendar day exists only inside a zone.
Land it I store UTC, transmit ISO 8601 with offsets, reject naive datetimes, and compute customer-day ranges in the customer's IANA zone at the API edge.
- "Where do I get the customer's time zone?"
Use the customer's own setting, and check it. The best source is the profile, saved once when the customer signs up from the device's zone name, for example
Asia/Kolkata. A second option is a request header such asX-Timezonesent by the app, which is useful for guests.Validate whatever arrives.
zoneinfo.available_timezones()lists the valid IANA names, andZoneInfo(name)raisesZoneInfoNotFoundErrorfor a bad one, which you turn into a 422. Never trust an offset such as "+05:30" as a stand-in, because offsets do not know about daylight-saving changes.The right zone depends on the question. For "my orders today" in the customer app, it is the customer's zone. For a restaurant's dashboard or daily totals, the business day belongs to the restaurant, so use the restaurant's own zone, otherwise a kitchen in Mumbai sees its evening orders split across two days when a manager views it from London.
Fall back to a stated default, and document it.
- "Why not store local time?"
Because a local time can be ambiguous or missing, and it loses information. Clocks change twice a year in many countries. When they go back, the same wall time, say 01:30, happens twice, and a stored "01:30" does not say which. When they go forward, a time such as 02:30 does not exist at all.
A UTC instant has none of these problems. It names one exact moment, it sorts correctly, and subtraction gives a true duration. Any local time can be computed from it when needed, using the rules of the zone at that date.
India has no daylight saving, so India looks safe, but your code runs for other zones as well, and a restaurant chain may open in one.
If you need to remember which zone a person meant, such as the time of a reservation, store the zone name in a separate column next to the UTC instant. Do not store the local string. The rule I teach: store instants in UTC, store zone names as data, convert at the edge.
- "How do I serialise datetimes consistently in FastAPI?"
The goal is one format everywhere. The details are short.
- Declare the type: use
datetimewithAwareDatetimein request models so naive values are rejected with 422, and plaindatetimefields in responses that always hold aware values. - Let Pydantic emit it: in JSON mode a UTC value comes out as
2026-11-24T20:30:00Z; other offsets such as+05:30stay as they are. - Normalise inputs: accept any offset, but convert to UTC before storing, so comparisons never involve mixed zones.
- State it in the contract: say once that every timestamp is ISO 8601 with an offset.
Do not mix epoch seconds in one endpoint and strings in another. Clients end up writing special cases, and the first mistake shows up as a bug exactly like the wrong day.
- Declare the type: use
- "What should tests do about "now"?"
Inject a clock (Q123), so each test chooses the instant instead of reading the machine's. Business code asks
clock.now(), production wires the real UTC clock, and a test passes a fixed one.Then test the boundaries on purpose. The scenario here needs three checks, using
Asia/Kolkata: an order at 23:59:59 local belongs to that day, one at 00:00:01 belongs to the next, and the same instant gives a different date in UTC. Here is the arithmetic, run for real.q112_day_range.pyruns offlineUTC date : 2026-11-24 India date: 2026-11-25 25 Nov in India = [ 2026-11-24T18:30:00+00:00 , 2026-11-25T18:30:00+00:00 )The range is half-open: the start is included and the end is not, so an order at exactly midnight lands in one day only. Also add a test across a daylight-saving change in another zone, where a day has 23 or 25 hours, so a hard-coded 24-hour day fails visibly.
Q113. "Money in APIs: Decimal, minor units and serialisation."
Reveal answer
Strong answer Never use float for money. Binary floating point cannot store 0.1 exactly, so sums drift (0.1 + 0.2 is 0.30000000000000004), and rounding errors accumulate in totals, taxes and refunds.
There are two sound representations. Minor units (integer cents, total_cents: 19990) are simplest and what the canonical app uses: addition and comparison are exact, the database column is a plain integer, and JSON carries an integer every language reads the same way. Decimal (Decimal("199.90")) is fine in Python and in a database NUMERIC column, when you need fractions of a cent (fuel prices) or must apply tax percentages.
Serialising Decimal is the trap. Pydantic writes it as a JSON string ("199.90") in JSON mode, precisely to protect precision, because a JSON number would be parsed by JavaScript as a float. Decide that in the contract and make clients parse the string.
Always pair an amount with a currency code (ISO 4217), and decide the rounding mode (banker's or half-up) once, in one function, for every tax and discount calculation.
Picture it The same arithmetic in three representations, and how Pydantic serialises a Decimal.
from decimal import Decimal
from pydantic import BaseModel
print("float :", 0.1 + 0.2, "| 3 x 0.1 =", 3 * 0.1, "| sum of 10 x 0.1 =", sum([0.1] * 10))
print("Decimal:", Decimal("0.1") + Decimal("0.2"), "| from float:", Decimal(0.1))
print("cents :", 10 + 20, "(int, exact)")
class Price(BaseModel):
amount: Decimal
cents: int
p = Price(amount=Decimal("199.90"), cents=19990)
print("pydantic JSON:", p.model_dump_json(), "<- Decimal becomes a STRING")
print("pydantic dict:", p.model_dump())
print("JS parse of 0.1+0.2 would give 0.30000000000000004; of '199.90' a string you must parse yourself")Make the invisible visible: Real output.
float : 0.30000000000000004 | 3 x 0.1 = 0.30000000000000004 | sum of 10 x 0.1 = 1.0
Decimal: 0.3 | from float: 0.1000000000000000055511151231257827021181583404541015625
cents : 30 (int, exact)
pydantic JSON: {"amount":"199.90","cents":19990} <- Decimal becomes a STRING
pydantic dict: {'amount': Decimal('199.90'), 'cents': 19990}
JS parse of 0.1+0.2 would give 0.30000000000000004; of '199.90' a string you must parse yourselfWhat you see: Float gives 0.30000000000000004. Decimal and integer cents give exactly 0.3 and 30. A Decimal field is dumped as the string "199.90" in JSON, and stays a Decimal in Python mode.
Float
Errors accumulate silently.
# ❌ TRAP: float money
class OrderOut(BaseModel):
total: float # 199.9 -> 199.89999Integer cents
Exact and portable.
class OrderOut(BaseModel):
total_cents: int = 19990
currency: str = "INR"The shift: Count the smallest unit as a whole number; format for humans only at the screen.
Land it I store and send money as integer minor units with a currency code, use Decimal only where fractions matter, and round in exactly one place.
- "How do I handle currencies with different minor units?"
Never hard-code
100. Most currencies have two decimal places, but the Japanese yen has none, the Kuwaiti dinar has three, and a few others differ. ISO 4217 defines the exponent for each currency code.So the API stores and sends an integer in the currency's smallest unit, together with the code:
{"amount": 1999, "currency": "INR"}means 19.99 rupees, and{"amount": 1999, "currency": "JPY"}means 1,999 yen. The same integer means different money, which is why the code must travel with it.Keep a small table of exponents by code (
INR: 2, JPY: 0, KWD: 3), loaded from a library or a reviewed file, and use it for two things only: converting to a display string and parsing user input such as "199.90".Everything in between, sums, comparisons and tax, works on integers and never needs the exponent. Reject mixed-currency arithmetic with an error, since adding rupees to yen is a bug, not a calculation.
- "How do I compute tax without float?"
Use integers and round once. Tax is a percentage of an amount, and a percentage of whole cents is usually not a whole number, so you must choose where the rounding happens.
With integer cents, express the rate in basis points (one hundredth of a percent), so 18 percent is 1800. Then multiply, add half the divisor, and use integer division, which rounds half up. I ran this for a 19,990 cent subtotal.
q113_money.pyruns offlineprint((subtotal * 1800 + 5000) // 10000) # 3598 print(0.1 + 0.2) # 0.30000000000000004 print(Decimal("0.1") + Decimal("0.2")) # 0.3The exact value is 3598.2 cents, and the function returns 3598. The alternative is
Decimalwithquantize(Decimal("1"), rounding=ROUND_HALF_UP), which gives the same result.The rule that matters is one tested function used by the whole code base, and a decision on whether tax is rounded per line or on the total, because the two can differ by a cent or two and an accountant will ask.
- "What about prices shown as
199.90in the UI?" Format it in the client, from the integer and the currency code, using the locale's rules. The API sends
{"amount": 19990, "currency": "INR"}, and the app decides how it looks for this user.Pre-formatted strings from the server look helpful but cause real trouble. The format is a presentation matter that changes by language and region: India groups digits as 1,99,900.00 while many countries use 199,900.00, and some put the symbol after the number. A server that formats must know the viewer's locale, and a client that must read the string back has to parse it, which is a source of bugs, because commas and dots swap meaning between locales.
Use the platform's tools:
Intl.NumberFormatin browsers,NumberFormaton Android and iOS. They know the exponent and the symbol for each code.One exception is receipts and invoices produced as documents. There the server renders a fixed, legal format, but it still keeps the integer as the source of truth and formats at the last step.
- "Is
NUMERICin PostgreSQL always right?" It is exact, and it is a good choice when you need it.
NUMERIC(12, 2)means 12 digits in total with 2 after the decimal point, so values up to 9,999,999,999.99. Declare precision and scale explicitly, because a bareNUMERICaccepts any number of digits and hides mistakes.SQLAlchemy returns a Python
Decimalfor it, and Pydantic accepts that and, in JSON mode, writes it as a string such as"199.90". So the contract must say clients parse strings. Do not convert throughfloatanywhere on the path, since that reintroduces the problem.Integer cents are simpler and faster: the column is a plain
BIGINT, comparison and sums are trivial, and JSON carries a number every language reads the same way. That is why the canonical app uses them.I choose
NUMERICwhen fractions of a cent are a real requirement, for example fuel prices, per-unit rates or currency conversion, and integers otherwise.
Q114. "gRPC versus REST for internal Python services."
Reveal answer
Strong answer gRPC uses HTTP/2 and Protocol Buffers: you write a .proto file describing services and messages, generate typed client and server code, and send compact binary messages over multiplexed streams. REST over JSON uses human-readable resources over HTTP, usually HTTP/1.1 or 2.
gRPC gives smaller payloads, strict contracts checked at build time, built-in deadlines and streaming in both directions, and generated clients in many languages. Its costs: harder debugging (binary, needs special tools), no direct browser support without a proxy (gRPC-Web), a code generation step in every build, and more friction for load balancers and caches.
Use gRPC for internal, high-volume, latency-sensitive calls between services you control, especially in polyglot teams that benefit from generated clients. Use REST for public APIs, browser clients, partner integrations and anything where ease of use and debugging matter most.
In Python, the grpcio package is installed on the course machine; async servers use grpc.aio. FastAPI itself is a REST framework: a service that needs both runs a gRPC server beside it, sharing the same service layer.
Picture it The two contracts for the same call, "get an order".
REST (FastAPI)
Contract is the OpenAPI document.
@router.get("/{order_id}",
response_model=OrderOut)
def get(order_id: int): ...
# curl localhost:8000/v1/orders/17gRPC
Contract is the .proto file.
service Orders {
rpc Get(GetOrder) returns (Order);
}
message GetOrder { int64 order_id = 1; }
message Order { int64 id = 1;
string status = 2; }The shift: With REST the contract is documentation generated from code; with gRPC the contract comes first and code is generated from it.
| Pick it when | Cost or catch | |
|---|---|---|
| REST + JSON | public API, browsers, partners, simple debugging with curl | larger payloads, weaker typing, streaming is awkward |
| gRPC | internal service-to-service, high volume, streaming, many languages | binary debugging, browser needs a proxy, code generation step |
| GraphQL | many different clients need flexible shapes of the same data | caching and cost control are harder, N+1 risk on the server |
| Message queue or Kafka | work does not need an immediate answer | no direct reply, eventual consistency |
Land it I use REST for anything public or browser-facing and consider gRPC for internal hot paths where typed contracts and streaming earn the extra tooling.
- "What changes for load balancing with gRPC?"
The problem is that gRPC keeps one long-lived HTTP/2 connection and sends many calls over it. A load balancer that works at the connection level (layer 4) picks a backend once, when the connection opens, so every call from that client goes to the same pod. With three clients and ten pods, seven pods may sit idle.
There are two fixes. The first is a layer 7 balancer that understands HTTP/2 and can spread individual calls across backends, such as Envoy, or a service mesh that includes it. The second is client-side balancing, where the gRPC client resolves a list of backend addresses (often through a headless Kubernetes service) and rotates among them with
round_robin.Also watch what happens at scale-up. New pods get no traffic until clients open new connections, so set a maximum connection age on the server (
MAX_CONNECTION_AGE), which makes clients reconnect and spread out.I check this with a per-pod request counter during a load test. If one pod is hot, the balancer is the cause.
- "How do I handle versioning in gRPC?"
Protocol Buffers were designed for change, as long as you follow a few rules. Every field has a number, and the number, not the name, is what goes on the wire. Adding a field with a new number is safe: old clients ignore it, and old messages read by new code show the default value.
The rules to remember are these. Never change the type or meaning of an existing field number. Never reuse a number of a deleted field. When you remove a field, add
reserved 4; reserved "old_name";so nobody reuses it by accident. Prefer new optional fields over changing old ones. Enum values can be added, but clients must handle values they do not know.Breaking changes, such as a different shape for a response, go into a new package or service version (
orders.v2), served next tov1until all clients move.A tool such as
buf breakingcan compare the new.protofiles with the last release in CI and fail on a break, the counterpart of an OpenAPI diff for REST.- "How do deadlines work?"
A deadline is an absolute point in time by which the whole call must be finished. The caller sets it once, for example 800 ms from now, and the gRPC library sends it along as a header. Each service that receives it can read how much time remains.
The strength is propagation. When the order service calls payments and then the maps service, it passes the same deadline, so each call gets only the time that is left. If 600 ms of the 800 have gone, the next call has 200 ms. When the deadline passes, the call fails with
DEADLINE_EXCEEDEDand the work is cancelled everywhere down the chain, so servers stop wasting effort on a request nobody is waiting for.In REST, you must do this by hand: each service picks its own timeout, and the timeouts add up. A 2 second timeout in each of three nested calls can mean 6 seconds for the user (Q98). Some REST setups copy a deadline header, but nothing in the protocol demands it.
In gRPC I always set a deadline on the client. The default is none, which means wait forever.
- "Can one service expose both?"
Yes, and it is a good design when you have both kinds of callers. The business logic lives in a service layer with no knowledge of any protocol. On top sit two thin adapters: a FastAPI router for REST and a gRPC servicer class generated from the
.proto. Both parse their input, call the same service method and format the result.Errors need translation in each adapter. The domain error
OutOfStockbecomes HTTP 409 in the REST adapter andFAILED_PRECONDITIONin the gRPC one; a missing order is 404 in one andNOT_FOUNDin the other. Keep the mapping tables next to each adapter, so the services stay protocol-free.Run both in one process for simplicity (uvicorn for REST,
grpc.aioserver on another port, started in the lifespan) or as separate deployments if their scaling differs.The cost is two interfaces to keep consistent. I would add tests that call both with the same input and compare the outcome, so behaviour cannot drift.
Q115 · Design. "Design the QuickBite restaurant dashboard API (live orders, status updates)."
Reveal answer
Strong answer The dashboard has two needs: a reliable list of what is happening right now, and a live feed of changes. I separate them so a lost connection never loses data.
Reads: GET /v1/restaurants/{id}/orders?status=placed,preparing&cursor= returns active orders with cursor pagination, sorted by creation time. It is the source of truth and is what the page loads on start and after every reconnect. Live feed: GET /v1/restaurants/{id}/orders/stream as server-sent events, each event carrying an id (a monotonically increasing event number) and a small payload (order id, new status). The client reconnects with Last-Event-ID and the server replays missed events from a short log.
Writes: PATCH /v1/orders/{id} with {"status": "preparing"} and If-Match. The service checks the allowed transition (placed to preparing to ready), rejects others with 409 invalid-status-transition, writes an event to the outbox in the same transaction, and returns the new ETag.
Auth: staff tokens with restaurant:orders:read and restaurant:orders:update, plus a repository filter on the staff member's restaurant id (Q91).
Picture it The endpoint table I would draw first.
| Endpoint | Purpose | Notes |
|---|---|---|
| GET /v1/restaurants/{id}/orders | active orders, cursor paged | ETag, limit max 100, sort by created_at, id |
| GET /v1/restaurants/{id}/orders/stream | live changes (SSE) | heartbeat 15 s, ids for replay, X-Accel-Buffering: no |
| PATCH /v1/orders/{id} | change status | If-Match, transition rules, 409 / 412 |
| GET /v1/restaurants/{id}/summary | counts per status | cached 5 s, Cache-Control: private |
Poll everything
Whole list every 2 seconds.
// illustrative
setInterval(async () => {
const all = await fetch("/orders"); // ❌
render(await all.json());
}, 2000);Snapshot + stream
One load, then deltas.
// illustrative
render(await (await fetch(url)).json());
const es = new EventSource(streamUrl);
es.onmessage = e => apply(JSON.parse(e.data));
// reconnect resumes via Last-Event-IDThe shift: Fetch the state once, then listen for changes, and always be able to refetch the state.
Land it A cursor-paged list as the source of truth, an SSE stream with replayable event ids for live changes, and a PATCH with If-Match and transition rules for updates, all behind restaurant-scoped authorisation.
- "How do the events get from the order service to the stream?"
The goal is that the dashboard hears about a change within a second or two, from a pod that did not handle it. There is a chain with four links.
- Commit: the PATCH changes the order status and inserts an outbox row in the same transaction, so the event exists if and only if the change does.
- Relay: a small process reads new outbox rows and publishes them to a broker, Redis streams or Kafka, with the restaurant id as the key so one restaurant's events stay in order.
- Fan-out: every API pod subscribes, filtered by the restaurants whose dashboards are connected to it, and writes each event to those SSE connections with the event id.
- Replay log: the same events go into a short store, say the last 1,000 per restaurant, for reconnects.
No pod needs to know which pod took the PATCH. The cost is a few hundred milliseconds of delay and the relay to operate, and the gain is that the live feed and the database cannot disagree for long.
- "What if a tablet is offline for an hour?"
Then the client uses the list endpoint, which is always the source of truth. On reconnect it sends
Last-Event-ID: 8412. The server checks its replay log. If events from 8413 onward are still there, it sends them in order and the dashboard catches up smoothly.If the id is older than the window, for example the log only keeps the last hour or 1,000 events, the server cannot be sure what was missed. It sends one special event,
event: resync, and the client throws away its local list and callsGET /v1/restaurants/{id}/orders?status=placed,preparingagain. That list is small, since it holds only active orders, so a refetch is cheap.Every resync path depends on the list being correct, so the event stream is only an optimisation on top of it.
A tablet that has been off for an hour does not need to replay anything useful anyway. It needs the current state, and the list gives exactly that. I test by killing the connection, waiting longer than the window and checking the screen heals.
- "How would you reduce load from 500 restaurants?"
The structure does most of the work. Per-restaurant channels mean an event goes only to that restaurant's connections, not to all 500. If each restaurant has two tablets, that is 1,000 connections in total, which a few pods hold easily as idle sockets.
The list endpoint is small (active orders only, say 10 to 30 rows) and has an ETag, so a refresh is often a 304 with no body. A 5 second server-side cache of the summary absorbs refresh-happy staff who tap the reload button. Heartbeats every 15 seconds keep connections alive without much cost.
As a rough load figure: 500 restaurants times 60 orders an hour times 4 status changes is 120,000 events an hour, about 33 a second across the whole system, which is light.
What I would watch is the number of open connections per pod, event delivery delay, and reconnect storms after deploys, which I smooth with client-side jitter (Q107). If that were not enough, scale pods out, since the pub/sub design needs no stickiness.
- "What about order sound alerts and notifications?"
Those are client behaviours driven by the same events. The dashboard tab, when open, plays a sound when it receives an event whose new status is
placed. The server only has to make the event clear: order id, status, and a timestamp.The harder case is a tablet that sleeps or a browser tab that is in the background. Browsers throttle or suspend background pages, and a sleeping device closes its network connections, so an SSE stream cannot be relied on to wake it. For those, add push notifications (web push, or Firebase Cloud Messaging on Android), sent by a worker that consumes the same outbox events and decides whom to notify.
Make the alert idempotent. If the tablet reconnects and replays events, it must not ring five times for an order it already announced. Keep the last announced order id in local storage and compare.
I keep the roles separate: SSE is for screens that are open, push is for screens that are not, and the list endpoint is what the staff member sees when they come back.
11 · DrillTesting, Performance and Deployment — Q116–Q150
The last thirty-five questions ask what happens after the code works: how you prove it keeps working, how you see it in production, how fast it is and where the time goes, and how it ships without dropping a request. Senior interviews often end here, because these are the topics where experience shows. Expect follow-ups of the form "what number did you measure?"
Numbers below come from the course machine (12 cores) with FastAPI 0.141.1, uvicorn 0.53 and Python 3.12; yours will differ, so trust the shape of the result more than the digits. Scripts are in code/e20-python-api/E/; the canonical app is the one from section 07.
These questions test whether your tests are fast, isolated and honest: a clean database per test, the right client for the job, and no mocks that make a bug invisible.
Q116. "TestClient versus httpx.AsyncClient with ASGITransport — when do you use each?"
Reveal answer
Strong answer TestClient is a synchronous wrapper. You write ordinary def test_... functions and call client.get(...). Behind the scenes it runs your ASGI app on a background event loop thread. It also runs the lifespan (startup and shutdown) when you use it as a context manager, and it supports WebSockets. It is the default for most API tests.
httpx.AsyncClient(transport=ASGITransport(app=app)) calls the app directly on your event loop with await. Use it when the test itself must be async: it awaits other async code (an async SQLAlchemy session, an async fixture), or it must share one loop with the app's resources.
Two gotchas. ASGITransport does not run lifespan, so startup code never runs unless you enter app.router.lifespan_context(app) yourself (or use the asgi-lifespan package). And it buffers the whole response, so streaming and SSE cannot be tested with it.
My rule: TestClient for sync-style tests, lifespan, WebSockets and streaming; AsyncClient for tests that must be async anyway.
Picture it The same app through both clients, watching whether startup ran.
import asyncio, httpx
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.testclient import TestClient
events = []
@asynccontextmanager
async def lifespan(app):
events.append("startup"); yield; events.append("shutdown")
app = FastAPI(lifespan=lifespan)
@app.get("/ping")
async def ping(): return {"pong": True}
c = TestClient(app); print("TestClient (no with): ", c.get("/ping").json(), events)
with TestClient(app) as c: print("TestClient (with): ", c.get("/ping").json(), events)
events.clear()
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as ac:
r = await ac.get("/ping"); print("AsyncClient+ASGITransport:", r.json(), events, "<- lifespan did NOT run")
events.clear()
async with app.router.lifespan_context(app): # run lifespan yourself (or use asgi-lifespan)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as ac:
await ac.get("/ping"); print("with lifespan_context: ", events)
print("after exit: ", events)
asyncio.run(main())Make the invisible visible: Real output.
TestClient (no with): {'pong': True} []
TestClient (with): {'pong': True} ['startup']
AsyncClient+ASGITransport: {'pong': True} [] <- lifespan did NOT run
with lifespan_context: ['startup']
after exit: ['startup', 'shutdown']What you see: Without with, TestClient never runs lifespan ([]); with it, startup runs and shutdown fires on exit. AsyncClient with ASGITransport also skips lifespan, shown by the empty list, until the test enters lifespan_context itself.
Spring Boot
Slice tests with MockMvc.
// illustrative
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@Test void get() throws Exception {
mvc.perform(get("/v1/orders/1"))
.andExpect(status().isOk());
}
}FastAPI
Plain function, plain client.
def test_get(client):
r = client.get("/v1/orders/1")
assert r.status_code == 200
async def test_async(async_client):
r = await async_client.get("/v1/orders/1")
assert r.status_code == 200The shift: No test runner extension or annotation magic: a client object and ordinary functions.
Land it TestClient for most tests and lifespan, AsyncClient with ASGITransport when the test itself is async, and I remember that ASGITransport skips lifespan.
- "Do I need pytest-asyncio or anyio for async tests?"
Yes. A test function that is
async defis a coroutine, and pytest by itself only calls it and throws the coroutine away, so the body never runs and the test seems to pass. A plugin must drive the event loop for you.pytest-asynciois installed on the course machine. You mark tests with@pytest.mark.asyncio, or setasyncio_mode = autoinpyproject.tomlso every async test and fixture is collected.anyio's pytest plugin works too and also runs against trio, which matters only if you use trio.Pick one and set it in configuration, not in each file. Mixing the two, or leaving the mode on strict while forgetting a marker, gives tests that silently do nothing, or fixtures that are never awaited and arrive as coroutine objects.
Also set the loop scope on purpose (Q118). An async fixture that builds a database engine must live on the same loop as the tests that use it. A sync suite that uses
TestClientneeds none of this, which is one more reason it is my default.- "Which is faster?"
For a single small test the difference is milliseconds and not worth caring about.
TestClientstarts a background thread with an event loop (the portal) the first time you use it, which costs a few milliseconds, and then each request crosses between threads.AsyncClientwithASGITransportcalls the app directly on your loop, with slightly less overhead per request.So the advice is about structure. Create one client per fixture, and use it as a context manager so the portal starts once, not once per request. A test that creates a new
TestClient(app)for each call pays the start-up each time.The big costs in a suite are elsewhere: creating the app, building the database schema, seeding data and importing heavy libraries. If 500 tests each spend 4 ms on the client, that is 2 seconds. If each also rebuilds an engine and tables for 20 ms, that is 10 seconds.
I measure with
pytest --durations=10before optimising anything, and in my experience the slowest fixtures are the real target, not the HTTP client.- "Can
TestClientraise server errors into my test?" By default yes, and that is useful.
TestClient(app)hasraise_server_exceptions=True. If a route raises an exception that no handler catches, Starlette still sends the 500 response, but the client then re-raises the original exception in your test. A bug shows up as a traceback pointing at the faulty line, not as a vague "assert 500 == 200".Sometimes you want the other behaviour. A test about the 500 response itself, such as "an unexpected error returns the generic body without leaking the exception text", must see the response. Set
raise_server_exceptions=False, and then you can assert on the status, the problem body and the request id.The canonical
conftest.pydoes exactly this in a separate client fixture. I keep two fixtures,client(strict) andclient_500(lenient), so the choice is visible in the test signature.Handled errors, such as your own domain errors turned into 409, are not affected: they are normal responses, and the flag matters only for exceptions that escape every handler.
- "Does either client hit a real network?"
No, and that is both a strength and a limit. Both clients call the ASGI application as a Python function in the same process. No socket is opened, no port is bound, and nothing goes through uvicorn.
So they cannot catch problems that live outside the app: uvicorn flags (workers, timeouts, limits), the reverse proxy and its buffering or body-size rules, TLS and certificates, DNS, real network timeouts (Q98), HTTP/2 behaviour, and header changes made by proxies. The SSE cut-off at 60 seconds in Q108 is a typical example that no in-process test can see.
That is the reason for a few smoke tests against a built container, run in CI or after deploy: call
/healthz, make one authenticated request, and open one stream. They are slow and few, but they check the thing you actually ship.A good split is hundreds of fast in-process tests for logic and contract, and a handful of real-network checks for the deployment path. Keep them separate with a pytest marker, so developers can run the fast set on every save.
Q117. "How do you give every test a clean database?"
Reveal answer
Strong answer Isolation means a test never sees rows left by another test, so the suite passes in any order and in parallel. There are three common ways, ordered from fastest to most faithful.
- Fresh in-memory SQLite per test: create an engine with
StaticPool(one shared connection, which an in-memory database needs), create the tables, seed, yield, dispose. Costs a few milliseconds. The canonicalconftest.pydoes this. - Transaction rollback: open a connection and a transaction at the start of the test, bind the session to it, roll back at the end. Fast on a real database such as PostgreSQL, but code under test that commits needs a savepoint trick to stay inside the outer transaction.
- Template database or truncate: for PostgreSQL, create a template database once and clone it per test, or
TRUNCATE ... RESTART IDENTITY CASCADEbetween tests. Slower, but the code under test can commit for real.
Whatever you choose, build the schema once per session and the data per test, and never rely on test order. Do not share a module-level engine that tests mutate.
Picture it Two tests whose fixture creates a new empty database each time. The second one asserts there are no rows, though the first inserted one.
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.pool import StaticPool
@pytest.fixture
def engine():
e = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
with e.begin() as c:
c.execute(text("CREATE TABLE orders (id INTEGER PRIMARY KEY, total_cents INTEGER)"))
yield e # each test gets its own empty in-memory database
e.dispose()
def count(e):
with e.connect() as c: return c.execute(text("SELECT count(*) FROM orders")).scalar()
def test_a_inserts(engine):
with engine.begin() as c: c.execute(text("INSERT INTO orders (total_cents) VALUES (1200)"))
assert count(engine) == 1
def test_b_starts_empty(engine):
assert count(engine) == 0 # passes in ANY order: no leftovers from test_aMake the invisible visible: Real pytest output.
test_clean_db.py::test_a_inserts PASSED [ 50%]
test_clean_db.py::test_b_starts_empty PASSED [100%]Running teardown with pytest sessionfinish...
============================== 2 passed in 0.36s ===============================Why: Both pass, and they would pass in either order, because each test got its own database. The key detail is poolclass=StaticPool: without it every new connection to sqlite:// opens a different empty in-memory database, and the tables vanish.
Shared database
Tests depend on each other.
# ❌ TRAP: one engine for the module
engine = create_engine("sqlite:///test.db")
def test_a(): insert(); assert count()==1
def test_b(): assert count()==0 # failsEngine per test
Always starts empty.
@pytest.fixture
def engine():
e = create_engine("sqlite://",
poolclass=StaticPool)
Base.metadata.create_all(e)
yield e; e.dispose()The shift: Each test builds its own world, so no test can depend on another.
Land it Every test gets a fresh database through a fixture, either an in-memory engine with StaticPool or a rolled-back transaction, and no test relies on order.
- "Why does the in-memory SQLite database need
StaticPool?" Because of how SQLite works with memory. An in-memory database (
sqlite://) exists only inside a single connection. When that connection closes, the data is gone, and a new connection opens a different, empty database.SQLAlchemy's default pool for in-memory SQLite may hand different connections to different threads.
TestClientruns the app in its own thread, so a table created by the test thread would be invisible to the app thread, and you would see "no such table" errors that look like a bug in your code.StaticPoolfixes this by keeping exactly one connection and giving the same one to everybody. Addconnect_args={"check_same_thread": False}, because SQLite by default refuses to use a connection from a thread other than the one that created it. With both settings, the test thread, the app thread and the seed code all see the same database.The trade-off is that all access shares one connection, so work is serialised. That is fine in tests, and it is one reason why concurrency tests need PostgreSQL (Q120).
- "How do I run tests in parallel?"
Parallel runs need isolation between workers, not just between tests. With
pytest-xdist(pytest -n 4), several processes run tests at the same time.- In-memory per test: each test builds its own engine, so nothing is shared, and no special work is needed. This is why the canonical suite parallelises easily.
- PostgreSQL: derive a database name from the worker id, which xdist provides as
worker_id(gw0,gw1). Createtest_gw0once per worker, and run each test in a rolled-back transaction. - File databases: avoid a shared
test.dbfile. Two workers writing to it will hit "database is locked" errors or see each other's rows.
Also look for module-level state, such as a global counter, a cache or a settings object that tests modify, because processes are separate but two tests in the same worker still share them. And remember that parallel runs make hidden order dependence visible, which is a feature.
- "Where does seed data come from?"
From small helper functions in the tests themselves, not from one giant shared file. A helper such as
make_restaurant(db, name="Spice Hub")or the canonical app'sseed()creates only what a test needs, with sensible defaults, and the test overrides the one value it cares about.A huge fixture file that loads fifty rows for every test has three problems. Every test depends on every row, so changing one row breaks unrelated tests. Failures are hard to read, since a count of 7 means nothing until you open the file. And each test pays the cost of loading data it does not use.
I keep the rule that the data a test needs is visible in the test. If the test is about stock running out, the reader should see
stock=5in the test body and not have to find it in a fixture.For realistic volume, such as pagination over 1,000 rows, a loop inside the test with a bulk insert is clearer than a data file, and it takes milliseconds.
- "What about migrations in tests?"
Test them in two different ways, because they answer different questions. The per-test databases are built with
Base.metadata.create_all(), which is fast but never touches Alembic. So nothing in those tests proves that your migration scripts produce the same schema as your models.In CI, once per session, start a throwaway PostgreSQL database and run
alembic upgrade head. That proves the scripts run in order from an empty database. Then run Alembic's autogenerate comparison (alembic checkin recent versions, or compare metadata) and fail if it reports differences, because a difference means someone changed a model without writing a migration.Run
alembic downgrade -1once to check that the last migration is reversible, if you promise rollbacks.A real risk is data migrations: a script that works on an empty table but takes a long lock on ten million rows. Rehearse those against a copy of production-sized data, not in unit tests.
Q118 · Scenario. "Tests pass locally but fail in CI with "Event loop is closed". Diagnose."
Reveal answer
The real test Whether you know that async resources are bound to the loop that created them, and each test may get a different loop.
Strong answer An asyncio resource such as a connection pool, an HTTP client or a lock becomes attached to the event loop that first used it. When that loop closes, the resource still exists but its sockets belong to a dead loop. Using it from a new loop raises RuntimeError: Event loop is closed (or "attached to a different loop").
Test frameworks usually create a new loop per test (pytest-asyncio's default) while your code base holds a module-level client or engine created once. The first test passes. A later test, running on a new loop, reuses the stale object and fails. Locally you run one test file or one order and miss it; CI runs everything, in a different order, sometimes with xdist.
The fixes: create async resources inside fixtures or the app's lifespan (so each test or each app instance gets its own), never at import time; use matching fixture scope and loop scope (a session-scoped async fixture needs a session-scoped loop); and dispose clients and engines at teardown.
Also check for background tasks or threads that outlive a test and touch the closed loop during teardown.
Picture it A module-level httpx.AsyncClient used by two successive asyncio.run calls (a stand-in for two tests with two loops), talking to a real local server.
import asyncio, threading, time, httpx, uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/ping")
async def ping(): return {"pong": 1}
server = uvicorn.Server(uvicorn.Config(app, port=8768, log_level="error"))
threading.Thread(target=server.run, daemon=True).start()
while not server.started: time.sleep(0.05)
client = httpx.AsyncClient(base_url="http://127.0.0.1:8768") # ❌ TRAP: module-level async resource
async def call(): return (await client.get("/ping")).json()
print("first asyncio.run :", asyncio.run(call())) # the pooled connection is now tied to loop #1
try:
print("second asyncio.run:", asyncio.run(call())) # a new test = a new loop; loop #1 is closed
except Exception as e:
print("second asyncio.run:", type(e).__name__ + ":", e)
server.should_exit = TrueMake the invisible visible: Real output.
first asyncio.run : {'pong': 1}
second asyncio.run: RuntimeError: Event loop is closedWhy: The first call opens a keep-alive connection owned by loop number one. When that loop finishes, the connection stays in the client's pool. The second call, on a fresh loop, picks it up and fails with the exact message from CI.
Module-level client
Created once, outlives loops.
# ❌ TRAP: bound to the first loop
client = httpx.AsyncClient()
async def call(): return await client.get(u)Created per app or test
Owned by the loop.
@asynccontextmanager
async def lifespan(app):
app.state.http = httpx.AsyncClient()
yield
await app.state.http.aclose()The shift: Async objects belong to a loop; make their lifetime match the loop's.
Land it Async clients and engines must be created inside a fixture or lifespan so they live and die with the same event loop, never at import time.
- "Why does it only fail in CI?"
Because the two environments run the tests differently. Locally you often run one test or one file, so the stale object is created by the test that first needs it, and used on the same loop. Everything is consistent, so it passes.
In CI the whole suite runs. The first test that touches the shared object creates it on its loop. When that test finishes, pytest-asyncio closes the loop (by default each test has its own). The next test gets a fresh loop but finds the old engine, client or lock at module level, with its connections tied to the closed loop, and fails with
RuntimeError: Event loop is closed.Other differences push the same way. CI may run tests in a different or random order (
pytest-randomly), so the "first" test changes between runs. Parallel workers (-n) split the suite so that some workers see only certain tests. CI machines are also slower, which can expose cleanup races.That is why I reproduce it locally with the same command as CI, in the same order, and with the same plugins, before changing anything.
- "What is the loop scope setting in pytest-asyncio?"
It controls which tests share one event loop. In pytest-asyncio the choices are
function(the default, one loop per test),class,module,packageandsession. Fixtures have a loop scope too.The rule is that an async resource must be used only on the loop that created it. So a fixture with
scope="session"that builds an engine needsloop_scope="session", and the tests that use it must run on that same session loop. Otherwise the engine is created on one loop and each test uses it from another, which is the error from the question.You can set defaults in configuration,
asyncio_default_fixture_loop_scopeandasyncio_default_test_loop_scope, which are options in recent pytest-asyncio versions (check the docs of the one you run, since names have changed between releases). Setting them explicitly also removes a deprecation warning.The simplest rule I follow: per-test loops and per-test resources. A session loop with session resources is faster, but any leaked state spreads to every test.
- "Does a sync
TestClienthave the same problem?" It can, in a different form.
TestClientruns the app in a background thread with its own loop for as long as the client is open. If the client is opened withwith TestClient(app) as client:, lifespan runs on that loop, and everything the app creates stays on it.The trouble starts when something async is created outside the app, for example a module-level
asyncio.Lock()or anAsyncClientused both from the app code and from a test that runs on its own loop. Two loops then touch one object. In Python 3.10 and later, asyncio primitives bind to a loop when first used, and a later use from another loop raises an error such as "attached to a different loop".The cure is the same: create async resources in the app's lifespan and store them on
app.state, so only the app's loop uses them. If a test needs to peek at one, go through the app, with a route or anapp.stateread, instead of awaiting it from the test thread.Sync tests that use
TestClientand never create async objects themselves are the safest case.- "How do I find the culprit quickly?"
Start with a search, because the culprit is usually a module-level object. Search the code and the tests for
AsyncClient(,create_async_engine(,asyncio.Lock(),asyncio.Queue(),asyncio.Event()andaiohttp.ClientSession(outside of functions and fixtures. Agrep -rntakes seconds.Then read the traceback from the bottom. The error line is
Event loop is closed, and the frame just above it is the stale object's method, for exampleconnection.executeorclient.send. The frame above that is your code that used it. Follow that name back to where it was created.If nothing obvious turns up, bisect with the tests: run
pytest -xto stop at the first failure, then run the failing test alone (it should pass), then with the test before it (it should fail). The pair tells you which test left the object behind.Turn on
PYTHONASYNCIODEBUG=1or-X devfor warnings about unclosed resources, and treat "Task was destroyed but it is pending" messages as hints of leaked work.
Q119. "Dependency overrides versus mocking."
Reveal answer
Strong answer app.dependency_overrides[get_mailer] = lambda: fake replaces one dependency for the app instance, by identity. The rest of the real code runs. It is explicit, scoped to one app, and cleared with one call.
unittest.mock.patch replaces an attribute globally by name for the duration of a with block. It works on anything, including code that is not a dependency, but it patches where a name is looked up, which is easy to get wrong (patching module.send when the code imported send directly changes nothing). It also affects every caller in the process.
I prefer overrides for the app's seams (database session, current user, settings, clock, mailer, payment gateway) and hand-written fakes over auto-generated mocks. A fake with simple behaviour (sent.append(to)) tests the outcome, while a mock mostly tests that a method was called with certain arguments, which breaks on every refactor and proves little.
Use patch for things that are not injectable, such as the system clock inside a library or a third-party function, and keep those uses few.
Picture it The same endpoint with no test double, an override and a patch.
from typing import Annotated
from unittest import mock
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
class Mailer:
def send(self, to): raise ConnectionError("real SMTP")
def get_mailer() -> Mailer: return Mailer()
app = FastAPI()
@app.post("/v1/orders")
def create(mailer: Annotated[Mailer, Depends(get_mailer)]):
mailer.send("ravi@example.com"); return {"ok": True}
c = TestClient(app, raise_server_exceptions=False)
print("no test double :", c.post("/v1/orders").status_code)
class FakeMailer:
sent = []
def send(self, to): self.sent.append(to)
fake = FakeMailer()
app.dependency_overrides[get_mailer] = lambda: fake # swaps the dependency, nothing global patched
print("dependency_overrides:", c.post("/v1/orders").status_code, fake.sent)
app.dependency_overrides.clear()
with mock.patch.object(Mailer, "send", return_value=None) as m: # patches the class for everyone, by name
print("mock.patch :", c.post("/v1/orders").status_code, m.call_args)Make the invisible visible: Real output.
no test double : 500
dependency_overrides: 200 ['ravi@example.com']
mock.patch : 200 call('ravi@example.com')What you see: Without a double the real mailer raises, so the endpoint returns 500. With the override the fake collects the address and the test can assert on fake.sent. The patched version works too, but all it can check is the call arguments, and the patch applies to the class everywhere.
mock.patch
Global, by name.
with mock.patch.object(
Mailer, "send") as m:
client.post("/v1/orders")
m.assert_called_once()dependency_overrides
Scoped, by dependency.
app.dependency_overrides[get_mailer] = (
lambda: fake)
client.post("/v1/orders")
assert fake.sent == ["ravi@example.com"]The shift: Replace the seam you designed, not the internals you happened to import.
Land it I override the dependencies that are the app's seams with simple fakes, assert on outcomes, and keep mock.patch for the few things that cannot be injected.
- "Do overrides need cleaning up?"
Yes, and it matters more than people think.
app.dependency_overridesis a plain dictionary on the app object. It stays there for the life of that app. If a fixture setsapp.dependency_overrides[get_mailer] = fakeand never removes it, the next test, using the same app, still gets the fake.A test that expects the real mailer, or a different fake, then fails or passes for the wrong reason, and the failure depends on test order.
There are two clean fixes. Use a fixture with
yieldand clear the dictionary after:yield clientfollowed byapp.dependency_overrides.clear(). Or, better, build a new app for every test from an app factory, as the canonicalconftest.pydoes, so the dictionary starts empty and dies with the test.The second approach also protects against leaks of other kinds, such as middleware state and caches on the app, and makes parallel runs safe. The cost is a few milliseconds per test. I accept that cost, because leaked overrides are hard to find.
- "Can I override a dependency that has sub-dependencies?"
Yes, and the override replaces the whole dependency, including everything it depended on. FastAPI resolves the override function in place of the original, using the override's own parameters. If the original
get_current_userdepended onget_settingsandget_db, an override that takes no parameters needs neither, and they are not called for that dependency.The override can declare its own
Depends. For example, a fakeget_current_usercan depend on the realget_dbto load a user row, while skipping token decoding. That gives you a realistic user object without building tokens.This makes it easy to swap one seam without touching the others. Override
get_current_userto return a fixedUser, andget_settingskeeps working normally. Overrides are matched by the function object, so import the same function the route used; a copy imported from another path will not match.A subtle point: the override replaces by identity, so if routes use a wrapper such as
require_scope("orders:read")that creates a new dependency each call, you must override the inner dependency it uses, not the wrapper.- "When is a mock the right tool?"
A mock is the right tool when the interaction itself is the behaviour you promised. Three cases fit:
- An interaction is the requirement: "the payment gateway is called exactly once with this idempotency key". The outcome is the call, so asserting on it is correct.
- Something you cannot inject: the system clock inside a library, or a function in a third-party package.
mock.patchreaches it where an override cannot. - Failure injection: making a dependency raise
TimeoutErrorto check your 504 path, which a simple fake can also do, but a mock does in one line.
Even then I usually wrap the thing in a small fake class that records calls, such as
FakeGateway.calls. The assertion reads asassert gateway.calls == [("key-1", 19990)], and it keeps working after a refactor changes which method is used. A mock that assertscharge.assert_called_once_with(...)breaks every time the internals change, while the behaviour stays right.- "What is the danger of mocking the database?"
You end up testing your belief about the database instead of the database. A mocked session returns whatever you told it to, so a query with a wrong join, a missing filter or a typo in a column name still passes. The test is green and production is wrong.
Real problems that mocks hide include: a query that returns duplicates because of a join, a unique constraint that rejects the second insert, a transaction that is never committed, an N+1 pattern (51 queries instead of 2), and a type that SQLAlchemy converts differently from what you assumed.
Mocks are also fragile. They encode the exact calls your code makes, such as
session.executethen.scalars().all(). A harmless refactor breaks the test, which teaches people to distrust the suite.So use a real session, SQLite in memory for most tests and PostgreSQL for a marked subset, and override only the connection source (Q120). If you want to be sure about the query count, SQLAlchemy events can count statements per request, and that check is real, not mocked.
Q120. "SQLite in tests versus PostgreSQL in a container — the trade-offs."
Reveal answer
Strong answer SQLite in memory is fast (milliseconds), needs nothing installed, and makes every test easy to isolate. It is a good default for most tests of routing, validation, serialisation and simple queries.
Its weakness is that it is a different database from the one you run. It stores any value in any column unless the table is declared STRICT, ignores VARCHAR lengths, has no SELECT ... FOR UPDATE, serialises writers so races do not show up, and lacks PostgreSQL features such as JSONB, arrays, partial indexes and exact constraint behaviour (deferred constraints, concurrent index builds).
A PostgreSQL container (the same major version as production) is slower to start (seconds, once per session) but tests the real thing: locking, isolation, constraint errors, migrations. The canonical app runs its test suite on both; the same 45 tests pass on postgres:18-alpine, including a race of 8 threads buying 5 items that ends with five 201 responses, three 409 and stock zero.
My policy: most tests on SQLite, plus a smaller set marked for PostgreSQL that cover locking, constraints and migrations, run in CI against a container.
Picture it Three things SQLite quietly allows, and what the same SQLAlchemy construct compiles to on each database.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, total_cents INTEGER NOT NULL, status VARCHAR(5))")
db.execute("INSERT INTO orders (total_cents, status) VALUES ('not a number', 'way-too-long-for-varchar5')")
print("typed columns accept :", db.execute("SELECT total_cents, typeof(total_cents), status FROM orders").fetchall())
db.execute("CREATE TABLE strict_t (n INTEGER) STRICT")
try: db.execute("INSERT INTO strict_t VALUES ('abc')")
except sqlite3.Error as e: print("STRICT table rejects :", e)
print("FOR UPDATE : not supported by SQLite, SQLAlchemy silently omits it on this dialect")
from sqlalchemy import select, column, table
from sqlalchemy.dialects import sqlite, postgresql
q = select(column("stock")).select_from(table("menu_items")).with_for_update()
print("on SQLite :", str(q.compile(dialect=sqlite.dialect())).replace("\n", " "))
print("on Postgres :", str(q.compile(dialect=postgresql.dialect())).replace("\n", " "))Make the invisible visible: Real output.
typed columns accept : [('not a number', 'text', 'way-too-long-for-varchar5')]
STRICT table rejects : cannot store TEXT value in INTEGER column strict_t.n
FOR UPDATE : not supported by SQLite, SQLAlchemy silently omits it on this dialect
on SQLite : SELECT stock FROM menu_items
on Postgres : SELECT stock FROM menu_items FOR UPDATEWhat you see: SQLite stored the text 'not a number' in an integer column, and a string far too long for VARCHAR(5). Only a STRICT table refuses. And with_for_update() compiles to plain SELECT on SQLite but adds FOR UPDATE on PostgreSQL, so a locking bug cannot appear in a SQLite test.
SQLite only
Fast, forgiving, blind to races.
engine = create_engine("sqlite://",
poolclass=StaticPool)
# ❌ no FOR UPDATE, no real constraintsBoth, by marker
Speed plus fidelity.
@pytest.fixture
def engine(request):
if request.node.get_closest_marker("pg"):
return create_engine(PG_URL)
return create_engine("sqlite://", ...)The shift: Use the cheap database for most tests and the real one for the behaviour only it has.
Land it I run most tests on in-memory SQLite for speed and a marked subset on a real PostgreSQL container for locking, constraints and migrations.
- "How do I start PostgreSQL for tests?"
There are three ways, from least to most effort. I pick based on whether I need it every time or only in CI.
- CI service container: in GitHub Actions or GitLab CI, declare
services: postgres: image: postgres:18on the job, with a health check, and pass the URL inQUICKBITE_TEST_PG_URL. This is my default for the PostgreSQL tests. - Local docker run:
docker run --rm -e POSTGRES_PASSWORD=pw -p 5433:5432 postgres:18-alpine, then set the same variable. Quick and visible, and you stop it yourself. - Testcontainers: a library that starts a throwaway container from the test code and removes it afterwards, so a developer needs only Docker. It is not installed on the course machine.
The canonical app reads
QUICKBITE_TEST_PG_URLand skips the PostgreSQL tests when it is not set, so the plain test run works without Docker. In CI the variable is always set, so the skipped tests cannot go unnoticed. Use the same major version as production.- CI service container: in GitHub Actions or GitLab CI, declare
- "Why not use PostgreSQL for everything?"
Because feedback speed decides whether people run the tests. Take 500 tests at 5 ms each: 2.5 seconds, a little more with start-up, so about 3 seconds on in-memory SQLite. Developers run that on every change.
On PostgreSQL, each test usually pays for a connection over the network, a transaction or schema reset, and often a truncate or template copy. Even at 50 ms per test that is 25 seconds, and with heavy setup per test it can reach minutes. Developers start skipping the suite or running it only in CI, and bugs are found later, when they cost more.
Most of what the API tests check, such as validation, routing, serialisation, error shapes, auth, pagination and ETags, behaves the same on both databases, so the extra cost buys little there.
The two-tier approach spends the slow time only where it pays: locking, constraints, isolation and migrations, which SQLite cannot reproduce (it serialises writers, for example). A few dozen slow tests in CI is a better deal than a thousand slow tests everywhere.
- "What about SQLite behaviour differences that cause false failures?"
Yes, and the risk runs in both directions: a test can fail on SQLite while the code is right on PostgreSQL, or pass on SQLite while it is wrong on PostgreSQL. The first kind wastes time, the second hides bugs.
Known differences: SQLite has no real boolean or date type, so values are stored as integers or strings and comparisons can surprise you; it lacks
ILIKE(it hasLIKE, case-insensitive for ASCII by default); it accepts any value in any column unless the table isSTRICT; it ignoresVARCHAR(50)lengths; and it has noFOR UPDATE. Support forRETURNINGandON CONFLICTdepends on the SQLite version.My defence is to keep database-specific SQL in repositories and test those queries on PostgreSQL, so the API tests stay portable. SQLAlchemy constructs such as
select, joins and filters run on both.If a feature only exists on PostgreSQL, such as JSONB or arrays, mark its tests as PostgreSQL-only and let them skip when no URL is set, instead of faking it on SQLite.
- "How do I test migrations?"
Make the migration check part of CI, not of unit tests, and make it do four things. First, start an empty PostgreSQL database. Second, run
alembic upgrade head, which proves every script applies in order. Third, compare the resulting schema with the models: autogenerate (oralembic check) should report no differences, and a difference means a model changed without a migration. Fourth, runalembic downgrade -1once, if you promise that rollbacks work, then upgrade again.A fifth check that pays off is upgrading from the previous release's schema with some data in it, since migrations that work on empty tables can fail on real rows, for example a new
NOT NULLcolumn without a default.Keep large data changes out of migration scripts, or run them in batches, because a single statement that locks a ten-million-row table can stop production.
The unit tests keep using
create_all()for speed. The two checks are different, and I want both: one proves the models work, the other proves the upgrade path works.
Q121. "Contract testing an API against its OpenAPI schema."
Reveal answer
Strong answer A contract test checks that what the server really returns matches what the OpenAPI document promises. FastAPI generates the document from your code, so the two start in sync; they drift when a route returns a dict with different keys, when a response has no response_model, or when someone edits a serialiser.
There are three levels. The cheapest: in a normal test, take a response and validate it with jsonschema against the schema from app.openapi(). The next: property-based testing with a tool like Schemathesis, which reads the schema and generates hundreds of valid and invalid requests, checking that no response is a 500 and every response matches its declared schema.
Schemathesis is not installed on the course machine; I describe it rather than run it. The third: consumer-driven contracts (Pact), where each client publishes what it relies on and the provider's build verifies it.
Contract tests also catch breaking changes. Export openapi.json in CI, diff it against the last release, and fail on removed fields, changed types or newly required request fields (Q34).
Picture it One route that declares response_model and one that does not, checked against the schema of the first.
import jsonschema
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class OrderOut(BaseModel):
id: int
status: str
total_cents: int
app = FastAPI()
@app.get("/v1/orders/{oid}", response_model=OrderOut)
def get(oid: int): return {"id": oid, "status": "placed", "total_cents": 1200}
@app.get("/v1/orders-bad/{oid}") # no response_model: nothing enforces the contract
def get_bad(oid: int): return {"id": oid, "status": "placed", "total": 12.0}
spec = app.openapi()
def schema_for(path):
ref = spec["paths"][path]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
if "$ref" in ref: ref = spec["components"]["schemas"][ref["$ref"].split("/")[-1]]
return ref
c = TestClient(app)
schema = schema_for("/v1/orders/{oid}")
jsonschema.validate(c.get("/v1/orders/1").json(), schema); print("good endpoint : response matches OrderOut schema")
body = c.get("/v1/orders-bad/1").json()
try:
jsonschema.validate(body, schema)
except jsonschema.ValidationError as e: print("drifted body :", e.message)
print("schema props :", sorted(schema["properties"]), "| required:", schema["required"])Make the invisible visible: Real output.
good endpoint : response matches OrderOut schema
drifted body : 'total_cents' is a required property
schema props : ['id', 'status', 'total_cents'] | required: ['id', 'status', 'total_cents']What you see: The declared route passes. The second route returns total instead of total_cents, and the check names the missing required property. Without a response_model, FastAPI had no way to stop that drift at runtime, which is why I put response_model on every route.
Spec written by hand
Drifts the day after.
paths:
/v1/orders/{id}:
get: {responses: {"200": {...}}}
# ❌ nobody checks it against the codeGenerated + verified
Code is the source.
python dump_openapi.py > new.json
oasdiff breaking old.json new.json
schemathesis run new.json --checks allThe shift: Treat the schema as an artefact the build verifies, not as documentation.
Land it I generate the schema from code, check real responses against it, diff it for breaking changes in CI, and fuzz it with Schemathesis where available.
- "What does Schemathesis find that example-based tests miss?"
The ones nobody thought of, and those are exactly the ones that cause incidents. Example-based tests cover the cases a developer imagined. Schemathesis reads the OpenAPI schema and generates inputs from it, then mutates them: huge integers, negative numbers, empty strings, very long strings, unusual unicode, missing optional fields, nulls where a string is declared, and values at and just beyond each declared limit.
It checks two things on every response. The server must not return a 500, and the response must match the declared schema, including status code, content type and body. Typical first-run finds: a route that returns 500 for a page size of 0, a 200 whose body has an extra or missing field, an undocumented 404, and a date parser that crashes on a leap day.
It also finds drift between the document and the code, which hand-written tests rarely check.
Schemathesis is not installed on the course machine, so I describe it. In practice I run it in CI against a test instance with a fixed seed, so a failure can be reproduced, and I fix real findings while explicitly excluding noisy ones with a reason.
- "How do I diff schemas for breaking changes?"
Use a tool that understands the OpenAPI format, for example
oasdiff. In CI, exportopenapi.jsonfrom the pull request (app.openapi()writes it) and from the main branch, or from the last release, and compare the two files.The tool classifies each change. Breaking ones include removing an endpoint or a field, changing a field's type, narrowing an enum (removing a value clients may send), making an optional request field required, and tightening a limit such as
maxLength. Safe ones include adding an endpoint, adding an optional request field, or adding a response field.Wire it so a breaking result fails the build, with a way to approve it: a label on the pull request that a human, such as the API owner, must add, together with a new
/v2path or a deprecation period.Remember that adding a value to a response enum can also break clients that switch on it, so I tell clients in the docs to ignore values they do not know. The tool cannot judge that, a person can.
- "Where does
response_modelfit?" It is the part of the contract that runs inside the server. FastAPI uses the
response_modelto validate what the route returns and to drop every field not in the model. If a developer returns an ORM object with apassword_hashattribute, the field is not sent. If the route forgets a required field, Pydantic raises an error before a byte goes out.That turns drift into an immediate failure instead of a quiet one. Without it, a route that returns a plain dict can send anything, and the OpenAPI document would say one thing while the wire says another. With it, the first test that calls the route fails if the data does not fit.
It also feeds the other half: the response schema in
openapi.jsonis generated from the same model, so documentation and runtime check are one object.Mistakes I look for: routes declared with
-> dictor no model,response_model=Nonewithout a reason, and models withextra="allow"on output. A contract test can fail the build if any route lacks a response model.- "Is consumer-driven contract testing overkill?"
For one frontend, written and released by the same team, yes, it is more than you need. A schema diff in CI and a couple of end-to-end checks give most of the safety, and the team talks to itself.
Consumer-driven contracts (Pact is the common tool) earn their cost when there are many consumers you do not control. A mobile app with slow release cycles has old versions in the field for months. Partners integrate against your API and read your changelog late. In both cases you cannot tell which fields are still used, so removing a field is a gamble.
In the Pact model each consumer writes down the requests it makes and the response parts it depends on, publishes that to a broker, and your build verifies the provider against every published contract before release. A failing verification names the consumer that would break.
The costs are real: tooling, a broker, and discipline from every consumer team to keep contracts current. I adopt it when a breaking change has already hurt twice, not before.
Q122. "How do you test endpoints protected by authentication?"
Reveal answer
Strong answer Test at two levels. Most tests do not care about auth and should not pay for it: they use a token factory fixture that signs a valid token with a test key and sends it in the header, or they override get_current_user to return a fixed User. This keeps order, stock and pagination tests short.
A small, dedicated security test file exercises the real validation end to end: missing token (401 plus WWW-Authenticate), garbage, expired, wrong audience and issuer, wrong signing key, alg: none, the HS256-with-public-key forgery, missing required claims, missing scope (403) and someone else's order (404). These are the tests that protect you the day someone changes the decode call.
The factory takes keyword arguments for each claim (sub, scope, exp_in, aud, iss, key), so each security test changes exactly one thing. The test key pair is generated once per session; the app's settings receive the matching public key, so production code is exercised unchanged.
Picture it The security tests of the canonical app, listed by running them. Each name states one behaviour.
The setup: pytest tests/test_security.py -v in code/e20-python-api/quickbite_api.
tests/test_security.py::test_missing_token_is_401_with_challenge PASSED
tests/test_security.py::test_valid_token_is_accepted PASSED
tests/test_security.py::test_garbage_token_is_401 PASSED
tests/test_security.py::test_expired_token_is_401 PASSED
tests/test_security.py::test_wrong_audience_and_issuer_are_401 PASSED
tests/test_security.py::test_token_signed_with_another_key_is_401 PASSED
tests/test_security.py::test_forged_token_without_signature_check_is_rejected PASSED
tests/test_security.py::test_alg_none_is_rejected PASSED
tests/test_security.py::test_algorithm_confusion_hs256_signed_with_public_key_is_rejected PASSED
tests/test_security.py::test_missing_required_claims_are_rejected PASSED
tests/test_security.py::test_hs256_mode_for_local_demos PASSED
tests/test_security.py::test_jwks_mode_uses_the_key_the_client_returns PASSED
tests/test_security.py::test_scope_is_enforced_with_403 PASSED
tests/test_security.py::test_idor_other_customers_order_is_404 PASSED
tests/test_security.py::test_admin_can_read_any_order PASSED
tests/test_security.py::test_cors_preflight PASSED
======================== 16 passed, 1 warning in 1.13s =========================Why: The list reads as a checklist of Q82 and Q83: forged, expired, wrong audience and wrong key tokens are all rejected, and ownership and scope behave as designed. Sixteen tests run in about a second.
Test with a global bypass
Production code never runs.
# ❌ TRAP: auth switched off in tests
if settings.env == "test":
return User(id=1, role="admin")Real validation, test key
Same code path as production.
token = make_token(sub=7, scope="orders:read")
r = client.get("/v1/orders",
headers={"Authorization": f"Bearer {token}"})
assert r.status_code == 200The shift: Keep the production check running in tests and swap only the key.
Land it Most tests use a token factory signed with a test key, and a dedicated security file sends forged, expired and wrong-audience tokens through the real validation.
- "Why not disable auth when
ENV=test?" Because a branch that exists only in tests is code production never runs, and a flag that disables security can end up switched on in production. Both are real failure modes.
With
if settings.env == "test": return fake_userin the auth code, you are no longer testing your authentication. Tests pass through a path that production does not use. Worse, one wrong environment variable in a deployment, such as a copied.envfile, removes authentication for the whole API, and nothing in the code review looked suspicious, since the line was "just for tests".A dependency override keeps the production code clean. The test fixture sets
app.dependency_overrides[get_current_user] = lambda: User(...). The code in the repository contains no test logic and no way to turn auth off, and the override exists only in the test process.I do the same for the clock and the database. For the few real security tests I do not override anything: they send real tokens signed with the test key, through the real validation, so that path is exercised too.
- "How do I test with JWKS?"
Replace the network call with a fake key source, because the validation code does not care how a key arrives. In production,
PyJWKClientfetches the JSON Web Key Set (the list of public keys the identity provider publishes) from a URL and caches it. The decoder callsget_signing_key_from_jwt(token)to pick the key matching the token'skidheader.In tests, pass an object with the same method that returns your test public key. The canonical suite has a test for exactly this. Nothing touches the network, so it is fast and runs offline.
Use it to test the cases that matter. A token whose
kidmatches the test key passes. A token signed by a different private key, with the samekid, fails with 401. Key rotation is simulated by making the fake return a new key for a newkidand still serve the old one for a while, and the app must accept tokens from both.Also test the failure of the key source itself: when the fake raises an error, the API should answer 401 or 503 predictably and must not crash or let the token through.
- "How do I test expiry without sleeping?"
Never with
time.sleep, which makes the suite slow and still races. Build the expired token directly. The factory takesexp_in, the seconds from now until expiry, somake_token(exp_in=-60)creates a token that expired a minute ago, and the test asserts 401 with aWWW-Authenticateheader.Test the edges as well. A token that expires in 30 seconds should still work, and the app's leeway setting decides what happens at the boundary. If your decoder allows a small clock skew, such as 10 seconds, test one value inside and one outside it, so a change to the leeway fails a test.
For code that reads the clock itself, for example a rule like "refunds only within 15 minutes of the order", inject a clock (Q123) and move it forward in the test, instead of waiting.
The same idea covers "not before" (
nbf) and "issued at" (iat) claims: make them with values in the future, and check they are refused. Everything stays fast and repeatable.- "What about testing roles for restaurant staff?"
Roles are rules, so I test them as a small table of cases, one assertion each. The factory takes
sub,restaurant_idandscopeas arguments.- The capability: a staff token with
restaurant:orders:updatecan PATCH an order status; one with onlyrestaurant:orders:readgets 403. Missing scope means 403. - The ownership: a staff member of restaurant 5 reads restaurant 5's order, and gets 404 for restaurant 9's order, not 403, so ids cannot be probed.
- The combination: both together: the right scope on the wrong restaurant is 404, the wrong scope on the right restaurant is 403.
I write them with
pytest.mark.parametrize, one row per rule, with ids such asread-only-cannot-patch, so a failing row names the broken rule. Each test changes exactly one claim from a known-good token, so the failure points at that claim. A matrix of eight to twelve rows covers a typical role model and runs in milliseconds.- The capability: a staff token with
Q123 · Scenario. "A test fails only around midnight. Fix it."
Reveal answer
The real test Whether you make "now" an injected dependency instead of calling the clock inside business code.
Strong answer A test that fails only near midnight reads the real clock twice, or builds an expectation from the clock that is at a different date than the code under test saw. For example, the test creates an order (it gets today's date), then calls "orders for today". If midnight passes between the two, they disagree. Or the code uses UTC dates and the test uses local dates, which only differ for a few hours a day (Q112).
The fix is not to retry. Make the clock an input. Business code receives a Clock (a small object with now()) through a dependency or constructor argument. Production wires the real UTC clock. Tests pass a frozen or controllable one, and then run the boundary cases on purpose: 23:59:59 and 00:00:01 in the relevant zone.
A freezing library (freezegun, time-machine) can patch the clock globally and is acceptable for legacy code, but an injected clock is more explicit, works with threads and async code, and documents which functions depend on time.
Picture it The same query with a naive "today" and with an injected clock, run at two frozen instants on either side of midnight in India.
from datetime import date, datetime, timedelta, timezone
from zoneinfo import ZoneInfo
class Clock:
def now(self): return datetime.now(timezone.utc)
class FixedClock(Clock):
def __init__(self, at): self.at = at
def now(self): return self.at
def todays_orders_naive(orders, clock): # ❌ TRAP: "today" is the server's (UTC) calendar day
return [o for o in orders if o.astimezone(timezone.utc).date() == clock.now().astimezone(timezone.utc).date()]
def todays_orders(orders, clock: Clock, tz=ZoneInfo("Asia/Kolkata")):
start = clock.now().astimezone(tz).replace(hour=0, minute=0, second=0, microsecond=0)
return [o for o in orders if start <= o < start + timedelta(days=1)]
IST = ZoneInfo("Asia/Kolkata")
orders = [datetime(2026, 11, 24, 23, 59, 58, tzinfo=IST), datetime(2026, 11, 25, 0, 0, 2, tzinfo=IST)]
for label, at in [("23:59:59 IST", datetime(2026, 11, 24, 23, 59, 59, tzinfo=IST)), ("00:00:01 IST", datetime(2026, 11, 25, 0, 0, 1, tzinfo=IST))]:
for fn in (todays_orders_naive, todays_orders):
got = fn(orders, FixedClock(at))
print(f"{fn.__name__:20} clock {label}: {[o.strftime('%d %b %H:%M:%S') for o in got]}")Make the invisible visible: Real output.
todays_orders_naive clock 23:59:59 IST: ['24 Nov 23:59:58', '25 Nov 00:00:02']
todays_orders clock 23:59:59 IST: ['24 Nov 23:59:58']
todays_orders_naive clock 00:00:01 IST: ['24 Nov 23:59:58', '25 Nov 00:00:02']
todays_orders clock 00:00:01 IST: ['25 Nov 00:00:02']What you see: The naive function, which compares UTC dates, returns both orders at both instants: it ignores the customer's day. The injected-clock version returns only the order from the 24th at 23:59:59 and only the order from the 25th at 00:00:01. Both boundaries are now tests, not accidents.
Reads the clock inside
Result depends on when you run.
def todays(orders):
# ❌ TRAP: hidden global input
today = date.today()
return [o for o in orders
if o.date() == today]Clock is a parameter
Test chooses the instant.
def todays(orders, clock, tz):
start = clock.now().astimezone(tz)
start = start.replace(hour=0, minute=0,
second=0)
...The shift: Time is an input like any other, so pass it in.
Land it I inject a clock so tests choose the instant, and I test both sides of every day, month and daylight-saving boundary deliberately.
- "Where does the clock dependency live in FastAPI?"
As a small dependency that returns an object with a
now()method. Something likedef get_clock() -> Clock: return SystemClock(), whereSystemClock.now()returnsdatetime.now(timezone.utc). Routes and services receive it withDepends(get_clock), or services get it as a constructor argument from the route.In tests there are two ways. Override it with
app.dependency_overrides[get_clock] = lambda: FixedClock(datetime(2026, 11, 24, 23, 59, 59, tzinfo=timezone.utc)), or build aFakeClockwithadvance(seconds)and pass it to the app factory, so a test can move time forward.For code that runs outside a request, such as a background worker, a scheduled job or a command-line script, there is no dependency system, so pass the clock as a constructor argument. That is the reason to keep the clock a plain object and not a FastAPI feature.
A habit that helps: ban
datetime.now()anddatetime.utcnow()in business code with a lint rule, so the only way to get the time is through the clock. Then every test that depends on time has to say so.- "What other time-dependent bugs do tests miss?"
Anything where the calendar is not regular, and each is a bug waiting for the right date. A few I put in a checklist:
Daylight-saving days have 23 or 25 hours, so "add 24 hours" and "add one day" differ, and "midnight" may not exist in some zones. The 29th of February breaks code that does
replace(year=year+1). Month ends break "same day next month", since 31 January plus one month has no 31 February. Weeks differ by locale, and ISO week 1 can start in the previous year.Time zones with odd offsets break code that assumes whole hours: India is +05:30 and Nepal +05:45. Leap seconds rarely matter for business code, but they matter for logs that mix machines. Two events in the same second break sorting by timestamp, so tie-break by id.
I write one parametrised test per piece of date logic I own, with the awkward dates in the table, and use
zoneinfozones in the tests so the rules come from the real timezone database.- "Should the database also use the injected clock?"
For values your code decides, yes. If the service sets
created_at = clock.now()and writes it, a test can freeze the clock and assert the exact value. If instead the column hasserver_default=func.now(), the database fills it with its own clock, which a test cannot control, and assertions have to be fuzzy, such as "within five seconds of now", which is slow, flaky near boundaries and weak.That is the same trap as the midnight bug. If the code asks for "today's orders" using the injected clock while the rows were stamped by the database clock, the two can disagree on the date near midnight, and you are back where you started.
A reasonable rule is: the application owns business timestamps, from one clock, and the database default is only a safety net for rows inserted by hand.
There are exceptions. Audit columns managed by triggers, or ordering that must reflect the commit time in the database, are better left to the database. In those cases, do not assert on exact values in tests; assert on relationships, such as
updated_at >= created_at.- "Is freezegun ever the right tool?"
Yes, for code you cannot change. A legacy module that calls
datetime.now()in forty places, or a third-party library that reads the time itself, is hard to wrap, and a freezer patches the clock globally so the tests can still control it.time-machineis faster and more thorough thanfreezegun, and both are well known.There are limits. Some libraries cache the time at import, or use
time.monotonic(), which freezers usually do not move, so a timeout or a rate-limit window may behave oddly. In async code, the event loop has its own notion of time forasyncio.sleep, so a frozen wall clock can leave sleeps real. And threads started before freezing may see real time.A frozen clock is also global, so it can hide a bug where two parts of the code should have used the same instant but each read its own.
For new code I prefer an explicit parameter, because it documents which functions depend on time, works the same in threads and async code, and needs no magic. Freezers are my tool for wrapping old code until it can be refactored.
Q124. "Load-testing a FastAPI service and reading the results."
Reveal answer
Strong answer A load test answers "how much traffic can it take before it becomes slow or fails, and what breaks first?". The tools are Locust (Python scripts), k6 (JavaScript scripts) and wrk or hey (quick hammering). None of them is installed on the course machine, so the demo uses a small asyncio load generator against the in-memory app; for real tests use a dedicated tool running on a separate machine, since the load generator competes for CPU with the system under test.
Read results in percentiles, not averages. The median (p50) shows typical speed, p95 and p99 show the slow tail that users complain about, and the average hides it. Also watch throughput (requests per second), the error rate, and server-side numbers at the same time: CPU, memory, event loop lag, database connections in use, and queue lengths.
Test the right shape. Ramp up slowly, hold steady for several minutes, then spike. Use realistic data and a realistic mix of routes. A load test that hits one cached URL measures the cache.
Look for the knee: the point where throughput stops growing and latency starts climbing. Beyond it you are only adding queueing delay.
Picture it A 10 ms endpoint at 1, 10, 50 and 200 concurrent users, every user sending 20 requests back to back.
import asyncio, statistics, time, httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/fast")
async def fast(): await asyncio.sleep(0.01); return {"ok": 1}
async def user(c, n, lat):
for _ in range(n):
t = time.perf_counter(); await c.get("/fast"); lat.append((time.perf_counter() - t) * 1000)
async def run(users, n=20):
lat = []
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
t0 = time.perf_counter(); await asyncio.gather(*(user(c, n, lat) for _ in range(users))); wall = time.perf_counter() - t0
q = statistics.quantiles(lat, n=100)
print(f"{users:4} users: {len(lat)/wall:7.0f} req/s | p50 {q[49]:6.1f} ms | p95 {q[94]:6.1f} ms | p99 {q[98]:6.1f} ms")
for u in (1, 10, 50, 200): asyncio.run(run(u))Make the invisible visible: Real output (course machine, 12 cores; your numbers will differ).
1 users: 90 req/s | p50 11.1 ms | p95 11.4 ms | p99 11.5 ms
10 users: 845 req/s | p50 11.5 ms | p95 12.7 ms | p99 13.4 ms
50 users: 3873 req/s | p50 11.1 ms | p95 13.7 ms | p99 31.4 ms
200 users: 3843 req/s | p50 49.3 ms | p95 69.9 ms | p99 74.7 msWhat you see: Throughput grows from 90 to about 3,900 requests per second as users go from 1 to 50, with p50 flat at 11 ms. Between 50 and 200 users throughput does not rise (3,873 to 3,843) but p50 jumps from 11 to 49 ms: that is the knee, where extra users only wait in line. Note that the load generator and the app share one Python process here, so this shows the method, not the app's true capacity.
Average only
Hides the tail.
# ❌ TRAP
requests: 20000 avg latency: 48 ms
(1 in 100 users waited 3 s)Percentiles + errors
Shows what users feel.
p50 49 ms p95 70 ms p99 3,000 ms
errors 0.4 % rps 3,843
loop lag p99 41 ms db pool in use 10/10The shift: Measure the experience of the unlucky one in a hundred.
Land it I load-test from a separate machine with realistic traffic, read p50, p95 and p99 with error rate and server-side saturation, and find the knee before setting capacity and alerts.
- "What is "coordinated omission"?"
It is a measurement mistake that makes latency look better than it is. Imagine a load generator that sends one request, waits for the reply, then sends the next. If the server stalls for 10 seconds, the generator sends nothing during those 10 seconds, so it records one very slow request instead of the hundreds that real users would have sent and made wait. The slow period is under-counted, and p99 looks fine.
Real users do not wait politely. They arrive on their own schedule, and during a stall requests pile up in a queue, each waiting its turn. The wait before the request is even sent is part of what they feel.
The fix is a generator with a fixed arrival rate: it sends at scheduled times whether or not earlier replies came back, and measures latency from the scheduled time. k6's
constant-arrival-rateexecutor does this, and so does wrk2 (Gil Tene named the problem).When a tool offers both modes, use arrival rate for capacity tests, because production traffic is an arrival rate too.
- "What do I watch on the server during the test?"
Watch the server at the same time as the client, because the first resource to saturate is the bottleneck, and the client alone cannot tell you which one.
- CPU per worker: one uvicorn worker at 100 percent while others idle means the event loop or Python code is the limit; add workers or fix hot code.
- Event loop lag: how late scheduled callbacks run; a rising lag means something is blocking the loop (Q4).
- Database: pool in use and time waiting for a connection, slow queries, and locks. A pool of 10 with 200 concurrent requests shows up as waiting.
- Latency and errors: p99 by route, because one slow endpoint can hide in an average, and the 5xx and timeout rate.
- Memory: growth over the whole test, which shows leaks.
I put these on one dashboard next to the load profile, so I can read "at 600 requests per second the pool wait began to rise" from a single screen.
- "Where do I run the test?"
Run it against a staging environment that resembles production, and drive it from a different machine. Not from a laptop, not from production, and not from the same host as the app.
Resemblance means three things. The size: the same instance type, worker count and database tier, or at least a known fraction. The data: a copy of production-sized, anonymised data. An empty database makes every query look fast, and a query that scans ten rows in staging may scan ten million in production. The configuration: the same proxy, TLS, gateway, connection limits and middleware, since those layers add latency and limits of their own.
The load generator must be separate because it competes for CPU with the system under test. At a few thousand requests a second, the generator itself needs cores, and shared cores would blur your numbers.
Testing in production is occasionally right, for example a controlled ramp with a safe read-only route and an agreed window, but it needs a kill switch and everyone informed. For everything else, staging.
- "How do I turn a result into capacity?"
Find the knee, take the throughput there, and add margin. The steps are short and the arithmetic is worth writing down. Suppose the test shows throughput climbing to 600 requests per second on 4 pods, where p99 is still 200 ms, and past 600 the p99 jumps while throughput stays flat.
capacity arithmeticruns offlineknee = 600 req/s on 4 pods -> 150 req/s per pod headroom 40% = 150 x 0.6 = 90 req/s per pod (safe working load) expected peak = 1,800 req/s -> 1,800 / 90 = 20 pods autoscaler goal = scale up when a pod passes about 75 req/sThe assumptions are stated: the knee was measured on staging with production-like data, and the headroom of 30 to 50 percent covers spikes, one pod being down, and deploys that take pods out for a while. The autoscaler target sits below the knee so new pods are ready before the old ones saturate.
Then repeat the test after big changes: a new query, a new dependency or a library upgrade can move the knee overnight. I schedule a short load run each release and compare.
Q125 · Design. "Design the test pyramid for the QuickBite API."
Reveal answer
Strong answer A test pyramid puts many fast, narrow tests at the bottom and few slow, broad ones at the top. For a FastAPI service the layers look like this, with real counts from the canonical suite where they exist.
| Layer | What it covers | Speed | Count in the canonical suite |
|---|---|---|---|
| Unit | pure functions: money rounding, cursor encode and decode, state-transition table, token checks | microseconds | few; most logic is reached through the API layer |
| API tests (TestClient + SQLite) | routes, validation, errors, auth, idempotency, pagination, ETag | milliseconds each | 45 in four files: security 16, orders 15, errors and pagination 9, observability 4 |
| Real-database tests (PostgreSQL container) | locking, constraints, migrations, the 8-thread stock race | seconds | 1 test file, run when a PostgreSQL URL is set; 8 threads buying 5 items give 5 x 201, 3 x 409 and stock 0 |
| Contract and fuzz | response schema match, OpenAPI diff, Schemathesis | seconds to minutes | in CI |
| Smoke and load | the built container answers /healthz; a short load run | minutes | on deploy and nightly |
The suite is wider in the middle than a classic pyramid because the API layer is the public contract, and each API test runs the whole stack down to a real SQL database in milliseconds.
Picture it The real totals from the canonical app.
9 tests/test_errors_pagination.py
4 tests/test_observability.py
15 tests/test_orders.py
1 tests/test_postgres.py
16 tests/test_security.pyReason:
('/home/iam100god/Desktop/AI_COURSE/code/e20-python-api/quickbite_api/tests/test
_postgres.py', 24, 'Skipped: set QUICKBITE_TEST_PG_URL to run')
44 passed, 1 skipped, 1 warning in 3.73sWhy: 45 tests are collected: 44 pass on SQLite in under four seconds and the PostgreSQL one is skipped here, because no QUICKBITE_TEST_PG_URL is set. With a PostgreSQL 18 container the same suite reports 45 passed.
Spring Boot
Slices of the context.
// illustrative
unit plain JUnit, no Spring
@WebMvcTest controller + MockMvc
@DataJpaTest repository + H2/Testcontainers
@SpringBootTest whole app, slowFastAPI
One cheap whole-stack layer.
unit plain pytest functions
API TestClient + SQLite + overrides
real DB marked tests + PostgreSQL
smoke container + curlThe shift: In FastAPI the fast layer already includes the whole stack, so you need fewer mocked slices.
Land it Many fast API tests over SQLite carry most of the load, a few marked tests prove PostgreSQL-only behaviour, and contract, smoke and load tests guard the edges.
- "What would you not test?"
Three groups, and the first is the largest. I do not test framework behaviour: that FastAPI returns 422 for a string where an integer is declared is FastAPI's job and has its own tests. I do not test trivial code such as getters and plain data classes, or anything a type checker or linter already proves, such as a wrong argument count.
I also avoid duplicating coverage. If an API test already shows that the unique-constraint error becomes a 409, a second test of the same path at the service level adds cost and no confidence.
And I do not test private details. A test that asserts which internal function was called breaks on every refactor, while the behaviour has not changed.
The rule is that every test must defend something: a business rule, a past bug, a security promise or a contract. Each one has a maintenance cost, since someone must read, update and wait for it. If a test cannot say what would break in production without it, I delete it. A small suite that people trust and run is worth more than a large one they skip.
- "How do you keep the suite fast?"
Speed comes from avoiding waiting and from sharing the expensive parts. The practical list:
Create the app and the schema once, or cheaply per test with in-memory SQLite. Never call
time.sleep; inject a clock and move it. Use fakes for the network, mailer and payments, so no test touches a real service. Run in parallel withpytest-xdist, which works easily when each test has its own database. Keep the PostgreSQL tests few, marked, and run in CI. Check slow tests withpytest --durations=10and fix the worst first, because a few slow fixtures usually cost more than hundreds of tests.The target I use: the unit and API tests finish in a few seconds. The canonical suite's 44 passing tests and one skipped run in a few seconds, which is why people run it before every commit. A 4 minute suite gets run once a day, and bugs wait for it.
Speed is a design constraint, and I protect it in review: a new test that adds seconds needs a reason.
- "Where do property tests fit?"
On pure logic with many possible inputs, where one example proves little. A property test says "for any value in this range, this statement holds", and the library,
hypothesishere, generates hundreds of values, including awkward ones, and shrinks a failure to the smallest example.Good fits in this app: cursor encode and decode (for any id and timestamp,
decode(encode(x)) == x), money rounding (the tax of a sum is within one cent of the sum of taxes, and never negative), the status transition table (no sequence of allowed moves leaves the valid states), and parsers of query parameters (any string either parses or is refused with 422, never a 500).hypothesisis installed on the course machine. It finds edge cases such as empty strings, zero, negative numbers and huge values that hand-picked examples miss, and it saves the failing case in a local database so it replays next run.Poor fits are things that need a database or network for each example, because hundreds of runs become slow. Keep property tests at the unit layer, where each example costs microseconds.
- "How do you test concurrency?"
With real threads against a real database, because concurrency bugs live in the gap between a read and a write. The PostgreSQL stock race in the canonical suite is the model: eight threads each try to buy at the same time, and there are only five items. The correct outcome is five 201 responses, three 409 and stock at 0.
That test can only pass if the code locks properly, for example with
SELECT ... FOR UPDATEor an atomicUPDATE ... WHERE stock >= :n. If the code reads the stock, checks it and then writes, two threads can both see 1 left, and both succeed. A barrier at the start makes the threads begin together, so the race happens on every run, not by luck.SQLite serialises writers, so the same test on SQLite would pass even for broken code (Q120), and tells you nothing.
I assert on the invariants, not on which thread wins: total successes equal stock, stock never goes below zero. And I run it a few times, since a race that passes once may still fail on another run. It is one test file, marked for PostgreSQL, because it takes seconds.
These questions test whether work survives a deploy, whether you can follow one request through logs and traces, and whether your health checks tell Kubernetes the truth.
Q126. "BackgroundTasks, Celery, arq or Dramatiq — how do you decide?"
Reveal answer
Strong answer The deciding question is: what happens if this work is lost?
BackgroundTasks runs a function in the web process after the response. There is no queue, no retry, no persistence and no visibility. If the process stops (deploy, crash, out-of-memory kill) the work is gone. It suits cheap, best-effort jobs: warming a cache, writing an analytics event.
A real queue stores the job outside the web process, so a worker can pick it up later, retry on failure, apply backoff, run it on a schedule, and report progress. The Python options differ in weight and style. Celery is the most feature-rich and widespread, and the heaviest to configure.
arq is small and asyncio-native on Redis. Dramatiq is simple and reliable with good defaults on Redis or RabbitMQ. RQ is the simplest Redis queue. For event-style work, Kafka through an outbox suits cases where several services react to the same event.
Whatever the tool, jobs must be idempotent, because every queue delivers at least once. And create the job in the same database transaction as the business change (an outbox), so "order saved" and "email queued" cannot disagree.
Picture it The options side by side, with the point at which each stops being enough.
| Option | Pick it when | Cost or catch |
|---|---|---|
| BackgroundTasks | work is cheap and losing it is acceptable | lost on deploy or crash, no retry, shares the web process CPU and threads |
| arq | asyncio code base, Redis already present, simple retries | smaller ecosystem, fewer features, Redis only |
| Dramatiq | you want reliable defaults with little configuration | fewer integrations than Celery |
| Celery | complex workflows, schedules, many teams, mature monitoring | heavy configuration, sync-first, many ways to misconfigure |
| RQ | tiny needs, a few jobs, Redis | no async support, basic feature set |
| Kafka consumer via outbox | many consumers of the same event, replay needed | operational weight, eventual consistency, ordering design |
Switch from BackgroundTasks to a queue the day someone says "we must not lose this".
BackgroundTasks
In the web process.
@router.post("/orders")
def create(bg: BackgroundTasks):
...
bg.add_task(send_email, order.id)
# lost if the pod stops nowQueue
A worker process, a stored job.
# illustrative: dramatiq
@dramatiq.actor(max_retries=5)
def send_email(order_id): ...
# in the same transaction as the order:
outbox.add(kind="send_email", order=order.id)The shift: Move the job out of the process that might die, and write it down before you promise it.
Land it BackgroundTasks only for best-effort work; anything I must not lose goes through a durable queue or outbox with idempotent workers.
- "Why not just use Celery for everything?"
-
Celery is a strong default for complex needs, but it is not free. You run a broker (Redis or RabbitMQ), often a result backend, and a fleet of worker processes. You also choose a serialiser, tune prefetch and acknowledgement settings, and learn its configuration surface.
That cost pays off when you need scheduling, task chains, rate limits per task type, or many teams sharing one system. It is wasted when the whole requirement is two or three simple jobs, such as sending a confirmation email and resizing an image.
For small needs there are lighter paths. An outbox table in the database plus one worker loop that polls unsent rows is easy to read and gives you durability and retries with no new infrastructure. arq or Dramatiq give a real queue with far less configuration.
My rule is to start with the lightest tool that meets the loss and retry requirements, and move to Celery when the needs, not the fashion, grow into its features.
- "Async or sync workers?"
-
Match the worker style to what the job spends its time doing. The question is where each job waits.
If a job mostly waits on other systems, such as an HTTP call to an email provider or a database write, an async worker such as arq is a good fit. One process runs many jobs at once on an event loop, because while one job waits the loop runs another. Ten jobs that each wait 200 ms cost about 200 ms in total, not two seconds.
If a job burns CPU, such as rendering a PDF or resizing images, async gives nothing. The loop would be held by one job. Use process-based workers: Celery with the prefork pool, or Dramatiq with several processes, so each job gets its own core and its own interpreter lock.
Many teams run two worker pools with two queues: an async pool for I/O jobs and a process pool for heavy jobs. That also stops a slow PDF job from delaying a quick email.
- "How do I observe queue health?"
-
I watch six numbers, and I alert on one of them first.
- Queue depth: how many jobs are waiting. Graph it, but do not page on it alone.
- Age of the oldest job: how long the longest-waiting job has waited. This is the number users feel, so this is the alert.
- Job duration: a histogram per job type, so a slow dependency shows up as a shifted curve.
- Failures and retries: counts per job type; a rising retry rate warns you before the queue backs up.
- Dead-letter size: any growth needs a human.
Depth alone misleads. A queue of 10,000 jobs that workers drain in 20 seconds is healthy, while a queue of 50 whose oldest job has waited an hour means the workers are stuck. Alerting on oldest age catches the second case and ignores the first.
- "What is a dead-letter queue for?"
-
A dead-letter queue (DLQ) is a parking place for jobs that keep failing. Without it, a job that can never succeed has only two bad outcomes: it is retried forever, or it is dropped silently.
The flow is simple. A job fails and is retried a limited number of times, usually with growing waits (for example 10 seconds, 1 minute, 10 minutes). After the last attempt, the worker moves the job, with its payload, the error text and the attempt count, to the DLQ and acknowledges the original. The main queue is free again.
The reason this matters is the poison message: a job with bad data, for example an order id that no longer exists. If it is retried endlessly it occupies a worker slot every cycle and can starve healthy jobs.
The DLQ is only useful if someone looks at it. Alert when its size grows, give engineers a tool to inspect a message, and a way to replay it once the bug is fixed. Replay needs idempotent jobs, so running one twice is harmless.
Q127 · Scenario. "Order-confirmation emails are lost on every deploy. Why, and how do you fix it?"
Reveal answer
The real test Whether you say what really happens on SIGTERM (a grace window, then cancellation) and why even a long window does not fix crashes, then reach for an outbox.
Strong answer BackgroundTasks run inside the web process after the response. During a deploy Kubernetes sends SIGTERM. Uvicorn stops accepting new connections, waits for in-flight requests and background tasks, but only for the graceful-shutdown window (--timeout-graceful-shutdown). If a task is still running when the window ends, it is cancelled. And if the pod is killed with SIGKILL, runs out of memory or crashes, nothing waits at all. Nothing ever retries the lost task.
So "emails are lost on every deploy" means the tasks take longer than the window, or the pods are killed harder than expected. A longer window helps a little, but it cannot help against crashes and it slows deploys.
The durable fix is the transactional outbox. In the same database transaction that saves the order, insert an outbox row (order_confirmation, order id). A separate worker polls unsent rows, sends the email, and marks the row sent. If the web pod dies, the row is still in the database. If the worker dies after sending but before marking, the next run sends again, so the email handler must tolerate repeats (an idempotency key per order and message kind).
Picture it First, what uvicorn really does with a 3-second task when SIGTERM arrives half a second after the response, with a 10-second window and then a 1-second window. (Measured with the script from section 07, code/e20-python-api/C/sigterm_experiment.sh.)
[t=0] POST /orders-broken
[t=0] POST /orders (response now, email task takes 3 s)
[t=0.5] SIGTERM
{"done":true} <- /slow finished with HTTP 200
uvicorn exit code 143
INFO: Shutting down
INFO: Waiting for connections to close. (CTRL+C to force quit)
INFO: Waiting for background tasks to complete. (CTRL+C to force quit)
email for order 1 sent
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [269407][t=0] POST /orders-broken
[t=0] POST /orders (response now, email task takes 3 s)
[t=0.5] SIGTERM
Internal Server Error <- /slow finished with HTTP 500
uvicorn exit code 143
INFO: Shutting down
INFO: Waiting for connections to close. (CTRL+C to force quit)
ERROR: Cancel 2 running task(s), timeout graceful shutdown exceeded
INFO: Waiting for application shutdown.
asyncio.exceptions.CancelledError: Task cancelled, timeout graceful shutdown exceeded
asyncio.exceptions.CancelledError: Task cancelled, timeout graceful shutdown exceeded
INFO: 127.0.0.1:37876 - "GET /slow HTTP/1.1" 500 Internal Server Error
INFO: Application shutdown complete.What you see: With 10 seconds, uvicorn logs Waiting for background tasks to complete, the email is sent, and the in-flight request finishes with 200. With 1 second it logs Cancel 2 running task(s), timeout graceful shutdown exceeded: the in-flight request becomes a 500 and the task never completes.
The fix: Now the outbox. The order and the outbox row commit together; a worker crash after sending produces a repeat, never a loss.
import sqlite3
db = sqlite3.connect(":memory:", isolation_level=None)
db.executescript("""CREATE TABLE orders (id INTEGER PRIMARY KEY, total_cents INT);
CREATE TABLE outbox (id INTEGER PRIMARY KEY, kind TEXT, order_id INT, sent_at TEXT);""")
def place_order(total):
db.execute("BEGIN") # order + outbox row: ONE transaction
oid = db.execute("INSERT INTO orders (total_cents) VALUES (?)", (total,)).lastrowid
db.execute("INSERT INTO outbox (kind, order_id) VALUES ('order_confirmation', ?)", (oid,))
db.execute("COMMIT"); return oid
def relay_once(send, crash_after_send=False):
for row_id, order_id in db.execute("SELECT id, order_id FROM outbox WHERE sent_at IS NULL ORDER BY id").fetchall():
send(order_id)
if crash_after_send: raise SystemExit("worker killed after sending, before marking")
db.execute("UPDATE outbox SET sent_at = datetime('now') WHERE id = ?", (row_id,))
place_order(1200); place_order(900)
print("pending after commit :", db.execute("SELECT count(*) FROM outbox WHERE sent_at IS NULL").fetchone()[0], "(survives any restart: it is in the database)")
sent = []
try: relay_once(sent.append, crash_after_send=True)
except SystemExit as e: print("crash :", e)
relay_once(sent.append) # the next worker simply continues
print("emails sent :", sent, "<- order 1 twice: at-least-once, so the email handler must be idempotent")
print("pending now :", db.execute("SELECT count(*) FROM outbox WHERE sent_at IS NULL").fetchone()[0])Make the invisible visible: Real output.
pending after commit : 2 (survives any restart: it is in the database)
crash : worker killed after sending, before marking
emails sent : [1, 1, 2] <- order 1 twice: at-least-once, so the email handler must be idempotent
pending now : 0Why: Both rows are still pending after the commit, whatever happens to the web process. The simulated worker crash after sending order 1 causes a second send of order 1 on the next run, which is the "at least once" cost, so the sender needs an idempotency key. See the outbox pattern in Chapter E7.
BackgroundTasks
Hope the process lives.
db.commit()
bg.add_task(send_email, order.id)
# ❌ crash here: order saved, email goneOutbox
Written with the order.
with session.begin():
session.add(order)
session.add(Outbox("email", order))
# worker sends later, retries, marks sentThe shift: Make "this must happen" a row in the database, not a promise in memory.
Land it Tasks in the web process die with it, so I write an outbox row in the order's transaction and let an idempotent worker send and retry.
- "Why not just raise the graceful-shutdown timeout?"
-
A longer graceful-shutdown window helps only with orderly stops, and even there it helps a little. It does not make the work durable.
Think about the ways a pod ends. On a normal deploy, Kubernetes sends SIGTERM, uvicorn waits up to the window, and tasks that finish in time are safe. Raising the window from 10 to 60 seconds helps tasks that take 30 seconds. But Kubernetes also has its own limit,
terminationGracePeriodSeconds(30 s by default). When that passes, it sends SIGKILL, and nothing waits any more. You must raise both numbers together.Then there are stops with no warning at all: an out-of-memory kill, a node failure, a crash from a bug. No window helps there, and the task is simply gone.
A long window also has a price. Every rollout takes longer, because old pods linger, and a stuck request holds a pod for the full time.
So I set a sensible window for in-flight requests, and I make the email durable with an outbox, so the window is a courtesy and not the only protection.
- "How does the worker avoid sending twice when two workers run?"
-
Two layers make two workers safe: claim each row atomically, and make the send itself tolerate a repeat.
The claim is done by the database. On PostgreSQL, a worker selects unsent rows with
FOR UPDATE SKIP LOCKED. This locks the rows it picks, and a second worker running the same query at the same moment skips those locked rows and takes different ones. So within one transaction the two workers never receive the same row.The claim alone is not enough, because a worker can die after sending the email but before it marks the row as sent. The row stays unsent, and the next worker sends it again. No locking trick closes that gap, because the email provider and the database are two systems.
The answer is an idempotency key. I send the key
(order_id, "confirmation")to the provider, if it supports one, and I keep a unique record of what was sent. A repeat attempt then finds the record or the key and does nothing. - "Could I publish to Kafka directly instead?"
-
Not in the same step as the request, because that is a dual write. The order lives in the database and the event lives in Kafka, and no single transaction covers both.
Take the two orders of operations. If you commit the order and then publish, a crash between the two leaves a saved order with no event, so no email. If you publish first and then commit, a database failure leaves an event for an order that does not exist. In both cases the two systems disagree, and the disagreement is silent.
The outbox removes the problem by writing only to the database. The order and the outbox row are committed together, so they are either both there or both missing. A separate relay process then reads unsent outbox rows and publishes them to Kafka, marking each as published afterwards. Change-data-capture does the same by reading the database log instead of polling.
The relay can publish a row twice after a crash, so consumers must be idempotent. That is the accepted price: at-least-once delivery, with nothing lost.
- "What should the email message say if it arrives twice?"
-
It should say exactly the same thing. A customer who gets two identical confirmations is mildly annoyed. A customer who gets two different ones, such as a different total or a different delivery time, is confused and may phone support.
To achieve that, build the message from the stored order, not from the moment of sending. Do not put "now" or a counter of attempts in the text. If the order is read again, the content is the same, as long as the order has not changed. If the order changed in between, for example it was cancelled, the second email should reflect the current state, or better, be skipped.
The second protection is a record of what was sent. A table
sent_messageswith a unique constraint on(order_id, kind)means the second insert fails, and the worker treats that failure as "already done" and moves on.Insert the record before or together with the send, depending on which failure you prefer: sending once too many, or once too few. For a confirmation email, a repeat is the lesser evil.
Q128. "How do you run periodic jobs?"
Reveal answer
Strong answer A periodic job ("cancel orders unpaid after 30 minutes", "send a daily summary") has one hard requirement: with several pods it must run once per tick, not once per pod. An in-process timer (asyncio.create_task in lifespan) runs in every replica, so the job runs twenty times.
The options, from simplest to most flexible. A Kubernetes CronJob starts a fresh container on a schedule; it is the cleanest for infrequent or heavy jobs and needs nothing in the app. A scheduler inside a worker system (Celery beat, arq cron, APScheduler in a single dedicated process) suits frequent jobs.
Every pod runs the loop but takes a lock first: only the pod that wins a lease runs the tick. The lock can be a database row with an expiry, PostgreSQL advisory locks, or a Redis key with SET NX EX.
Whichever you choose, make the job itself idempotent and bounded: process rows in batches, and use "state transitions" (WHERE status = 'unpaid' AND created_at < :cutoff) so running it twice does no harm. Add a lease expiry so a crashed leader's lock frees itself.
Picture it A lease in one table. Three pods try each tick; the winner is decided by one atomic UPDATE. Midway, the leader dies.
import sqlite3
db = sqlite3.connect(":memory:", isolation_level=None)
db.execute("CREATE TABLE job_locks (name TEXT PRIMARY KEY, owner TEXT, until REAL)")
def try_lead(job, pod, now, ttl=60):
"""One atomic statement: take the lock if it is free or expired. rowcount says who won."""
db.execute("INSERT OR IGNORE INTO job_locks VALUES (?, NULL, 0)", (job,))
cur = db.execute("UPDATE job_locks SET owner=?, until=? WHERE name=? AND (until < ? OR owner=?)",
(pod, now + ttl, job, now, pod))
return cur.rowcount == 1
pods = ["pod-a", "pod-b", "pod-c"]
for t in (100, 160, 220, 280, 340):
if t == 220: pods.remove("pod-a"); print("-- pod-a is OOM-killed --")
winners = [pod for pod in pods if try_lead("expire-stale-orders", pod, now=t, ttl=50)]
print(f"t={t:3}s pods running the job this tick: {winners}")Make the invisible visible: Real output.
t=100s pods running the job this tick: ['pod-a']
t=160s pods running the job this tick: ['pod-a']
-- pod-a is OOM-killed --
t=220s pods running the job this tick: ['pod-b']
t=280s pods running the job this tick: ['pod-b']
t=340s pods running the job this tick: ['pod-b']Why: Only one pod runs the job each tick. When pod-a disappears, its lease runs out (50 seconds) and pod-b takes over without any human action. The rowcount of the conditional UPDATE is the whole election.
Timer in every pod
Twenty runs per tick.
@asynccontextmanager
async def lifespan(app):
# ❌ runs in every replica
asyncio.create_task(every(60, expire_orders))
yieldLease or CronJob
One runner per tick.
async def tick():
if await try_lead("expire-orders", POD):
await expire_orders() # idempotent
# or: kind: CronJob, schedule "*/1 * * * *"The shift: Scheduling and electing a runner are two problems; solve both.
Land it Periodic work runs from a Kubernetes CronJob or from a single elected runner, and the job itself is idempotent and batched so a double run is harmless.
- "CronJob or in-app scheduler?"
-
I use a CronJob by default and an in-app scheduler only when I have a reason. The reason is usually the interval or the start-up cost.
A Kubernetes CronJob starts a fresh container on a schedule, runs a command and exits. It needs no code in the web app, each run has its own logs and exit code, and settings such as
concurrencyPolicy, a deadline and a retry limit are built in. The smallest interval is one minute, and starting a container takes some seconds, so it suits jobs at least a minute apart.An in-app scheduler fits when ticks are more frequent than that, for example every 10 seconds, or when starting a new process is costly because it loads a large model. Because every pod runs the loop, you add a lease so one pod wins each tick.
A rule of thumb: a daily report, a nightly cleanup or an hourly sync should be a CronJob. A "check for expired holds every 5 seconds" job belongs in a worker with a lease.
- "What if the job takes longer than the interval?"
-
An overlap is a design case to handle on purpose, since a slow run that starts a second copy can double the load that made it slow.
With a Kubernetes CronJob, set
concurrencyPolicy: Forbid. If the previous run is still active when the next tick arrives, Kubernetes skips the new one.Replacekills the old run instead, which is usually wrong for jobs that are half-way through.Allow, the default, starts a second copy.With a lease in an in-app scheduler, the pod holding the lease renews it while it works, and other pods see the lease taken and skip the tick. If the pod dies, the lease expires after its time limit and another pod takes over.
Also make the job fit the interval. Process rows in bounded batches, for example 500 at a time, so one run has a predictable length. Then alert when a run takes more than half the interval, since that is the early sign that the job will soon overlap itself.
- "What about missed runs after downtime?"
-
The answer is different for each job, and the question to ask is whether a missed tick should be made up or forgotten.
- Catch-up jobs: "cancel orders unpaid for 30 minutes" finds everything overdue by its query, so after downtime the first run simply handles the backlog. Nothing special is needed.
- Point-in-time jobs: "send the 9 a.m. summary" should not send three summaries when the service returns at noon. Decide whether to send one late or skip it.
- Counting jobs: any job that assumes "I run exactly every minute" breaks after downtime.
The robust method is to store the time of the last successful run, and at each tick work out what is due from that time and the current time, rather than counting ticks. Kubernetes helps a little: a CronJob has
startingDeadlineSeconds, which limits how late a missed run may still start. If more than 100 runs are missed, the controller stops scheduling it, which is worth knowing. - "How do I test a scheduled job?"
-
Split the job into two parts and test each on its own. Never test it by waiting for the real schedule.
First, the work itself: a plain function such as
cancel_unpaid_orders(session, now). Pass the current time in as an argument, so a test can supply a fixed one. Create orders with different ages in a test database, call the function withnowset to a chosen moment, and check that exactly the orders older than 30 minutes were cancelled. Then call it a second time and check that nothing changes. That second call is the idempotency test, and it is the most valuable one.Second, the election or lease logic: with a fake clock, check that one of two instances wins, that the other skips, and that when the first stops renewing, the second wins after the lease expires.
The cron expression itself is configuration. Check it once with a tool that prints the next run times, and keep it out of the tests.
Q129. "Structured logging with request ids across async code."
Reveal answer
Strong answer In an async server one process handles many requests at once, interleaved on one thread, so a plain log line cannot say which request wrote it. The fix has three parts. Generate or accept a request id (X-Request-ID) in a middleware, store it in a ContextVar, and have a logging processor attach it to every line.
A ContextVar is the right storage because each asyncio task has its own copy of the context. Setting the id in one request's task does not change it in another's, even though they share a thread. A global variable would be overwritten by whichever request ran last.
The context follows await automatically and is copied into tasks you create and into threads started with asyncio.to_thread and the threadpool that runs plain def endpoints. It is not copied into threads you start by hand, so pass the id explicitly there.
Write the middleware as pure ASGI (not BaseHTTPMiddleware), which keeps the context intact for the endpoint. Echo the id in a response header so a customer can quote it. Structured JSON logs (structlog) then let you search by the id. See the contextvars idiom in Chapter E19.
Picture it Two concurrent "requests" that log before and after awaits and from a worker thread.
import asyncio, contextvars, logging, sys
request_id = contextvars.ContextVar("request_id", default="-")
class Rid(logging.Filter):
def filter(self, record): record.rid = request_id.get(); return True
h = logging.StreamHandler(sys.stdout); h.addFilter(Rid()); h.setFormatter(logging.Formatter("rid=%(rid)s %(message)s"))
log = logging.getLogger("qb"); log.addHandler(h); log.setLevel(logging.INFO)
def blocking_lookup(): # runs in a worker thread
log.info("thread: loading menu")
async def handle(rid, delay):
request_id.set(rid)
log.info("start")
await asyncio.sleep(delay) # other requests run meanwhile
await asyncio.to_thread(blocking_lookup) # to_thread copies the context into the thread
log.info("done")
asyncio.create_task(asyncio.sleep(0)) # tasks created here also inherit the context
async def main():
await asyncio.gather(handle("req-A", 0.02), handle("req-B", 0.01))
print("after both, in the parent task:", request_id.get())
asyncio.run(main())Make the invisible visible: Real output.
rid=req-A start
rid=req-B start
rid=req-B thread: loading menu
rid=req-B done
rid=req-A thread: loading menu
rid=req-A done
after both, in the parent task: -What you see: The lines interleave (A and B started together, B finished first), yet every line carries the right id, including the one logged from a worker thread. After both finish, the parent task still has the default -, because each handler changed only its own copy.
Global variable
Last writer wins.
CURRENT = None # ❌ shared by all requests
def log(msg): print(CURRENT, msg)ContextVar
One value per task.
rid = ContextVar("rid", default="-")
def log(msg): print(rid.get(), msg)
# middleware: rid.set(incoming_or_new())The shift: Per-request state in async code must live in the task's context, not in a module global.
Land it A pure ASGI middleware sets a ContextVar and a log processor adds it to every line, so interleaved async logs stay attributable and the id is returned to the client.
- "Why is
BaseHTTPMiddlewarea problem here?" -
BaseHTTPMiddlewareis a convenient way to write middleware, but it adds a layer that changes how the request runs, and that causes surprises around context.It wraps the downstream app and runs it in a separate task, passing the request and response through memory streams. A ContextVar set inside the endpoint's task may not be visible to the middleware after the call, and in some versions a value set in the middleware did not reach the endpoint the way you expect. The exact behaviour has changed between Starlette versions, so check your own with a test. It also has known caveats with streaming responses and with background tasks.
Pure ASGI middleware avoids all of it. It is a class with
__init__(self, app)andasync __call__(self, scope, receive, send). It sets the ContextVar, callsawait self.app(scope, receive, send)in the same task, and wrapssendto add the response header. It is a little more code, and it is faster, because there are no streams in between.For anything that touches context, I write pure ASGI.
- "Where does the id come from for a call between services?"
-
The id should come from the first service that sees the request, and every service after that should pass it on unchanged.
At the edge, the gateway or the first service reads
X-Request-IDfrom the incoming request. If it is there, check its length (for example 64 characters at most) and that it contains only safe characters, since the value goes straight into your logs and a hostile client could try to forge log lines. If it is missing or invalid, generate a UUID.When tracing is in use, the W3C
traceparentheader carries a trace id in a standard form, and the tools already understand it. I prefer to reuse that id as the request id when it exists, so logs and traces join with no extra mapping.Every outbound call, whether HTTP or a message on a queue, must copy the id into a header or the payload. One missing hop breaks the chain. The payoff is that a single id finds a customer's order in the logs of all services, in order.
- "What about background tasks and workers?"
-
A background task or a worker runs outside the request, so the ContextVar from the request is not there, and the log lines lose their id unless you carry it over by hand.
The method has two ends. At enqueue time, read the current id with
request_id_var.get()and put it in the job payload, next to the business data, for example{"order_id": 42, "request_id": "a1b2"}. At the start of the job, in the worker, read it back and callrequest_id_var.set(...)before doing any work. A small decorator on the job function can do this for every job.For FastAPI's own
BackgroundTasks, the context is copied into the task when it is started inside the same process, so the id usually remains. I would still test it, rather than trust it.If a job fails and is retried, keep the original id. It lets you follow one customer action from the request, through the queue, to the retry, in one search.
- "Should the id be in every error body?"
-
Yes, put it in every error body. It costs one field and it saves the most time when something goes wrong.
Picture a customer who sees "Something went wrong" and phones support. If the error body and the screen show
request_id: "7f3c...", the support agent asks for that string, an engineer searches the logs for it, and within seconds sees the whole request: the route, the user, the database error, the call to the payment service that timed out. Without it, the engineer has a customer name and an approximate time and starts a search through thousands of lines.The same id should also be in the
X-Request-IDresponse header, so it exists even for successful responses that the customer still thinks are wrong.Two cautions. The id must be random and carry no meaning, so it reveals nothing. And the error body must still hide internals: show the id and a friendly message, and keep the stack trace in the log only.
Q130. "OpenTelemetry for FastAPI: traces, metrics and logs."
Reveal answer
Strong answer OpenTelemetry (OTel) is a vendor-neutral standard and set of libraries for three signals. Traces show one request's path as a tree of timed spans (the HTTP handler, a database call, a payment call). Metrics are numbers over time (request rate, error rate, latency histograms). Logs are the events you already write, linked to a trace by trace and span ids.
In FastAPI you use instrumentation packages (opentelemetry-instrumentation-fastapi, -sqlalchemy, -httpx) that create spans automatically for requests, queries and outbound calls, and propagate the W3C traceparent header so spans from different services join into one trace. The SDK exports to a collector (OTLP) that forwards to a backend (Tempo, Jaeger, a vendor). The instrumentation packages are not installed on the course machine, only the API and SDK, so the demo creates spans by hand.
Practical points. Name spans by route template (POST /v1/orders), never by raw URL, to avoid unbounded cardinality. Sample (keep 1 to 10 percent of traces, plus all errors) to control cost. Put service.name in the resource. Link logs by adding the trace id to log lines next to the request id.
Picture it Three spans created by hand with the SDK and an in-memory exporter, showing the parent and child structure instrumentation would create for you.
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
exporter = InMemorySpanExporter()
provider = TracerProvider(resource=Resource.create({"service.name": "quickbite-api"}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("quickbite")
with tracer.start_as_current_span("POST /v1/orders", attributes={"http.request.method": "POST"}) as root:
with tracer.start_as_current_span("db.insert_order", attributes={"db.system": "postgresql"}):
pass
with tracer.start_as_current_span("http.payments.charge", attributes={"server.address": "payments"}) as s:
s.set_attribute("http.response.status_code", 504); s.set_status(trace.Status(trace.StatusCode.ERROR))
spans = exporter.get_finished_spans()
tid = {s.context.trace_id for s in spans}
print("spans:", [s.name for s in spans], "| distinct trace ids:", len(tid))
for s in spans:
parent = s.parent.span_id if s.parent else None
print(f"{s.name:24} span={s.context.span_id:016x} parent={parent and format(parent,'016x')} status={s.status.status_code.name}")Make the invisible visible: Real output (span ids differ on every run).
spans: ['db.insert_order', 'http.payments.charge', 'POST /v1/orders'] | distinct trace ids: 1
db.insert_order span=b874f5aeded3bd44 parent=aad80fe5f2bfe322 status=UNSET
http.payments.charge span=52ee123bb5e93fd2 parent=aad80fe5f2bfe322 status=ERROR
POST /v1/orders span=aad80fe5f2bfe322 parent=None status=UNSETWhat you see: All three spans share one trace id. The database and payment spans have the request span as their parent. The payment span is marked ERROR with status 504, so in a trace viewer the slow, failing child is obvious while the parent request looks fine on its own.
Logs only
You grep and guess.
12:01:03 INFO POST /v1/orders 504 2,410 ms
12:01:03 ERROR payments timeout
# which call? how long? which pod?Trace
The tree answers it.
POST /v1/orders 2,410 ms
db.insert_order 18 ms
http.payments.charge 2,350 ms ERROR 504The shift: A log line says that something happened; a trace says where the time went.
Land it I use OpenTelemetry auto-instrumentation for FastAPI, SQLAlchemy and httpx, export through a collector with sampling, and join logs to traces by id.
- "How do traces cross service boundaries?"
-
A trace crosses a service boundary through one HTTP header,
traceparent, and each side has a job to do.The header looks like
00-4bf92f35...-00f067aa0ba902b7-01. It holds a version, a 32-character trace id, the 16-character id of the calling span (the parent), and flags such as "this trace is sampled". The caller's instrumentation adds it to every outgoing request. The callee's instrumentation reads it and creates its own spans with the same trace id, using the caller's span as the parent. The backend then draws one tree from spans reported by two services.The weak points are the hops that do not use HTTP. A message put on a queue needs the header copied into the message headers or payload, and the consumer must read it and start its span as a child. If one service forgets, the trace splits into two unrelated traces, and nobody sees the full path.
I test propagation early, with a request through every service, before relying on traces in an incident.
- "What is the cost?"
-
The cost is real but small when it is configured sensibly. I would expect a few percent of CPU, some extra memory for spans that wait to be exported, and a little added latency from creating spans. I would measure it on my own service, since the figure depends on how many spans each request makes.
The main control is sampling. Head sampling decides at the start of a trace whether to keep it, for example keep 5 percent. It is cheap, but it decides before it knows whether the request will be slow or fail, so it can drop exactly the traces you wanted.
Tail sampling waits until the trace is finished, inside a collector, and then decides: keep every trace with an error, keep every one slower than a second, and keep 1 percent of the rest. It costs memory in the collector, since it must hold traces until they end, but it keeps the interesting ones.
A good start is head sampling at a low rate in the app, plus a collector that keeps all errors.
- "OpenTelemetry or Prometheus for metrics?"
-
They are not rivals, and I choose by what the team already runs. Prometheus is a metrics system with its own text format, a pull model, a query language (PromQL) and mature alerting. OpenTelemetry is a set of standards and libraries that can produce metrics, traces and logs, and send them anywhere.
Many teams use
prometheus_clientfor metrics, since the dashboards, alerts and community knowledge are mature, and OpenTelemetry for traces. The two meet through the collector: OTel metrics can be exported to Prometheus, and the collector can also scrape Prometheus endpoints.The trap is duplication. If the same request count is produced by both a Prometheus counter and an OTel instrument, you get two numbers that are slightly different, and a long argument about which is right. Choose one library per metric.
If you start fresh and want all three signals in one pipeline, OTel for everything is a reasonable choice. If you already have Prometheus, keep it and add OTel for traces.
- "What goes wrong most often?"
-
Three mistakes account for most of the pain, and all three can be avoided at review time.
- Unbounded attributes: putting a user id, an order id or a full URL with its query string into a metric label or a span name. Each distinct value makes a new time series or a new group, and storage and cost grow without limit. Use the route template
/v1/orders/{order_id}, and keep ids as span attributes on traces only, never as metric labels. - Broken propagation: a queue message, a thread pool or a hand-made HTTP call that does not pass the context. The trace stops at that hop.
- Sampling that drops the errors: head sampling at 1 percent keeps 1 percent of failures too.
A fourth, quieter problem is cost surprise: a chatty library that creates hundreds of spans per request. I review attributes the way I review log lines, asking what each one costs and who will use it.
- Unbounded attributes: putting a user id, an order id or a full URL with its query string into a metric label or a span name. Each distinct value makes a new time series or a new group, and storage and cost grow without limit. Use the route template
Q131. "Health versus readiness endpoints — what does each check?"
Reveal answer
Strong answer Kubernetes asks two different questions, and each needs its own endpoint.
Liveness (/healthz): "is the process stuck beyond repair?" If it fails, Kubernetes restarts the container. It must check almost nothing: that the event loop answers. Never put the database or other services in it, or a database outage makes every pod restart in a loop and turns a partial failure into a total one.
Readiness (/readyz): "can this pod take traffic right now?" If it fails, Kubernetes removes the pod from the Service's endpoints but does not restart it. It may check that the database answers a SELECT 1, that migrations are applied and the cache is warm. It must also fail when the pod is draining on shutdown, so the load balancer stops sending new requests before the process exits.
A third probe, startup, gives slow-starting apps extra time before liveness begins, so a 40-second start (Q140) is not killed. Keep probe handlers cheap, give each a short timeout, and return 503 with a small JSON body.
Picture it The two endpoints in a small app, tried in three situations.
from fastapi import FastAPI, Request, Response
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, text
app = FastAPI()
app.state.engine = create_engine("sqlite://"); app.state.draining = False
@app.get("/healthz")
def healthz(): return {"status": "alive"} # process is up: no dependencies checked
@app.get("/readyz")
def readyz(request: Request, response: Response):
if request.app.state.draining:
response.status_code = 503; return {"status": "draining"}
try:
with request.app.state.engine.connect() as c: c.execute(text("SELECT 1"))
except Exception as e:
response.status_code = 503; return {"status": "db_unreachable", "error": type(e).__name__}
return {"status": "ready"}
c = TestClient(app)
print("healthy :", c.get("/healthz").status_code, c.get("/readyz").json())
app.state.engine = create_engine("sqlite:////nonexistent-dir/x.db")
print("DB down :", c.get("/healthz").status_code, c.get("/readyz").status_code, c.get("/readyz").json())
app.state.engine = create_engine("sqlite://"); app.state.draining = True
print("draining :", c.get("/healthz").status_code, c.get("/readyz").status_code, c.get("/readyz").json())Make the invisible visible: Real output.
healthy : 200 {'status': 'ready'}
DB down : 200 503 {'status': 'db_unreachable', 'error': 'OperationalError'}
draining : 200 503 {'status': 'draining'}What you see: /healthz stays 200 in all three situations, because the process is fine. /readyz is 200 when the database answers, and 503 when it does not (db_unreachable) or when the pod is draining. That combination is exactly what Kubernetes needs: no restart for a database blip, but no traffic either.
One /health that checks everything
A database blip restarts every pod.
@app.get("/health")
def health():
db.execute("SELECT 1") # ❌ in liveness
redis.ping()
return {"ok": True}Two endpoints
Alive is cheap, ready is honest.
@app.get("/healthz")
def alive(): return {"status": "alive"}
@app.get("/readyz")
def ready(): ... # DB ok and not drainingThe shift: Restarting a healthy process does not fix a sick database, so keep the two questions apart.
Land it Liveness checks only that the process responds, readiness checks the dependencies I need and flips to 503 while draining, and a startup probe covers slow starts.
- "Should readiness check every downstream service?"
-
Only the ones the pod cannot do its main job without, and each with a short timeout. Readiness answers "should this pod receive traffic?", so it should fail only when sending traffic would produce errors.
For QuickBite, orders cannot work without the database, so the database check belongs in readiness. A notification provider or a maps service is different. If the maps service is down, orders can still be created and the estimated delivery time can be missing. Failing readiness for it would be wrong.
The dangerous case is a shared failure. If readiness includes a flaky third party, then on its bad minute every pod fails readiness together, the Service has no endpoints, and the whole API returns errors. One partial failure has become a total outage.
My rule is to check hard dependencies in readiness with a timeout of about a second, cache the result for a few seconds so that probes do not hammer the database, and report optional dependencies in metrics and logs instead.
- "What probe settings do you use?"
-
These are the starting values I use, and I adjust them from measurements, since a guess goes stale.
probe settingsruns offlinestartupProbe: {periodSeconds: 2, timeoutSeconds: 2, failureThreshold: 30} # up to 60 s livenessProbe: {periodSeconds: 10, timeoutSeconds: 2, failureThreshold: 3} # dead after 30 s readinessProbe: {periodSeconds: 5, timeoutSeconds: 2, failureThreshold: 2} # out after 10 sThe startup probe gives a slow start up to 30 failures times 2 seconds, which is 60 seconds. Liveness and readiness do not run until it succeeds.
Liveness is slow and patient on purpose: a restart is expensive, so I want 30 seconds of failure before it happens. Readiness is quicker, because removing a pod from traffic is cheap and reversible, so 10 seconds of failure is enough.
Then I measure the real start-up time on a cold node and set the startup window to about double it. The timeout of 2 seconds must be longer than the probe's own slowest response, or a busy pod fails probes it would pass.
- "Why must readiness fail during shutdown?"
-
Because two things happen at the same moment when a pod is stopped, and they are not coordinated. Kubernetes starts removing the pod from the Service's endpoint list, and it sends SIGTERM to the container. The endpoint change then travels to the load balancer or the proxies, which takes anywhere from a fraction of a second to several seconds.
If the server stops accepting connections right at SIGTERM, requests that the load balancer still sends to this pod meet a closed port and fail. Users see a burst of errors at every deploy.
Failing readiness first closes the gap. When SIGTERM arrives, the app sets a flag, so
/readyzanswers 503. The next probe marks the pod unready, and the traffic moves away, while the pod continues to serve requests it already has.The simple version is a
preStophook that runssleep 5. It delays SIGTERM by 5 seconds, which is usually enough for the endpoint removal to spread. Budget for that sleep inside the termination grace period. - "Does the probe path need authentication?"
-
No, keep the probe paths open without authentication. The kubelet, which calls them, has no token for your application, and a probe that needs a login would fail forever.
An open path is safe if it reveals nothing. Return a tiny body such as
{"status": "ok"}. Do not include hostnames, version numbers, database names or exception text, because an attacker who can reach the path learns about your internals. If readiness fails, the status code 503 is enough, and details belong in your logs.Then reduce who can reach it. If the probes come only from the kubelet on the node, you can serve them on a separate port that the public Service does not expose, or block
/healthzand/readyzat the ingress so they are not reachable from the internet.Keep them cheap too. An unauthenticated endpoint that runs a heavy database query is a free way for anyone to load your database.
Q132 · Scenario. "Uvicorn worker memory grows until the pod is OOMKilled. Investigate."
Reveal answer
The real test Whether you separate a real leak from normal growth and know how to find the growing allocation with data, not guesses.
Strong answer First decide whether it is a leak or steady growth to a plateau. Plot the memory of one worker over hours: caches, connection pools and warmed-up imports rise and then flatten. A leak keeps rising with the number of requests. Also compare per-worker memory with the pod's limit, because N workers multiply the footprint.
Then find what is growing. Use tracemalloc (snapshots before and after a period of traffic, compared by line) in a staging pod, or a heap tool such as memray or objgraph.
The usual suspects in a FastAPI service are: a module-level dict or list used as a cache with an unbounded key space (user input as key), per-request objects stored in a global (a registry, a list of connections), a client or session created per request and never closed, unbounded in-memory queues behind a slow consumer, WebSocket or SSE subscribers never removed when clients leave (Q108), and large responses held in memory.
Fixes: bound every cache (lru_cache(maxsize=...) or a TTL cache), clean up in finally, close clients in the lifespan, bound queues, and let workers recycle as a safety net with --limit-max-requests (with jitter, so they do not all restart together). A recycle limit hides a leak but does not fix it, so keep investigating.
Picture it A cache keyed by free-text search strings, measured with tracemalloc, then the same loop through a bounded cache.
import tracemalloc
from functools import lru_cache
CACHE = {} # ❌ TRAP: module-level dict keyed by request data
def menu_for(restaurant_id, filters):
key = (restaurant_id, filters)
if key not in CACHE: CACHE[key] = ["row"] * 50
return CACHE[key]
tracemalloc.start()
snap0 = tracemalloc.take_snapshot()
for i in range(20_000): menu_for(i % 10, f"free-text-search-{i}") # unbounded key space: every search string is new
snap1 = tracemalloc.take_snapshot()
for stat in snap1.compare_to(snap0, "lineno")[:2]:
print(f"{stat.traceback[0].filename.split('/')[-1]}:{stat.traceback[0].lineno} +{stat.size_diff/1024:.0f} KiB (+{stat.count_diff} objects)")
print("dict entries:", len(CACHE))
@lru_cache(maxsize=1000) # ✅ bounded: oldest entries are evicted
def menu_bounded(restaurant_id, filters): return ["row"] * 50
for i in range(20_000): menu_bounded(i % 10, f"free-text-search-{i}")
print("lru_cache :", menu_bounded.cache_info())Make the invisible visible: Real output.
mem_leak.py:7 +9482 KiB (+39988 objects)
mem_leak.py:12 +1220 KiB (+20001 objects)
dict entries: 20000
lru_cache : CacheInfo(hits=0, misses=20000, maxsize=1000, currsize=1000)What you see: In this small loop of 20,000 requests, line 7 (the cache insert) grew by about 9.5 MiB and the dict holds 20,000 entries: one per distinct search string, never evicted. The bounded version stops at 1,000 entries. Scale that to a million requests with a 50-item payload each and a pod is out of memory within hours.
Unbounded cache
Grows with distinct inputs.
CACHE = {} # ❌ key space is user input
def menu(rid, q):
if (rid, q) not in CACHE:
CACHE[(rid, q)] = load(rid, q)
return CACHE[(rid, q)]Bounded
Evicts the oldest.
@lru_cache(maxsize=1000)
def menu(rid, q):
return load(rid, q)
# or a TTL cache with a size capThe shift: Every cache needs a maximum size; the key space is controlled by your users.
Land it I confirm a real leak by watching memory against requests, locate it with tracemalloc snapshots, bound caches and queues, and use max-requests recycling only as a safety net.
- "How do I take a snapshot in a running pod?"
-
I would start with a switch I can turn on without a redeploy, and take a snapshot comparison rather than a single snapshot. One snapshot says what is big, and a comparison says what is growing, and growth is the leak.
- Enable: an environment variable such as
TRACEMALLOC=1startstracemalloc.start(10)at boot, in one staging pod. It slows the process and adds memory, so it never runs on all pods. - Baseline: after warm-up, take a snapshot and keep it in memory.
- Compare: a protected admin route (or a signal handler) takes a second snapshot after traffic and logs
snapshot.compare_to(baseline, "lineno")[:20].
The top lines show which file and line allocated the growing memory. The route must be protected by authentication, and ideally reachable only inside the cluster, since it exposes internals.
Where I cannot change the code,
py-spy dumpshows what threads are doing, and memray records allocations against a staging copy fed with replayed traffic. - Enable: an environment variable such as
- "Why does memory not drop after freeing objects?"
-
Because freeing an object in Python does not mean the process gives the memory back to the operating system. The memory is returned to Python's allocator, or to the C library's allocator, which keeps it to hand out again. The number you see as resident memory (RSS) therefore stays near the highest point it reached.
So a graph that rises during a busy hour and then stays flat is usually not a leak. It is the high-water mark. The test is whether the next burst reuses that memory. If memory plateaus at about 400 MB and does not climb with each new burst, the process is just holding a reserve.
Fragmentation makes it worse. If a process allocates many objects of different sizes and frees most of them, a few survivors scattered through the arenas stop the allocator from releasing whole blocks.
The practical answers are to set the memory limit from the plateau, not from the idle value, and to let workers restart now and then with
--limit-max-requests, which returns everything to the system in one step. - "What is a sensible memory limit?"
-
Measure the plateau under realistic load and then add headroom. Do not take a number from a quiet pod.
sizing the podruns offlineplateau per worker = 300 MB (measured after an hour at peak load) workers per pod = 4 pod plateau = 4 x 300 = 1,200 MB request = 1,200 MB (what the scheduler reserves) limit = 1,200 x 1.4 = 1,680 MB (rounded to 1.7 GiB; 40% headroom)The request equals the plateau so that the scheduler places the pod on a node that really has the memory. The limit sits higher so that bursts do not trigger an OOM kill.
Each uvicorn worker is a separate process with its own imports and caches, so memory scales with the worker count, which is why one or two workers per pod is common. If the plateau itself keeps rising across days, the headroom only delays the kill. That is a leak, and sizing will not fix it.
- "How does
--limit-max-requestshelp?" -
It is a safety net. Each worker counts the requests it serves, and after the set number it shuts down cleanly and the supervisor starts a fresh process. A fresh process starts with only its imports in memory, so anything it had accumulated is released at once.
Take a service that leaks about 1 MB per 1,000 requests, from a library you cannot patch. With
--limit-max-requests 50000a worker never grows beyond roughly 50 MB of leaked memory before it restarts. That is the arithmetic that makes the leak tolerable.Two details matter. First, if all workers start together and have the same limit, they restart at the same time and capacity drops. Uvicorn has
--limit-max-requests-jitter(check the flag in your version withuvicorn --help), which adds a random amount to each worker's limit so the restarts spread out. Second, a restart has a cost, because in-flight requests must finish and the new process must warm up.I use it to buy time, and I keep looking for the real leak.
Q133. "Which Prometheus metrics should an API export?"
Reveal answer
Strong answer Start from the RED method for every route: Rate (requests per second), Errors (share of failed requests) and Duration (a latency histogram). With only those you can build the dashboard and the alerts that matter. Add the USE numbers (utilisation, saturation, errors) for the resources behind the API.
- Counter
http_requests_total{method,route,status}: gives rate and error rate. - Histogram
http_request_duration_seconds{route}: gives p50, p95 and p99 with buckets near your SLO (50 ms, 100 ms, 250 ms, 500 ms, 1 s). - Gauge
http_requests_in_flight: shows concurrency and saturation. - Database pool: connections in use, waiting requests, checkout wait time. This is the first thing to saturate (Q61).
- Event loop lag: how late a scheduled callback runs; it reveals blocking code (Q134).
- Business counters: orders created, out-of-stock conflicts, payment failures.
The cardinality rule: label with the route template (/v1/orders/{oid}), never the raw path, and never user ids, or the number of time series explodes. With several workers, use prometheus_client's multiprocess mode or run one worker per pod.
Picture it A metrics middleware that labels with the route template, and what the scrape endpoint prints. Three requests to one template and one to an unknown path.
import time
from fastapi import FastAPI, Request, Response
from fastapi.testclient import TestClient
from prometheus_client import CollectorRegistry, Counter, Histogram, generate_latest
reg = CollectorRegistry()
REQS = Counter("http_requests_total", "Requests", ["method", "route", "status"], registry=reg)
LAT = Histogram("http_request_duration_seconds", "Latency", ["route"], buckets=(0.05, 0.1, 0.25, 0.5, 1), registry=reg)
app = FastAPI()
@app.middleware("http")
async def metrics(request: Request, call_next):
start = time.perf_counter(); response = await call_next(request)
route = request.scope.get("route"); label = route.path if route else "unmatched" # the TEMPLATE, never the raw URL
REQS.labels(request.method, label, response.status_code).inc()
LAT.labels(label).observe(time.perf_counter() - start); return response
@app.get("/v1/orders/{oid}")
def get(oid: int): return {"id": oid}
@app.get("/metrics")
def scrape(): return Response(generate_latest(reg), media_type="text/plain")
c = TestClient(app)
for i in (1, 2, 3): c.get(f"/v1/orders/{i}")
c.get("/nope")
out = c.get("/metrics").text
print("\n".join(l for l in out.splitlines() if l.startswith(("http_requests_total{", "http_request_duration_seconds_count", 'http_request_duration_seconds_bucket{le="0.05"'))))Make the invisible visible: Real output (excerpt).
http_requests_total{method="GET",route="/v1/orders/{oid}",status="200"} 3.0
http_requests_total{method="GET",route="unmatched",status="404"} 1.0
http_request_duration_seconds_bucket{le="0.05",route="/v1/orders/{oid}"} 3.0
http_request_duration_seconds_count{route="/v1/orders/{oid}"} 3.0
http_request_duration_seconds_bucket{le="0.05",route="unmatched"} 1.0
http_request_duration_seconds_count{route="unmatched"} 1.0What you see: The three order requests are one series, route="/v1/orders/{oid}", not three. Unmatched paths share the label unmatched, so a scanner probing thousands of URLs cannot create thousands of series. The histogram buckets and count give percentile and rate.
Raw path label
One series per order id.
# ❌ TRAP: unbounded cardinality
REQS.labels(request.url.path).inc()
# /v1/orders/1, /v1/orders/2, ...Route template
A handful of series.
route = request.scope.get("route")
label = route.path if route else "unmatched"
REQS.labels(request.method, label,
status).inc()The shift: Label by the shape of the URL, not by its content.
Land it I export rate, errors and a duration histogram labelled by route template, plus pool, in-flight and event-loop-lag gauges and a few business counters, and I never label with user data.
- "Why a histogram and not an average?"
-
An average hides the slow requests, and the slow requests are what users complain about. A route can have an average of 40 ms while one request in a hundred takes 2 seconds, and the average barely moves.
A histogram records how many requests fell into each time bucket: under 50 ms, under 100 ms, under 250 ms, and so on. Prometheus stores a counter per bucket, and
histogram_quantile(0.99, ...)works out p99 from those counters over any time window you pick. Because the buckets are counters, you can add them across pods first and then compute the quantile, which gives a correct number for the whole service.A summary computes quantiles inside each process. Those quantiles cannot be combined, since the p99 of five pods is not the average of five p99 values. So I avoid summaries for APIs that run as several pods.
The one design choice is the buckets. Put them around your objective, for example 50 ms, 100 ms, 250 ms, 500 ms and 1 s, so that the SLO threshold falls on a bucket boundary and the estimate near it is exact.
- "What alerts do you build?"
-
I page on what users feel and open a ticket for what is merely drifting. A page wakes a person, so it must be urgent and must lead to an action.
- Errors: the share of 5xx responses above 2 percent for 5 minutes.
- Latency: p99 above the objective, for example 1 second, for 10 minutes.
- Saturation: database pool wait time growing, or the oldest queued job getting older. These warn before users see errors.
- Tickets, not pages: disk filling over days, a certificate expiring in 14 days, slow growth in memory.
The windows matter. A 5-minute error alert ignores a single blip but catches an outage quickly. A short window pages too often, and a long one reports too late.
I avoid paging on CPU alone. A pod at 90 percent CPU that answers fast and without errors is not hurting anyone, and an alert on it trains people to ignore the pager.
- "How do metrics work with several uvicorn workers?"
-
Each uvicorn worker is a separate process with its own memory, and so its own counters. A scrape of
/metricsreaches whichever worker the load balancer picks, and returns only that worker's numbers. The graph then jumps around, because each scrape sees a different process.There are two honest fixes. The first is the multiprocess mode of
prometheus_client. You set a directory in thePROMETHEUS_MULTIPROC_DIRenvironment variable, the workers write their values to files there, and the metrics endpoint merges them. It works, but it needs a clean directory at start-up, and gauges need extra care because there is no single "current value" across processes.The second is one worker per pod, scaled by adding pods. Each pod's endpoint is complete, Prometheus scrapes each pod separately, and the queries add them up.
Most Kubernetes services do the second. It is simpler, and a pod then equals a small, equal unit of capacity.
- "Where do metrics from OpenTelemetry fit?"
-
OpenTelemetry (OTel) metrics fit when you want one instrumentation system for traces, metrics and logs, or when you do not run Prometheus. The two are compatible, so the choice is about which you instrument with, not which you must pick for storage.
OTel metrics can be sent to a collector, and the collector can expose them in the Prometheus format for scraping, or push them to a Prometheus-compatible store. In the other direction, the collector can scrape existing Prometheus endpoints. Your Grafana dashboards and Prometheus alert rules then keep working.
The risk is double counting. If the FastAPI instrumentation package already records
http.server.durationand you also keep a hand-writtenhttp_request_duration_secondshistogram, you now have two latency series that differ slightly, and two alert sets that may disagree.Decide per metric which library owns it. Keep the names consistent. Remember that OTel and Prometheus name things differently, so after the first export, check the real names before building dashboards on them.
Q134 · Scenario. "One slow endpoint drags every other endpoint down. Why, in async, and how do you fix it?"
Reveal answer
The real test Whether you explain that the event loop is shared and any blocking call stalls everything, and that plain def endpoints go to a pool.
Strong answer All async def endpoints in one worker run on one event loop thread. The loop switches between requests only at await points. If one endpoint runs blocking code (time.sleep, a sync database or requests call, a CPU loop, a big JSON dump) without awaiting, the loop cannot run anything else until it returns. Every other request in that worker, even /health, waits.
The signs: p99 of unrelated routes rises together, CPU of one worker at 100 percent, health probes time out, and event loop lag climbs. Confirm with an asyncio debug warning ("Executing <Task> took 0.5 seconds") or a lag gauge.
Fixes by cause. Blocking I/O: use an async client, or declare the endpoint def so FastAPI runs it in the 40-thread pool, or call await run_in_threadpool(fn) for one blocking call. CPU-bound work: move it to a process pool or a worker queue, because threads share the GIL (Q148). Also run more workers so one stuck loop affects less traffic.
Picture it Three slow endpoints, each taking 0.5 s, called three times at once. A health probe is due 50 ms after they start. The output says how late the probe was started.
import asyncio, time, httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
async def health(): return {"ok": 1}
@app.get("/report-blocking")
async def report_blocking(): time.sleep(0.5); return {"ok": 1} # ❌ TRAP: blocks the loop for everyone
@app.get("/report-threadpool")
def report_threadpool(): time.sleep(0.5); return {"ok": 1} # ✅ plain def: runs in a worker thread
@app.get("/report-async")
async def report_async(): await asyncio.sleep(0.5); return {"ok": 1} # ✅ awaits: yields to the loop
async def measure(path):
t0 = time.perf_counter()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
done = {}
async def probe():
await asyncio.sleep(0.05); due = time.perf_counter()
await c.get("/health"); done["ms"] = (time.perf_counter() - due) * 1000
done["late_ms"] = (due - t0 - 0.05) * 1000 # how late the loop even got around to starting it
await asyncio.gather(c.get(path), c.get(path), c.get(path), probe())
return done
for p in ("/report-blocking", "/report-threadpool", "/report-async"):
d = asyncio.run(measure(p)); print(f"{p:20} probe started {d['late_ms']:6.1f} ms late, then took {d['ms']:4.1f} ms")Make the invisible visible: Real output.
/report-blocking probe started 1504.9 ms late, then took 1.4 ms
/report-threadpool probe started 26.1 ms late, then took 1.2 ms
/report-async probe started 2.0 ms late, then took 1.0 msWhat you see: With the blocking async def, the probe started about 1,505 ms late: the three 0.5 s sleeps ran one after another on the loop (3 x 0.5 s). As plain def in the threadpool it started 26 ms late, and with a real await asyncio.sleep only 2 ms late.
Blocking async
Everyone waits.
@router.get("/report")
async def report():
time.sleep(0.5) # ❌ blocks the loop
return build()Yields or pooled
Others keep moving.
@router.get("/report")
def report(): # ✅ runs in a thread
time.sleep(0.5)
return build()The shift: One word, async or not, decides whether a slow call stalls one request or the whole worker.
Land it All async endpoints share one loop, so one blocking call stalls every request; I move blocking I/O to def or a threadpool, CPU work to processes, and watch event loop lag.
- "How do I measure event loop lag in production?"
-
Measure how late the loop wakes a task that asked to sleep for a fixed time. That lateness is the lag, because the loop could not run the task until the blocking code finished.
loop lag proberuns offlineasync def loop_lag_monitor(gauge, interval=0.1): while True: start = time.perf_counter() await asyncio.sleep(interval) gauge.set(time.perf_counter() - start - interval)Start it as a task in the lifespan. If it sleeps 100 ms and wakes after 105 ms, the lag is 5 ms, which is normal. If it wakes after 600 ms, something held the loop for half a second.
I export the value as a gauge, or as a histogram so I can see the worst case, and alert when lag stays above about 50 ms. Lag shows up before the health probes time out, so it is an early warning.
The probe costs almost nothing, since it wakes ten times a second and does one subtraction.
- "Is plain
defalways the cure?" -
No. A plain
defendpoint moves the blocking code off the event loop, which is a real improvement, but the threadpool has a limit and the limit becomes the next problem.FastAPI runs plain
defendpoints in AnyIO's threadpool, which allows 40 threads at the same time by default. Suppose an endpoint blocks for 2 seconds on a slow report query. Forty requests at once use all the threads, the 41st waits for a free thread, and every otherdefendpoint waits behind it. The loop is fine, but this class of requests queues, and a queue means growing latency.So the order of preference is clear. First choice, an async client or driver, so that waiting uses no thread at all. Second,
defwith its 40 threads, which is fine for moderate concurrency. For CPU-bound work, a thread helps little because of the GIL, so a process pool or a queue is the answer.Also consider a separate limiter for the slow endpoint, so that it cannot use all 40 threads.
- "What does asyncio debug mode report?"
-
Debug mode makes asyncio watch its own callbacks and complain when one is slow. You turn it on with the environment variable
PYTHONASYNCIODEBUG=1, or withloop.set_debug(True), or by running Python with-X dev.The useful report is a log line like
Executing <Task ...> took 0.512 seconds. It appears whenever a step of a coroutine runs for longer thanloop.slow_callback_duration, which is 100 ms by default, and it names the coroutine and the place where it was created. That points you straight at the endpoint that blocked.It also reports other mistakes: a coroutine that was never awaited, and calls to non-thread-safe loop methods from the wrong thread.
The price is speed. Debug mode adds checks to every callback and keeps extra information, so the program can run noticeably slower. I use it in staging, in tests and on a developer's machine under realistic traffic. In production I use the cheap lag gauge instead.
- "How do I stop it from happening again?"
-
I use three layers: a review rule, a lint rule in CI, and a runtime alarm. Each catches what the one before misses.
- Review rule: no synchronous I/O libraries inside
async defcode. That meansrequests, sync database drivers,time.sleepand plain file reads of large files. Usehttpx.AsyncClientor an async driver, or put the call in adeffunction. - Lint in CI: ruff has ASYNC rules and flake8-async has similar checks. They flag blocking calls inside coroutines, so a pull request fails before it is merged.
- Runtime alarm: the event loop lag gauge, with an alert at about 50 ms, catches the blocking calls that hide inside a library.
The linter cannot see a blocking call that is two functions deep inside a third-party package, which is why the gauge stays. I also write a test that fires 50 concurrent requests and checks the total time, as the course demo does.
- Review rule: no synchronous I/O libraries inside
Q135 · Design. "Design observability for QuickBite: dashboards and alerts."
Reveal answer
Strong answer I design it from the questions an on-call engineer asks at 3 a.m., in order: "is it broken?", "who is affected?", "where?", "why?". Each question maps to a signal.
Is it broken? One top-level dashboard with the golden signals per service: request rate, error rate, p99 latency, saturation. Service level objectives drive the alerts: for example "99.5 percent of order creations succeed in under 1 second over 30 days", with burn-rate alerts that page when the error budget is being spent too fast.
Who and where? Break the same metrics down by route, by status and by dependency (payments, database, maps). Why? Click from a slow route to traces (OpenTelemetry), and from a trace to logs by request id. Logs are structured JSON with the request id, customer id and order id.
Business dashboards sit next to technical ones: orders per minute, payment failure rate, delivered orders versus placed. A drop in orders per minute with healthy technical metrics is itself an alert.
Picture it The alert list I would start with, each tied to a user-visible symptom and to what the responder does first.
| Alert | Condition | First action |
|---|---|---|
| Order creation errors | 5xx or 409 spikes above 2% for 5 min | open the route's traces, check payments and DB panels |
| Latency | p99 of POST /v1/orders above 1 s for 10 min | look for event loop lag and DB pool wait |
| Saturation | DB pool wait above 100 ms or readiness failing | check pool use, slow queries, replica lag |
| Queue age | oldest outbox row older than 5 min | check the worker, the relay and broker health |
| Business | orders per minute 50% below the same hour last week | check app releases, payment provider status |
Alert on causes
Noisy and late.
# ❌ TRAP: CPU alone pages people
alert: HighCPU
expr: cpu > 80
for: 1mAlert on symptoms
Tied to users.
alert: OrderErrorBudgetBurn
expr: error_ratio_1h > 14.4 * 0.005
for: 5m
# page: users are failing nowThe shift: Page on what customers feel; use causes as clues in the dashboard.
Land it Golden-signal dashboards per service, SLO burn-rate alerts on user-visible symptoms, traces linked to structured logs by request id, and business metrics next to technical ones.
- "What is an error budget?"
-
An error budget is the amount of failure that your objective allows, turned into a number you can spend. It changes the question from "is this bad?" to "how much of what we are allowed have we used?".
error budgetruns offlineSLO = 99.5% of order creations succeed over 30 days allowed failure = 0.5% 30 days = 30 x 24 = 720 hours budget in time = 0.005 x 720 = 3.6 hours of total failureA burn rate says how fast you spend it. A burn rate of 1 uses the budget exactly over the 30 days. A burn rate of 14.4 would use it in about 2 days.
A good alert pages on a high burn rate over a short window (for example 14.4 over one hour), and opens a ticket on a slow one (for example 1 over three days). A small blip then does not wake anyone, while a real outage does within minutes.
- "How do you avoid alert fatigue?"
-
I make every page earn its place, then I review the pages after the fact. Alert fatigue is a slow decay: each noisy alert teaches the on-call person that pages are usually nothing.
- Page only if it is urgent and actionable: a person must be able to do something now. Everything else is a ticket or a dashboard.
- Review every page: in the weekly review ask, did this need a human? If not, delete it or loosen the threshold. Track pages per on-call shift as a number.
- Group and link: group related alerts, for example the pool alert and the latency alert from one cause, into one notification, and attach a runbook link with the first three checks.
The target I use is no more than a few pages per shift, and almost all of them real. If the count is higher, the monitoring is the problem, not the system. Alerts based on symptoms users feel, such as error rate, produce far fewer false alarms than alerts on causes, such as CPU.
- "What do you log versus trace versus count?"
-
I choose by the question each signal answers, because using all three for everything is expensive.
Metrics are cheap numbers over time. I count what I want to graph and alert on: request rate, error rate, latency, pool use, orders per minute. They tell me that something is wrong and roughly where.
Traces show where the time went inside one request, across services. I look at a trace when a metric says the p99 of
POST /v1/ordersrose, and I need to know whether the time went to the database, to the payment call, or to the code. They are sampled, because storing all of them costs too much.Logs hold the details to reconstruct one incident: the request id, the customer and order ids, the decision taken, the error text. They are the most expensive per fact, so I log events and decisions, not every function call.
The flow on call is metric to trace to log, joined by the request id.
- "How do you prove the monitoring works?"
-
I rehearse failures on purpose, because an alert that has never fired is only a hope. A game day is a planned session where the team breaks something in staging and watches whether the monitoring does its job.
For QuickBite I would run three drills. Stop the payment stub, and check that the payment failure rate rises, the alert fires within its window, and the dashboard points at the payment dependency. Hold the database pool full with slow queries, and check that the pool wait alert fires before users see errors. Stop the outbox relay, and check that the "oldest unsent row" alert fires.
For each drill I write down four things: did the alert fire, how long after the fault, did the page link to a useful runbook, and could someone who did not build the system find the cause using only the dashboards and traces.
The gaps found become tickets. Repeat the drills every quarter, because the system and the team change.
These questions test whether you measure before you optimise, know the real costs inside a request, and can ship a small, safe, well-behaved container.
Q136. "Where does time go in a FastAPI request, and how do you profile it?"
Reveal answer
Strong answer A request passes through stages, and each has a typical cost. Server and parsing: uvicorn reads the bytes and parses HTTP (tiny with httptools). Middleware: each layer adds a little; pure ASGI middleware is cheap, BaseHTTPMiddleware costs more. Dependency resolution: FastAPI builds the arguments, and each dependency adds a call. Request validation: Pydantic (fast, in Rust). Your endpoint: usually dominated by the database and outbound calls. Response serialisation: validation and JSON encoding, which grows with the size of the response (Q137).
In most real services the database round trips are the largest slice, then outbound HTTP calls, then serialisation of big responses, and the framework overhead is small. That is why "FastAPI is slow" is rarely the true diagnosis.
Method: measure first. For latency by stage use traces (Q130) or a timing middleware that records Server-Timing. For CPU use a sampling profiler such as py-spy (attach to a running process, low overhead) or pyinstrument (neither is installed on the course machine, so the demo uses the standard cProfile). Look at cumulative time per function, then drill into the top one. Profile with realistic data sizes.
Picture it A menu endpoint with a 20 ms query and 2,000 rows, profiled with cProfile, keeping only the interesting lines.
import cProfile, io, pstats, time
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Item(BaseModel):
id: int; name: str; price_cents: int
app = FastAPI()
def slow_query(): time.sleep(0.02); return [{"id": i, "name": f"dish {i}", "price_cents": 100 + i} for i in range(2000)]
@app.get("/v1/menu", response_model=list[Item])
def menu(): return slow_query()
c = TestClient(app); c.get("/v1/menu")
pr = cProfile.Profile(); pr.enable(); c.get("/v1/menu"); pr.disable()
s = io.StringIO(); pstats.Stats(pr, stream=s).sort_stats("cumulative").print_stats(60)
keep = [l for l in s.getvalue().splitlines() if any(k in l for k in ("slow_query", "time.sleep", "serialize_response", "validate_python", "run_endpoint_function", "function calls"))]
print("\n".join(l.strip() for l in keep))Make the invisible visible: Real output (cut to the relevant functions).
3212 function calls (3146 primitive calls) in 0.043 seconds
1 0.001 0.001 0.022 0.022 /home/iam100god/Desktop/AI_COURSE/code/e20-python-api/E/profile_request.py:9(slow_query)
1 0.020 0.020 0.020 0.020 {built-in method time.sleep}
1 0.001 0.001 0.003 0.003 /home/iam100god/Desktop/AI_COURSE/.venv/lib/python3.12/site-packages/pydantic/type_adapter.py:398(validate_python)
1 0.003 0.003 0.003 0.003 {method 'validate_python' of 'pydantic_core._pydantic_core.SchemaValidator' objects}
4 0.000 0.000 0.002 0.000 /home/iam100god/Desktop/AI_COURSE/.venv/lib/python3.12/site-packages/fastapi/routing.py:301(serialize_response)
4 0.000 0.000 0.001 0.000 /home/iam100god/Desktop/AI_COURSE/.venv/lib/python3.12/site-packages/fastapi/routing.py:344(run_endpoint_function)What you see: Of 43 ms in the whole call, about 22 ms is slow_query, of which 20 ms is the time.sleep standing in for the database. Pydantic's validate_python for the 2,000-row response takes about 3 ms. The framework routing and dependency code barely shows up.
Guess and tune
Optimise what looks slow.
"Pydantic must be slow, let's switch
to dicts and orjson everywhere."
# ❌ no measurementMeasure then tune
Fix the biggest slice.
trace: db 22 ms | serialise 3 ms | rest 1 ms
=> add an index / fetch fewer rows first
=> serialisation is not the problemThe shift: The slowest-looking part is rarely the slowest part; let the numbers choose.
Land it I find the slow stage with traces or a timing middleware, profile CPU with a sampling profiler on realistic data, and fix the biggest slice first, usually the database.
- "How do I add a timing middleware cheaply?"
-
Write a pure ASGI middleware that times the call and adds a header. It is about fifteen lines, and the cost per request is two clock reads. Pure ASGI means it is a plain class that wraps the app, with no helper base class between you and the request.
timing_middleware.pyclass TimingMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): if scope["type"] != "http": return await self.app(scope, receive, send) start = time.perf_counter() async def send_with_timing(message): if message["type"] == "http.response.start": ms = (time.perf_counter() - start) * 1000 message.setdefault("headers", []).append( (b"server-timing", f"app;dur={ms:.1f}".encode())) await send(message) await self.app(scope, receive, send_with_timing)Browsers show the
Server-Timingheader in the network panel, so every response explains itself, and a developer can see "app took 12.3 ms" without opening any dashboard. The same number can feed a latency histogram, so the data is also in Prometheus. The header only reports time inside the app, so compare it with the total time the browser saw: the difference is the network and the proxy. Add it to the middleware stack once, withapp.add_middleware(TimingMiddleware).I use
perf_counterand nottime.time, because it is monotonic and cannot jump when the clock is adjusted. - "Is py-spy safe in production?"
-
Yes, it is one of the safer profilers for a live service, with two conditions I check first.
py-spy is a sampling profiler that runs as a separate process. About 100 times a second it reads the target's memory to see which function each thread is in, and builds a picture of where time goes. It does not inject code and does not stop the target for long, so the slowdown is small, and you do not restart the service to use it.
The conditions are permissions and scope. Reading another process needs the ptrace permission, which in a container means adding the
SYS_PTRACEcapability, and many security policies forbid that in production. Run it on a staging pod, or on one canary pod with the capability added for the session.The workflow I use is
py-spy record -d 30 -p PID -o profile.svgon a busy worker, then read the flame graph from the widest bar down. Thirty seconds of real traffic usually names the hot function.py-spy dumpprints the current stacks, which helps with a hang. - "What about N+1 queries?"
-
An N+1 problem is the classic hidden cost, because it looks innocent in the code and appears in the profile as "database time" with no single slow query.
It happens when you load a list with one query and then touch a related object for each row, and the ORM issues one more query per row. For 50 orders that is 1 plus 50 equals 51 statements. Each statement takes only a millisecond, so no query looks slow, but 51 round trips add up, and the total grows with the page size.
The fix for detection is to count statements per request. With a SQLAlchemy event listener on
before_cursor_execute, increment a counter stored in a ContextVar, and log it or export it with the request. Then an endpoint that normally issues 2 statements and suddenly issues 51 stands out on a graph.In the course app, listing 50 orders went from 51 statements to 2 with
selectinload, and to 1 withjoinedload. I also add a test that asserts the statement count for key routes, so the problem cannot come back unnoticed. - "What do I look at after the first fix?"
-
I measure again, because after the largest slice shrinks, the order changes, and the next biggest slice is now the target.
Suppose a request took 400 ms: 260 ms in database round trips, 80 ms calling the payment service, 40 ms serialising the response, 20 ms elsewhere. Fixing the N+1 problem might cut the database part from 260 to 40 ms. The total is now 180 ms, and the payment call at 80 ms is the largest slice. If the objective is 250 ms at the 99th percentile, I may already be done.
That is the stopping rule: meet the latency objective at the target load, with some margin, and then stop. Beyond that point each further improvement costs readability and time, and users cannot feel it.
Two precautions. Re-measure under realistic data sizes and concurrency, since a fix that helps with 10 rows can matter little with 10,000. And keep the before and after numbers in the pull request, so the next person knows what the change achieved.
Q137 · Scenario. "Serialising large responses dominates CPU time. Fix it."
Reveal answer
The real test Whether you let FastAPI serialise once through Pydantic with a declared return type, and whether you avoid the double work and the oversized response, not whether you name a faster JSON library.
Strong answer Think about the work per item. A response model validates each object and then writes JSON. Doing that for 5,000 items costs real CPU, and doing it twice (validate to a model, dump to a dict, then encode with another library) costs more. The three ways to make it cheaper, in order of impact:
- Return less: paginate (cursor), select only needed columns, drop fields clients never use. Halving the data halves the cost, and also the network and client time.
- Serialise once: declare the return type or
response_modeland return the data. As of FastAPI 0.141, when a response model or return annotation is present FastAPI serialises to JSON bytes through Pydantic's Rust core in one step. Do not first callmodel_dump()and wrap the dicts inJSONResponse; that is the slowest path in the measurement below. - Skip the validation when you already trust the data: return a ready-made
Response(content=TypeAdapter(...).dump_json(items)), which bypasses the response model entirely. It is the fastest but gives up filtering and OpenAPI-enforced shape, so keep it for hot read paths with already-validated data.
One more note for 0.141: ORJSONResponse is deprecated, because the Pydantic path above replaced its reason for existing. Choosing it gives a warning, and with a declared response type it was slower than the default in my measurement. The orjson library remains useful elsewhere, for example encoding cache entries or queue messages outside FastAPI's response path.
Picture it A 5,000-item list through four routes. Items have four fields, one of them a list.
import json, timeit, warnings
warnings.simplefilter("ignore")
from fastapi import FastAPI
from fastapi.responses import JSONResponse, Response
from fastapi.testclient import TestClient
from pydantic import BaseModel, TypeAdapter
class Item(BaseModel):
id: int; name: str; price_cents: int; tags: list[str]
rows = [{"id": i, "name": f"dish {i}", "price_cents": 100 + i, "tags": ["veg", "spicy"]} for i in range(5000)]
objs = [Item(**r) for r in rows]
app = FastAPI()
@app.get("/typed", response_model=list[Item]) # FastAPI validates + serialises to JSON bytes in Rust
def typed(): return rows
@app.get("/typed-instances")
def typed_inst() -> list[Item]: return objs
@app.get("/dump-json") # model_dump -> JSONResponse: dicts, then stdlib json
def dump(): return JSONResponse([o.model_dump() for o in objs])
@app.get("/raw-bytes") # one Rust call, bypasses response_model entirely
def raw(): return Response(TypeAdapter(list[Item]).dump_json(objs), media_type="application/json")
c = TestClient(app)
for p in ("/typed", "/typed-instances", "/dump-json", "/raw-bytes"):
c.get(p); t = min(timeit.repeat(lambda: c.get(p), number=1, repeat=7)) * 1000
print(f"{p:18} {t:6.1f} ms ({len(c.get(p).content)//1024} KiB)")Make the invisible visible: Real output, best of seven (course machine; includes the test client's overhead, so read the ratios, not the digits).
/typed 16.9 ms (353 KiB)
/typed-instances 11.0 ms (353 KiB)
/dump-json 22.0 ms (353 KiB)
/raw-bytes 6.7 ms (353 KiB)What you see: Returning model instances with a return annotation took 11.0 ms. response_model over plain dicts, which must be validated first, took 16.9 ms. The model_dump() plus JSONResponse path took 22.0 ms, twice the best, for identical bytes. A raw dump_json response took 6.7 ms. Section 07's measurement on the same version gave the same ordering.
Dump then encode
Two conversions, one slow encoder.
@router.get("/menu")
def menu():
items = repo.all() # models
# ❌ dicts, then stdlib json
return JSONResponse(
[i.model_dump() for i in items])Declared return type
One pass in Rust.
@router.get("/menu")
def menu() -> list[ItemOut]:
return repo.all(limit=100)
# ✅ validated and encoded once,
# and capped by paginationThe shift: Serialise once, as late as possible, and send fewer items.
Land it I cut the response size first, then declare a return type so FastAPI validates and encodes once through Pydantic, and I reserve raw dump_json for proven hot paths; ORJSONResponse is deprecated as of 0.141.
- "Should I turn off
response_modelvalidation to save CPU?" -
Not by default. The response model does two jobs at once: it filters fields and it enforces the contract, and the CPU saving is smaller than people expect when you return the right thing.
The filtering is a security feature. If your database model has
password_hashor an internal note, the response model with only the public fields is what stops them reaching the client by accident. That mistake is silent and serious, and the response model prevents it for every route.On cost, the measurement in the section is the guide: returning model instances with a declared response type took about 11 ms for the large list, because FastAPI serialises to JSON bytes in one step through Pydantic. The slow path was building dicts first and then validating them. So the first optimisation is to avoid that double work, not to remove the model.
I skip the response model only on a hot route that I have measured, whose data is already validated, and where the saving is worth losing the filter. In that case I return a ready
Responsebuilt withTypeAdapter(...).dump_json, and I add a test that checks the output shape. - "What about compression?"
-
I compress at the edge, not inside the application, for large JSON responses. Compression is worth doing, since JSON is repetitive and often shrinks by 80 percent or more, and the question is only where the CPU cost is paid.
The gateway, the load balancer or the CDN is built for this. It compresses with optimised code, it can cache compressed copies for identical responses, and it keeps the CPU of your Python pods free for the work only they can do.
Inside FastAPI,
GZipMiddlewareworks, but it has costs. It needs the whole response body, or buffers chunks, so it fights with streaming responses such as Server-Sent Events, where each chunk should reach the client at once. It also compresses on the same event loop thread that serves other requests.If you have no gateway at all, then use
GZipMiddlewarewithminimum_sizeset to about 1,000 bytes so tiny responses are not compressed, and keep streaming routes out of it. Brotli gives smaller files than gzip but compresses more slowly, so it suits cached static content more than dynamic JSON. - "How big should a page be?"
-
I set a default of 20 items, and a hard maximum of 100, enforced by the validation on the
limitparameter. A client that asks for 10,000 gets a 422 error, not a slow server.Two forces choose the number. The first is size on the wire: 100 orders with lines might be 100 KB uncompressed. A mobile client on a poor connection feels anything over a few hundred kilobytes, no matter how fast the server is. The second is work on the server: validating and encoding 100 items is a fraction of a millisecond each, but 5,000 items is the case that dominated CPU in this chapter.
page limitslimit: Annotated[int, Query(ge=1, le=100)] = 20If a client really needs everything, for example an accounting export, do not raise the page limit. Offer an export job that runs in a worker and writes a file to object storage, as in the course's Q105, and let the client download that. A single huge GET holds a worker, a connection and memory for the whole time.
- "Are there faster formats?"
-
Yes, binary formats are smaller and faster to parse, and I use them where their cost is worth it. Still, for a public API I keep JSON.
MessagePack is "JSON in binary", often 20 to 40 percent smaller, and parses faster. Protocol Buffers are smaller still and come with a schema that generates typed clients, which is why gRPC uses them. The costs are real. A browser cannot show them in the network panel, a developer cannot read them with
curl, tooling is thinner, and every client needs a library.JSON compressed at the edge gets much of the size benefit already. Gzipped JSON is often within a factor of two of Protobuf, and every language and tool understands it.
My rule is the following. Public and partner APIs: JSON, compressed, with a stable schema. Internal service-to-service calls on a hot path, between teams that share tooling: consider gRPC, and measure the gain before the migration, not after.
Q138. "Async database driver versus sync driver in the threadpool — the measured trade-offs."
Reveal answer
Strong answer A sync driver (psycopg in a plain def endpoint) blocks a thread while waiting on the database. FastAPI gives each such request one of 40 threads, so up to 40 queries can be in flight per worker. An async driver (asyncpg, psycopg's async mode, aiosqlite) yields to the event loop while waiting, so thousands of waits cost almost nothing.
What matters is how many requests wait at the same time. If a request spends 50 ms waiting on a remote database, 40 threads give about 800 requests per second per worker, which is more than most services need. If waits are long (slow queries, many external calls per request) or concurrency is high (thousands of idle WebSockets, fan-out of several calls per request), threads run out and async wins.
The costs of async: every library in the path must be async, lazy loading breaks (MissingGreenlet, Q59), traces are harder to read, and one blocking call anywhere stalls the loop (Q134). The costs of sync: memory per thread, the 40-thread ceiling, context switches.
So the choice is about your workload, not fashion, and it must be measured. The demo shows the part people forget: on a local database there is no network wait for async to hide.
Picture it 400 trivial queries on a local SQLite file, with a sync driver in a 40-thread pool and with the async driver aiosqlite.
import asyncio, sqlite3, time
from sqlalchemy import create_engine, text
from sqlalchemy.ext.asyncio import create_async_engine
from concurrent.futures import ThreadPoolExecutor
N = 400
sync_e = create_engine("sqlite:///./drv.db", pool_size=20, max_overflow=0)
async_e = create_async_engine("sqlite+aiosqlite:///./drv.db", pool_size=20, max_overflow=0)
with sync_e.begin() as c: c.execute(text("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, v TEXT)")); c.execute(text("DELETE FROM t")); c.execute(text("INSERT INTO t (v) VALUES ('x')"))
def sync_query():
with sync_e.connect() as c: return c.execute(text("SELECT v FROM t")).scalar()
async def async_query():
async with async_e.connect() as c: return (await c.execute(text("SELECT v FROM t"))).scalar()
async def run_sync_in_threads():
loop = asyncio.get_running_loop()
with ThreadPoolExecutor(40) as ex: await asyncio.gather(*(loop.run_in_executor(ex, sync_query) for _ in range(N)))
async def run_async():
await asyncio.gather(*(async_query() for _ in range(N)))
for label, fn in (("sync driver in 40-thread pool", run_sync_in_threads), ("async driver (aiosqlite)", run_async)):
t = time.perf_counter(); asyncio.run(fn()); print(f"{label:32} {N} queries in {(time.perf_counter()-t)*1000:6.0f} ms")
print("note: SQLite is local and aiosqlite itself uses a thread per connection, so this shows overhead, not network wait")Make the invisible visible: Real output (course machine).
sync driver in 40-thread pool 400 queries in 97 ms
async driver (aiosqlite) 400 queries in 228 ms
note: SQLite is local and aiosqlite itself uses a thread per connection, so this shows overhead, not network waitWhat you see: The sync driver with threads finished 400 queries in 97 ms, the async driver in 228 ms. SQLite is local and fast, and aiosqlite itself runs each connection in a thread, so async adds scheduling overhead and hides no waiting. With a networked PostgreSQL and 20 ms per query the picture changes: waiting dominates, and the async side is limited by the pool, not by threads.
Sync in a thread
Simple, 40 at a time.
@router.get("/orders")
def list_orders(s: Session = Depends(get_session)):
return s.scalars(select(Order)).all()Async driver
Thousands of waits, stricter rules.
@router.get("/orders")
async def list_orders(
s: AsyncSession = Depends(get_session)):
r = await s.scalars(select(Order))
return r.all()The shift: Async buys cheap waiting; it costs you the rule that nothing in the path may block or lazy-load.
Land it I default to sync endpoints with SQLAlchemy for simplicity and move to async drivers when measured concurrency of waiting requests exceeds the thread pool, accepting the stricter rules.
- "Does async make each query faster?"
-
No. A query takes as long as the database takes to run it, and the driver style does not change that. Async changes what the web server does while it waits for the answer.
With a sync driver in a plain
defendpoint, a thread is held for the whole wait: if a query takes 50 ms, that thread sits idle for 50 ms. With an async driver, the coroutine reachesawait, the event loop runs other requests during those 50 ms, and returns when the data arrives. The request itself still takes 50 ms plus overhead.So the benefit is throughput under high concurrency, not latency for one request. If your service handles 20 requests at a time, 40 threads cope easily, and async gives you nothing visible. If it handles 5,000 waiting requests at a time, such as long-polling or many calls to slow services per request, threads run out and async lets the server keep up.
In the course demo, with a local database and almost no wait, the async version was not faster, since there was no waiting to hide. Async pays only when there is something to wait for.
- "How many connections do async apps need?"
-
The same as a sync app needs for the same query rate. Async lets many requests wait at once, but a query still needs its own database connection while it runs, and the number of connections is set by the pool, not by the number of requests.
Picture 5,000 requests waiting at the same moment, with a pool of 10 connections. Only 10 queries run at once. The other requests wait in the pool queue for a free connection, and if the wait passes the pool timeout (30 s by default in SQLAlchemy, 1 s in the course test), they fail with a timeout error. Async did not remove the limit. It moved the waiting from threads to the pool queue, where waiting is cheap, but latency still grows.
So I size the pool from the number of queries in flight at once, using Little's law: queries per second times the average time a connection is held. Then I check the total across pods against the database's
max_connections(Q143).Async makes it easier to build too many waiting requests, which is why pool wait time deserves its own alert.
- "Can I mix sync and async in one app?"
-
Yes, and many real systems do. The rule is to keep the two styles apart, so that no sync call ever runs on the event loop.
A common layout is one async engine for the hot, high-concurrency routes, for example the public order endpoints, and one sync engine for admin tools, reports and migrations, where simplicity matters more than concurrency. Each engine has its own pool with its own size, which you add up when you budget connections.
Two mistakes to avoid. First, never call a sync session inside an
async defendpoint: it blocks the loop for the whole query, which is the failure from Q134. If you must call sync code from async code, wrap it inawait run_in_threadpool(...). Second, do not share a session between the two worlds. A session belongs to one engine and one kind of code.Mixing has a maintenance cost, since developers must know which route uses which style. I do it only when measurement shows a hot path that justifies the second style, and I document it in the repository.
- "What benchmark would convince you?"
-
The benchmark must reproduce the part that async is supposed to help: many requests waiting on a real database over a real network. A local test cannot show that, so it can only show overhead.
- Same route twice: implement one route with the sync driver in a
defendpoint and one with the async driver, with the same query, the same pool size and the same response model. - Real conditions: run in staging against a database with production-sized data, on a network path like production, so the 5 to 50 ms of round-trip wait is real.
- Steady load at several concurrency levels: for example 20, 100 and 500 at once, for several minutes each, and record throughput, p50 and p99 latency, CPU and memory.
I would be convinced if async wins clearly at the concurrency I expect, for example 30 percent more throughput at 500 at once, and does not lose at low concurrency. If the lines are the same at my real load, I keep the simpler sync version.
- Same route twice: implement one route with the sync driver in a
Q139. "Write the Dockerfile for a FastAPI app with uv: multi-stage, non-root, small."
Reveal answer
Strong answer The goals are: reproducible dependencies, a small final image, no build tools or package managers in it, and a process that runs as an unprivileged user and stops cleanly.
- Builder stage: a Python image with
uvcopied in. Copy onlypyproject.tomlanduv.lockfirst and runuv sync --frozen --no-dev --no-install-project, so the dependency layer is cached until the lock file changes. Then copy the app. - Runtime stage: a slim Python image, copy the finished virtual environment and the app from the builder, create a system user and switch to it with
USER. - Command:
CMD ["uvicorn", "app.main:create_app", "--factory", ...]in exec form (a JSON array), so uvicorn is PID 1 and receives SIGTERM directly. Set--timeout-graceful-shutdown. - Hygiene: a
.dockerignore(no.git, tests, caches,.venv),PYTHONUNBUFFERED=1so logs appear at once, no secrets in layers, and a pinned base image tag (or digest).
The canonical file below was built in section 07: the image is 289 MB, runs as uid 10001, and docker stop returned in 0.54 seconds because uvicorn handled SIGTERM as PID 1. I checked the uvicorn flags with uvicorn --help: --factory, --timeout-graceful-shutdown, --workers, --proxy-headers and --limit-max-requests all exist in 0.53.
Picture it The complete Dockerfile of the canonical app, copied from code/e20-python-api/quickbite_api/Dockerfile (not rebuilt by this section; the build and its measurements are in section 07).
# syntax=docker/dockerfile:1
# ---- builder: resolve and install dependencies with uv, from the lock file ----
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:0.11 /uv /usr/local/bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
WORKDIR /srv
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project # cached layer: only changes with the lock file
COPY app ./app
# ---- runtime: no uv, no build tools, non-root ----
FROM python:3.12-slim AS runtime
ENV PATH="/srv/.venv/bin:$PATH" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
RUN useradd --system --uid 10001 --no-create-home quickbite
WORKDIR /srv
COPY --from=builder /srv/.venv ./.venv
COPY --from=builder /srv/app ./app
USER quickbite
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=3s CMD python -c "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/healthz')"
CMD ["uvicorn", "app.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--timeout-graceful-shutdown", "20"]Single stage as root
Big, slow to rebuild, risky.
FROM python:3.12
COPY . .
RUN pip install -r requirements.txt
# ❌ build tools in the image, runs as root
CMD uvicorn app.main:appMulti-stage with uv
Small, cached, non-root.
FROM python:3.12-slim AS builder
RUN uv sync --frozen --no-dev
FROM python:3.12-slim
COPY --from=builder /srv/.venv /srv/.venv
USER quickbite
CMD ["uvicorn", "app.main:create_app", "--factory"]The shift: Build in one image and ship another that holds only what runs.
Land it A two-stage build with uv and a locked dependency layer, a slim runtime image, a non-root user, and an exec-form uvicorn command so SIGTERM reaches the server.
- "Why exec form for CMD?"
-
The shell form hides the signal from your program, and a clean shutdown depends on that signal. There are two ways to write
CMDin a Dockerfile, and they behave differently.The shell form,
CMD uvicorn app.main:app, makes Docker run/bin/sh -c "uvicorn ...". The shell becomes PID 1, and uvicorn is its child. When Kubernetes ordocker stopsends SIGTERM to PID 1, the shell does not pass it on to its child. Uvicorn never learns that it should stop. After the grace period, 30 seconds in Kubernetes and 10 seconds fordocker stop, SIGKILL arrives, and in-flight requests are cut off. Every deploy then takes the full wait.The exec form,
CMD ["uvicorn", "app.main:create_app", "--factory"], runs uvicorn directly as PID 1. It receives SIGTERM, starts its graceful shutdown, and exits. In the course test,docker stopreturned in 0.54 seconds for exactly this reason.One note: a shell script as entrypoint should end with
exec uvicorn ..., which replaces the shell. - "Why slim and not alpine?"
-
Because slim images use glibc, which is the C library that most Python binary wheels are built for, and Alpine uses musl, which is different. A package that ships a ready-made wheel for glibc may have no musl wheel, and then pip falls back to compiling it from source.
The problems this causes are practical. Packages with C code, such as
psycopg[binary],cryptography,orjsonandnumpy, can have slow builds of several minutes, need a compiler inside the image, and sometimes fail. Subtle differences in musl, such as DNS or memory-allocator behaviour, have also caused hard-to-find slowdowns for some Python workloads.The size win is also smaller than it looks. A
python:3.12-slimbase is around 120 MB. The final image in the course was 289 MB, mostly dependencies, which Alpine does not shrink.If you want something smaller and safer, use a distroless Python image, which has no shell and no package manager. You lose the ability to open a shell in the container, so debug through logs, or use an ephemeral debug container.
- "How do I keep builds fast in CI?"
-
The idea is to order the Dockerfile so that the slowest steps run least often. Docker caches each layer, and one changed layer rebuilds everything after it.
- Dependencies first: copy only
pyproject.tomlanduv.lock, runuv sync --frozen --no-dev --no-install-project, and only then copy the source. A code-only change leaves the dependency layer cached, so the rebuild takes seconds. - Cache mounts: with BuildKit,
RUN --mount=type=cache,target=/root/.cache/uvkeeps uv's download cache between builds, so even a changed lock file re-downloads only the new packages. - Registry cache: in CI, where the machine starts empty, use
--cache-fromand--cache-toto store layers in the registry.
Add a
.dockerignorethat excludes.git, caches and tests, so a change in those files does not invalidate the copy step. I measure the time of a no-change build, a code-only build and a dependency build, and expect about 5, 15 and 90 seconds respectively as a rough shape. - Dependencies first: copy only
- "How many workers in the container?"
-
One or two per pod is my default, and I scale by adding pods. A pod is the unit Kubernetes schedules, restarts and measures, so making it small and uniform makes capacity easier to reason about.
Each worker is a full process. It has its own imports, its own database pool and its own memory. With four workers and a pool of 5 plus 5 overflow, one pod can open up to 40 connections, and 20 such pods ask for 800. The same capacity from one worker per pod and 80 pods asks for 800 in total too, but each pod can be sized and restarted on its own, and metrics and memory limits are per pod and simple to read.
Workers do have a use. If a pod gets a whole core or more of CPU, one async worker uses one core at most, so a pod with 2 CPUs benefits from 2 workers. The rule I follow is one worker per CPU the pod really has, limited to a small number.
Then I measure: load test one pod with 1, 2 and 4 workers, and keep the smallest count that meets the target.
Q140 · Scenario. "The container takes 40 seconds to become ready and Kubernetes keeps killing it. Fix it."
Reveal answer
The real test Whether you first measure where start-up time goes, then fix the cause and the probes, instead of only raising the probe timeout.
Strong answer There are two parts. Why is start-up slow? and why is Kubernetes killing a pod that is merely slow? Answer both.
Start-up time is usually imports, work done at import time or in the lifespan, or waiting for a dependency. Measure it with python -X importtime -c "import app.main" and with timestamps in the lifespan. Typical causes: heavy imports (a machine learning library imported at module level), creating a database engine and running create_all or migrations at start, loading large files, waiting for DNS or a database that is not up yet, and a cold file system pulling the image.
Fix by lazy-importing rarely used heavy modules, moving migrations to a separate job (Q69), warming caches in the background after readiness, and making the image smaller.
Kubernetes kills the pod because the liveness probe starts too early and fails while the app is still booting. The answer is a startup probe that tolerates a long start (for example 30 failures every 2 seconds), with liveness and readiness beginning only after it succeeds. Raising liveness delays is the wrong fix, because it also delays detection of a real deadlock later.
Picture it First measure. How long does importing the canonical app take on this machine, and which imports cost most?
import subprocess, sys, time
code = "import time; t=time.perf_counter(); import app.main; print(f'import app.main: {(time.perf_counter()-t)*1000:.0f} ms')"
subprocess.run([sys.executable, "-c", code], cwd="/home/iam100god/Desktop/AI_COURSE/code/e20-python-api/quickbite_api")
r = subprocess.run([sys.executable, "-X", "importtime", "-c", "import app.main"], cwd="/home/iam100god/Desktop/AI_COURSE/code/e20-python-api/quickbite_api", capture_output=True, text=True)
rows = []
for line in r.stderr.splitlines()[1:]:
parts = line.split("|")
if len(parts) == 3 and parts[1].strip().isdigit(): rows.append((int(parts[1]), parts[2].strip()))
print("slowest top-level imports (cumulative microseconds):")
for us, name in sorted(rows, reverse=True)[:5]: print(f" {us/1000:7.0f} ms {name}")Make the invisible visible: Real output.
import app.main: 577 ms
slowest top-level imports (cumulative microseconds):
583 ms app.main
267 ms fastapi
264 ms fastapi.applications
251 ms fastapi.routing
170 ms fastapi.paramsWhat you see: Importing the app takes about 0.6 seconds here, mostly FastAPI itself (about 270 ms). So a 40-second start in the story is not Python imports; it is something done at start-up (a migration, a slow dependency, a large model). The measurement says where to look before any fix. Now the probe configuration.
# illustrative
startupProbe:
httpGet: {path: /healthz, port: 8000}
periodSeconds: 2
failureThreshold: 30 # up to 60 s to start
livenessProbe:
httpGet: {path: /healthz, port: 8000}
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet: {path: /readyz, port: 8000}
periodSeconds: 5Why: The startup probe holds liveness and readiness back until the app answers for the first time, up to a minute. After that liveness reacts within about 30 seconds to a real hang. A pod that takes 40 seconds to start is accepted, and traffic arrives only when /readyz says yes.
Liveness from second one
Boot looks like death.
livenessProbe:
httpGet: {path: /healthz, port: 8000}
initialDelaySeconds: 5
failureThreshold: 3 # ❌ dead at 20 sStartup probe first
Patience, then vigilance.
startupProbe:
httpGet: {path: /healthz, port: 8000}
periodSeconds: 2
failureThreshold: 30
# liveness starts after it passesThe shift: Give start-up its own generous clock, and keep the strict one for later.
Land it I measure what the 40 seconds are spent on and cut it, and I add a startup probe so liveness only judges a pod that has finished booting.
- "Should migrations run at start-up?"
-
No, do not run migrations in every replica at start-up. They are a one-time change to shared state, and an app container is started many times.
Suppose a rollout starts ten new pods. All ten run the migration at the same moment. At best, the migration tool takes a lock and nine pods wait, so readiness is slower. At worst, some migrations are not safe to run concurrently, and you get duplicate-object errors, or a half-applied change. A failing migration also puts every new pod into a crash loop, while the old pods keep running, so the rollout stalls.
The better pattern is to run migrations as a separate step before the rollout: a Kubernetes Job, a Helm pre-upgrade hook, or an init step run once by the pipeline. It runs once, fails once, and the pipeline stops before any app pod changes.
This only works if migrations are backward compatible, since old pods keep running against the new schema during the rollout (Q144). The app then starts quickly and predictably.
- "What if the app must load a large model or file?"
-
I separate the two questions: how long loading takes, and when traffic should arrive. Probes handle the second, and some design handles the first.
The simplest option is to bake the model or file into the image at build time, so start-up only reads it from the local disk. That makes the image larger, but removes a network download from every start.
If it must be loaded at run time, start the server first and load the file in the background, for example in a task started from the lifespan. Until loading is finished,
/readyzanswers 503. The startup probe gives the pod enough time to get there, and readiness keeps traffic away until it is truly able to serve.Think about workers too. With four uvicorn workers in a pod, each loads its own copy, so a 1 GB model needs 4 GB of memory. Either use one worker per pod, or load the model before forking so that the workers share the pages through copy-on-write, and check with a measurement that the sharing holds in practice.
- "Is raising
initialDelaySecondsenough?" -
No, it is a guess, and a guess that goes stale.
initialDelaySecondstells Kubernetes to wait a fixed time before the first liveness check. If the app takes 40 seconds to start and you set 45, it works today.The problems come later. A new dependency makes start-up take 50 seconds, and the pod is killed again. If you set 120 seconds to be safe, then a pod that really deadlocks in its first two minutes is not detected, and every start waits at least that long to be judged.
A startup probe answers the question directly. It checks every 2 seconds, with a failure threshold of 30, so the app has up to 60 seconds, and the moment the probe passes, liveness and readiness take over. A start that takes 12 seconds is ready after 12 seconds. A start that takes 55 seconds still works. Only a start that takes more than 60 seconds is killed.
So I keep the delay at zero and let a startup probe cover the range. I then review its limit whenever the measured start-up time changes.
- "How do I see why a pod was killed?"
-
Start with
kubectl describe pod, because the events and the last state tell most of the story, and use the logs of the dead container for the rest.- Events: look for lines such as
Liveness probe failedorStartup probe failed, which show that the kubelet killed it for failing a check. - Last state: it lists the reason and the exit code. Code 137 means the process received SIGKILL, and together with
OOMKilledit points to memory (Q132). Code 143 means SIGTERM, an orderly stop. Code 1 or 3 usually means the app crashed on start-up, such as a bad setting. - Previous logs:
kubectl logs POD --previousshows the output of the container that died. The current container may have just started, with nothing in its log.
If the pod restarts in a loop,
kubectl get pod -wshows the restart count and the back-off. Matching the time of the kill to the time of the probe failures usually answers whether the app was slow or really broken. - Events: look for lines such as
Q141. "Graceful shutdown: what happens to in-flight requests on SIGTERM?"
Reveal answer
Strong answer On a deploy or a scale-down, Kubernetes sends SIGTERM to the container, waits terminationGracePeriodSeconds (default 30), and then sends SIGKILL. In between, uvicorn does an orderly shutdown: it stops accepting new connections, lets in-flight requests finish and waits for background tasks, then runs the lifespan shutdown (closing the engine and clients) and exits with code 143.
The limit is --timeout-graceful-shutdown N. When N seconds pass and work is still running, uvicorn cancels the remaining tasks: the in-flight requests fail with 500 and background tasks stop (Q127). So set N to a little more than your longest normal request, and keep it below the pod's grace period, or Kubernetes kills the process first.
There is a race to handle on the Kubernetes side. Removing the pod from the Service endpoints and sending SIGTERM happen at the same time, and the load balancer may keep sending traffic for a second or two. The usual fix is a preStop hook that sleeps 5 seconds (or a readiness flip on SIGTERM), so traffic stops before the server closes its listening socket.
Also: run uvicorn as PID 1 in exec form (Q139), otherwise it never sees the signal.
Picture it The real experiment: a request that takes 3 seconds and a background task of 3 seconds, SIGTERM after half a second, with two window sizes. (Script from section 07: code/e20-python-api/C/sigterm_experiment.sh.)
[t=0] POST /orders-broken
[t=0] POST /orders (response now, email task takes 3 s)
[t=0.5] SIGTERM
{"done":true} <- /slow finished with HTTP 200
uvicorn exit code 143
INFO: Shutting down
INFO: Waiting for connections to close. (CTRL+C to force quit)
INFO: Waiting for background tasks to complete. (CTRL+C to force quit)
email for order 1 sent
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [269407][t=0] POST /orders-broken
[t=0] POST /orders (response now, email task takes 3 s)
[t=0.5] SIGTERM
Internal Server Error <- /slow finished with HTTP 500
uvicorn exit code 143
INFO: Shutting down
INFO: Waiting for connections to close. (CTRL+C to force quit)
ERROR: Cancel 2 running task(s), timeout graceful shutdown exceeded
INFO: Waiting for application shutdown.
asyncio.exceptions.CancelledError: Task cancelled, timeout graceful shutdown exceeded
asyncio.exceptions.CancelledError: Task cancelled, timeout graceful shutdown exceeded
INFO: 127.0.0.1:37876 - "GET /slow HTTP/1.1" 500 Internal Server Error
INFO: Application shutdown complete.What you see: With a 10-second window uvicorn logged Waiting for connections to close and Waiting for background tasks to complete, the slow request returned 200 and the email was sent, and the process exited 143. With a 1-second window it logged Cancel 2 running task(s), timeout graceful shutdown exceeded and the in-flight request came back as 500.
# illustrative: a rollout with preStop
t=0 pod marked terminating; endpoints update begins
t=0 preStop: sleep 5 (traffic still arrives)
t=5 SIGTERM -> uvicorn stops accepting, drains
t=5..25 in-flight requests and tasks finish (grace 20 s)
t=25 lifespan shutdown: engine.dispose(), exit 143
t=30 terminationGracePeriodSeconds reached -> SIGKILL if still aliveNo drain
Requests cut mid-flight.
# ❌ default sleep-less rollout,
# no uvicorn timeout, shell-form CMD
terminationGracePeriodSeconds: 30Drain on purpose
Quiet rollouts.
lifecycle:
preStop: {exec: {command: ["sleep","5"]}}
terminationGracePeriodSeconds: 30
# uvicorn --timeout-graceful-shutdown 20The shift: Plan the order: stop sending, then stop accepting, then finish, then exit, all inside the grace period.
Land it On SIGTERM uvicorn stops accepting and drains in-flight work for up to the graceful-shutdown timeout, so I keep that timeout below the pod grace period and add a preStop sleep so traffic stops first.
- "How should the numbers relate?"
-
The rule is that the sum of the waits must fit inside the grace period, with a margin. Kubernetes counts its grace period from the moment it starts stopping the pod, and the preStop hook uses part of it.
shutdown budgetruns offlineterminationGracePeriodSeconds = 30 preStop sleep = 5 (traffic drains away) uvicorn --timeout-graceful-shutdown = 20 (in-flight work finishes) 5 + 20 = 25 s < 30 s (5 s margin for lifespan shutdown)The sequence is: preStop sleeps 5 seconds while the endpoint removal spreads, then SIGTERM goes to uvicorn, which has up to 20 seconds to finish requests and close the engine. If the total went above 30, Kubernetes would send SIGKILL in the middle of the drain, and the whole point would be lost.
The canonical Dockerfile sets 20 for uvicorn, which fits this budget. If your longest normal request is 40 seconds, raise the grace period to about 55 and uvicorn's value to 45, and accept that rollouts take longer.
- "What about long WebSocket or SSE connections?"
-
They never finish by themselves, so the shutdown window cuts them. After
--timeout-graceful-shutdownseconds uvicorn closes them, and every client gets a dropped connection at the same moment.The dropped connections are only a problem if clients react badly, so there are two things to do. On the server, at the start of the shutdown, send a close frame (WebSocket code 1001, "going away") or a "reconnect" event on the stream. The client then knows this is planned and can connect to another pod at once, instead of waiting for a timeout to notice.
On the client, reconnect with exponential backoff and jitter: wait a random time, for example between 0 and 2 seconds, doubling after each failure. Without jitter, 10,000 clients of a stopped pod reconnect at the same instant and flatten the other pods, a reconnect stampede.
For rolling deploys, I also keep the pod's readiness failing, so that new connections go to other pods while old ones are being closed.
- "What does Gunicorn change?"
-
Gunicorn adds a supervisor process between Kubernetes and the workers, and with it a second set of names for the same ideas. In the old pattern, Gunicorn runs the uvicorn worker class and manages several workers.
SIGTERM goes to the Gunicorn master. It tells each worker to stop, and then waits
graceful_timeoutseconds (30 by default) before killing any that are left. Inside each worker, uvicorn still does its own drain. So you now have two timeouts to keep in order: uvicorn's own window should be smaller than Gunicorn'sgraceful_timeout, which should be smaller than the pod's grace period.One more change: the class
uvicorn.workers.UvicornWorkeris deprecated in current uvicorn, and the maintained version is the separateuvicorn-workerpackage.In Kubernetes the pod is already your process manager and restarts crashed containers, so a second manager has little to add. I run uvicorn directly, one process per container, and scale with pods (Q5). I would use Gunicorn only on plain virtual machines, where nothing else restarts the process.
- "How do I test graceful shutdown?"
-
Write a test that does what a deploy does: start the server, begin a slow request, send SIGTERM, and check that the request still completes and that the exit code is 143.
- Start: launch uvicorn as a subprocess with a test route that sleeps for 3 seconds, and wait until the port answers.
- Begin a slow request: start the call in a thread or an async task, and wait a moment so the server has accepted it.
- Send SIGTERM:
proc.send_signal(signal.SIGTERM), then collect the response and the process exit code. - Assert: the response is 200 with the full body, and the exit code is 143 (128 plus signal 15), with the shutdown completed in less than the timeout.
Run a second version of the test against the built container image, with
docker stop, and check that it returns in about a second and not after the full 10-second kill timeout. That version catches the shell-formCMDmistake immediately, since the signal never arrives.One such test in CI is cheap protection for a deploy path that otherwise fails only in production.
Q142. "Configuration per environment, and injecting secrets."
Reveal answer
Strong answer Follow the twelve-factor rule: the same image runs everywhere, and configuration comes from the environment, not from files baked into the image. Describe settings once in a BaseSettings class with types and defaults for local development. Production overrides come from environment variables, set by the platform (Kubernetes ConfigMap for plain values, Secret for sensitive ones).
Secrets deserve special handling. Use SecretStr so they print as asterisks in logs and reprs. Prefer mounted files (secrets_dir, files in /run/secrets) or a secret manager the platform injects (External Secrets, Vault agent, the cloud's secret store) over plain environment variables, which leak into crash dumps, docker inspect and child processes. Never put secrets in the image, the repository or a .env committed to Git.
Validate at start-up. If a value is wrong or missing, the process should fail immediately with a clear error, so a bad rollout never becomes ready, instead of failing at 3 a.m. on the first request that needs it. Keep one get_settings() with lru_cache, overridable in tests.
Picture it The same settings class in development, in production through environment variables, with a secret mounted from a file, and with a bad value.
import os, tempfile, pathlib
from pydantic import SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
d = pathlib.Path(tempfile.mkdtemp()); (d / "quickbite_jwt_secret").write_text("s3cret-from-mounted-file\n")
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="QUICKBITE_", secrets_dir=str(d), extra="ignore")
environment: str = "dev"
database_url: str = "sqlite:///./dev.db"
db_pool_size: int = 5
jwt_secret: SecretStr | None = None
print("dev defaults :", Settings().model_dump())
os.environ.update(QUICKBITE_ENVIRONMENT="prod", QUICKBITE_DATABASE_URL="postgresql+psycopg://app@db/quickbite", QUICKBITE_DB_POOL_SIZE="10")
s = Settings(); print("prod via env :", s.environment, s.database_url, s.db_pool_size)
print("secret :", repr(s.jwt_secret), "| value starts:", s.jwt_secret.get_secret_value()[:6])
os.environ["QUICKBITE_DB_POOL_SIZE"] = "lots"
try: Settings()
except Exception as e: print("bad value :", e.errors()[0]["type"], "-> the pod crashes at start, not at 3 a.m.")Make the invisible visible: Real output.
dev defaults : {'environment': 'dev', 'database_url': 'sqlite:///./dev.db', 'db_pool_size': 5, 'jwt_secret': SecretStr('**********')}
prod via env : prod postgresql+psycopg://app@db/quickbite 10
secret : SecretStr('**********') | value starts: s3cret
bad value : int_parsing -> the pod crashes at start, not at 3 a.m.What you see: In development the defaults apply and, since the secret file exists in this demo, the secret loads as SecretStr('**********'). Environment variables override the URL and pool size without touching code. A wrong value ("lots" for an integer) fails validation with int_parsing the moment settings are created, which in a pod means a failed start and a stopped rollout.
Spring Boot
Profiles and externalised config.
spring:
datasource:
url: ${DATABASE_URL}
password: ${DB_PASSWORD}pydantic-settings
Environment and secrets dir.
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="QUICKBITE_",
secrets_dir="/run/secrets")
database_url: str
jwt_secret: SecretStr | None = NoneThe shift: Same idea as profiles and placeholders: one artefact, behaviour decided by the environment, validated at start.
Land it One image everywhere, typed settings read from environment variables, secrets from mounted files or a secret manager as SecretStr, validated at start-up so bad config fails the rollout.
- "Why not a different config file per environment in the image?"
-
Because a separate file per environment breaks the best property a release can have: the thing you tested is the thing you ship.
If the image for production contains
config.prod.yamland the one for staging containsconfig.staging.yaml, then you build two different images, or one image containing every file. The production image has never been through staging as it is. A typo in the prod file is found only in production. If you build one image and select the file by an environment name, you have moved the problem, since the prod values are in the image, and any person who can pull the image can read them.The twelve-factor way fixes both. The image holds code and safe defaults only. The platform supplies the differences as environment variables or mounted files, so promoting means taking the same image digest from test to staging to production, changing only what the platform injects.
Secrets also stay out of the artefact, so a registry leak does not become a credentials leak. The settings class then validates at start-up that every needed value is present.
- "How do I rotate a secret without downtime?"
-
The method is overlap: for a while, both the old and the new secret are valid, so nothing breaks while the change spreads.
- Add the new, keep the old: for a JWT signing key, publish the new key next to the old one, with key ids, so tokens signed by either verify. For a third-party API key, create the second key at the provider.
- Roll out: deploy or restart pods so they all use the new key for signing and sending. Both keys still verify and work.
- Retire the old: when old tokens have expired or no pod uses the old key, remove it.
For database passwords, use a secret manager that creates fresh short-lived credentials, or alternate between two database users: rotate the password of user B while the app uses user A, switch to B, and then rotate A.
Mounted secret files update in place in Kubernetes after a short delay, but your app reads them only at start-up, so it must re-read them. Most teams find it simpler to restart the pods with a rolling restart, which also gives a clean check that the new secret works.
- "How do tests change settings?"
-
Tests build their own settings in code, and they never rely on the machine's environment. That makes the tests the same on a laptop and in CI.
Two moves do it. First, construct
Settings(...)with explicit values in a fixture: a test database URL pointing at in-memory SQLite, a test JWT secret, a small pool size. Pass_env_file=Noneif you want the test to ignore any local.envfile. Second, replace the dependency that provides settings:app.dependency_overrides[get_settings] = lambda: test_settings. Every route that depends onget_settingsnow sees the test values, and the canonicalconftest.pydoes exactly this.The rule that makes it work is that settings are read in one place and passed in. Code deep in the business layer must not call
os.environ, because a test could not change that without touching global state.Clear the
lru_cacheonget_settingsin a fixture when a test changes environment variables, since the cached object would hide the change. - "What about feature flags?"
-
I separate two ideas that people mix up: configuration that is fixed at deployment, and flags that must change while the system is running.
A static flag, such as "enable the new menu search" on staging only, is just a setting. It comes from the environment, it is set at start-up, and changing it means a restart or a rollout. That is acceptable for things that change rarely.
A runtime flag has different needs. A percentage rollout ("5 percent of users get the new checkout"), a kill switch for a misbehaving feature, or a per-customer override must change in seconds without a deploy. That needs a flag service, or a database table, which the app reads with a short cache, for example 10 to 30 seconds, so the flag lookup does not cost a request each time.
The test I apply is "if this feature breaks at 2 a.m., can the on-call person turn it off without a deploy?" If the answer must be yes, use a runtime flag. Also remove old flags when a rollout is complete, since stale flags multiply the combinations you must test.
Q143 · Scenario. "After scaling to 20 pods, the database hits max connections. Fix it."
Reveal answer
The real test Whether you do the multiplication (pods x workers x pool) before touching any setting.
Strong answer The total number of connections your fleet can open is the product: pods x workers per pod x (pool_size + max_overflow). PostgreSQL's default max_connections is 100. Twenty pods with two workers and a pool of 5 plus 5 overflow can ask for 400. The pods did nothing wrong individually; the fleet did.
Fixes, in the order I would apply them. First do the arithmetic and shrink the pools: most requests hold a connection only a few milliseconds, so a pool of 3 with overflow 2 per worker is often plenty. Second reduce workers per pod to 1 and scale pods instead, so one pod is one small pool.
Third add a pooler such as PgBouncer in transaction mode between the pods and PostgreSQL: thousands of client connections share a few dozen real ones. Fourth, raise max_connections only with care, since each connection costs memory (several MB) and PostgreSQL slows with very many.
Also cap the autoscaler's maximum so scale-out cannot exceed the connection budget, and alert on connections used versus max_connections. With PgBouncer in transaction mode, avoid session-level features (prepared statements by name, SET, advisory session locks) or configure them accordingly.
Picture it The multiplication for four configurations, against 100 connections.
print(f"{'pods':>5} {'workers':>8} {'pool+overflow':>14} {'peak connections':>17} vs Postgres max_connections=100")
for pods, workers, pool, over in [(3, 2, 5, 5), (20, 2, 5, 5), (20, 2, 3, 2), (20, 1, 3, 2)]:
total = pods * workers * (pool + over)
print(f"{pods:5} {workers:8} {pool:>8}+{over:<5} {total:17} {'OVER by ' + str(total-100) if total > 100 else 'ok, headroom ' + str(100-total)}")
print("budget: leave ~10 connections for admin, migrations, monitoring; or put PgBouncer in front and keep per-pod pools tiny")Make the invisible visible: Real output.
pods workers pool+overflow peak connections vs Postgres max_connections=100
3 2 5+5 60 ok, headroom 40
20 2 5+5 400 OVER by 300
20 2 3+2 200 OVER by 100
20 1 3+2 100 ok, headroom 0
budget: leave ~10 connections for admin, migrations, monitoring; or put PgBouncer in front and keep per-pod pools tinyWhy: The 20-pod fleet with the default-looking pool needs 400 connections, four times what the database offers. Tightening the pool to 3+2 halves it and still exceeds 100. Only dropping to one worker per pod reaches exactly 100, with zero headroom for migrations and admin tools, which is why the real fix is a pooler plus small pools.
Per-pod pools only
Fleet size multiplies.
# ❌ 20 pods x 2 workers x 10
engine = create_engine(url,
pool_size=5, max_overflow=5)Small pools + PgBouncer
Fleet shares real connections.
# url points at pgbouncer:6432
engine = create_engine(url,
pool_size=3, max_overflow=2,
pool_timeout=5)The shift: Capacity is a fleet-level budget; every pod's pool is a slice of it.
Land it I compute pods times workers times pool, shrink pools and workers per pod, put PgBouncer in transaction mode in front, cap autoscaling to the budget and alert on connection usage.
- "Why does PgBouncer in transaction mode help?"
-
It makes a few hundred application connections share a few dozen real ones, by lending a real connection only while a transaction is running.
Without a pooler, each app connection is a real PostgreSQL connection, which is a separate backend process using several megabytes, whether it is busy or not. Most app connections are idle most of the time, since a request holds one for a few milliseconds and then does other work.
In transaction mode, PgBouncer gives the client a server connection when a transaction begins and takes it back when the transaction commits or rolls back. The next transaction, from any client, may use that connection. Two hundred pods' connections at about 5 percent busy need roughly ten real connections.
connection arithmeticruns offlineclient connections = 20 pods x 2 workers x 10 = 400 busy at a time (5%) = 400 x 0.05 = 20 -> default_pool_size around 25The price is that anything tied to one session breaks between transactions:
SET, named prepared statements in some setups, session advisory locks andLISTEN. UseSET LOCALinside a transaction instead. - "What does the application see when the limit is hit?"
-
The application sees one of two errors, and both look like random failures to a user unless you know where to look.
If the database itself is out of connections, PostgreSQL refuses the new one with
FATAL: sorry, too many clients already(or "remaining connection slots are reserved"). SQLAlchemy raises anOperationalErrorwhen it tries to open one. If the pool is full on the app side, a request waits for a free connection, and after the pool timeout it raisesQueuePool limit of size 5 overflow 5 reached(Q61).What the client gets is a 500, or a 503 if you handle it. The failures come in bursts, since once the connections are gone, every new request fails until some are released.
The incident gets worse in a specific way. New pods start, try to open connections, and fail their readiness check, so they never join the Service, while old pods keep running at their limit. An autoscaler may then add even more pods, which want even more connections.
The alert I want is on connections used versus
max_connections, before the limit is reached, at about 80 percent. - "How do I choose pool_size?"
-
I choose it from how many queries run at the same moment in one worker, not from how many requests arrive per second. A request holds a connection only while it queries.
Little's law gives the average: the number in the system equals the arrival rate times the time each one stays.
little's law for the poolruns offline100 requests/s per worker x 0.010 s held = 1 connection busy on average bursts and slow queries: allow 3x to 5x = pool_size 3 to 5So 100 requests per second, each holding a connection for 10 ms, keep one connection busy on average. A pool of 3 to 5 absorbs bursts, and a slow query that holds a connection for 500 ms does not starve the rest.
The hold time includes everything inside the session scope. If an endpoint opens a session and then calls an external payment API before committing, the connection is held for the whole payment call. Do slow external work outside the transaction.
After setting the numbers, check the pool's checkout wait time in production. If requests wait often, the pool is too small, or queries are too slow, and the metric tells you which.
- "What about read replicas?"
-
Read replicas add read capacity, but they also add a second set of connection limits and a consistency trap. They do not replace the arithmetic from the question, they repeat it.
Each replica is its own PostgreSQL server with its own
max_connections. If twenty pods connect to one replica with the same pool size as to the primary, the replica faces the same limit. So I create a second engine, with its own pool sized for reads, and route read-only endpoints such as the order list through it, usually with a separate dependency likeget_read_session.The trap is replication lag. A replica may be some milliseconds, or several seconds under load, behind the primary. A customer who places an order and immediately opens the order list may not see it. Two common answers: read your own recent writes from the primary, for example for a minute after a write, or send only screens that tolerate staleness, such as the menu or the history of old orders, to the replica.
I would try pool sizing, then PgBouncer, before adding replicas to fix a connection problem. Replicas fix read load, not connection counts.
Q144. "Zero-downtime deploys that include database migrations."
Reveal answer
Strong answer During a rolling deploy, old and new application versions run at the same time against one database. So every migration must work with both versions. That rules out a single deploy that renames a column or adds a NOT NULL column with no default: the old code breaks the moment the schema changes.
The method is expand and contract, spread over several deploys. Expand: add the new thing in a backward-compatible way (a nullable column, a new table, a new index built with CREATE INDEX CONCURRENTLY in PostgreSQL).
Old code ignores it. Migrate: deploy code that writes both old and new, backfill existing rows in small batches, then deploy code that reads the new one. Contract: once nothing uses the old column, enforce constraints (NOT NULL via a CHECK ... NOT VALID then VALIDATE to avoid long locks) and drop the old column in a later release.
Run migrations as a separate step before the app rollout (Q69), set a lock_timeout so a migration never queues behind a long transaction and blocks everyone, and keep each migration small and reversible where possible. Test it on a copy of production-sized data.
Picture it A phone-number column becoming a normalised phone_e164 column, over three deploys. Each step is safe against the code of the previous one.
import sqlite3
db = sqlite3.connect(":memory:", isolation_level=None)
db.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY, phone TEXT)")
db.executemany("INSERT INTO customers (phone) VALUES (?)", [("98765 43210",), ("+91 91234 56789",), ("98111 22233",)])
def old_code_insert(phone): db.execute("INSERT INTO customers (phone) VALUES (?)", (phone,))
def new_code_insert(phone): db.execute("INSERT INTO customers (phone, phone_e164) VALUES (?, ?)", (phone, normalise(phone)))
def normalise(p): d = "".join(ch for ch in p if ch.isdigit()); return "+" + (d if d.startswith("91") and len(d) == 12 else "91" + d)
print("deploy 1 EXPAND : add a NULLABLE column; old code keeps working")
db.execute("ALTER TABLE customers ADD COLUMN phone_e164 TEXT"); old_code_insert("99999 00000")
print("deploy 2 MIGRATE : new code writes both; backfill old rows in small batches")
new_code_insert("97777 11111")
while True:
rows = db.execute("SELECT id, phone FROM customers WHERE phone_e164 IS NULL LIMIT 2").fetchall()
if not rows: break
for i, p in rows: db.execute("UPDATE customers SET phone_e164=? WHERE id=?", (normalise(p), i))
print(" batch updated ids", [i for i, _ in rows])
print(" rows still NULL:", db.execute("SELECT count(*) FROM customers WHERE phone_e164 IS NULL").fetchone()[0])
print("deploy 3 CONTRACT: reads switched; now enforce NOT NULL (Postgres: ALTER ... SET NOT NULL after a CHECK ... NOT VALID + VALIDATE), drop old column later")
print(db.execute("SELECT id, phone_e164 FROM customers").fetchall())Make the invisible visible: Real output.
deploy 1 EXPAND : add a NULLABLE column; old code keeps working
deploy 2 MIGRATE : new code writes both; backfill old rows in small batches
batch updated ids [1, 2]
batch updated ids [3, 4]
rows still NULL: 0
deploy 3 CONTRACT: reads switched; now enforce NOT NULL (Postgres: ALTER ... SET NOT NULL after a CHECK ... NOT VALID + VALIDATE), drop old column later
[(1, '+919876543210'), (2, '+919123456789'), (3, '+919811122233'), (4, '+919999900000'), (5, '+919777711111')]Why: The expand step added a nullable column and an old-code insert still succeeded (customer 4 was inserted by old code with no new value). The migrate step backfilled in batches of two rows until none were left, with new code writing both columns. Only then is it safe to make the column required and later drop the old one.
One-step migration
Old pods break on deploy.
def upgrade():
# ❌ old code still inserts "phone"
op.alter_column("customers", "phone",
new_column_name="phone_e164")Expand then contract
Each step is compatible.
# deploy 1
op.add_column("customers", sa.Column(
"phone_e164", sa.String(), nullable=True))
# deploy 2: dual write + backfill
# deploy 3: SET NOT NULL, later drop "phone"The shift: Never change what a running version depends on; add beside it and remove it later.
Land it I split every breaking schema change into expand, migrate and contract across deploys, build indexes concurrently, backfill in batches, and run the migration before the rollout with a lock timeout.
- "Which operations are dangerous in PostgreSQL?"
-
The dangerous ones are those that take a strong lock for a long time on a busy table, since a lock queues every other query behind it. On a table that serves traffic, a 30-second lock is an outage.
- Index without CONCURRENTLY:
CREATE INDEXblocks writes for the whole build. UseCREATE INDEX CONCURRENTLY, which takes longer but allows writes (it cannot run inside a transaction block). - Table rewrites: changing a column type with
ALTER COLUMN TYPE, or adding a column with a volatile default, can rewrite the whole table under an exclusive lock. Since PostgreSQL 11, adding a column with a constant default is fast, but check your version. - Constraints with validation: a new foreign key or
NOT NULLscans the table while locked. Add the constraint asNOT VALIDfirst, and thenVALIDATE CONSTRAINT, which takes a weaker lock.
Behind all of these is the lock queue: a migration waiting for a lock blocks the queries that arrive after it. So set
SET lock_timeout = '3s', and let the migration fail and retry, instead of freezing the table. - Index without CONCURRENTLY:
- "How do I backfill a table with 100 million rows?"
-
I do it in small batches, outside the migration, with a script that can be stopped and resumed. A single
UPDATEover 100 million rows would hold locks, bloat the table, flood the replication stream and run for hours in one transaction.backfill batchUPDATE orders SET status_v2 = status WHERE id > :last_id AND id <= :last_id + 5000 AND status_v2 IS NULL; -- commit, record :last_id, sleep 100 ms, repeatEach batch is a short transaction of about 5,000 rows, selected by a range of the primary key so each query uses the index. The script commits, saves the last id it finished, sleeps a little, and continues. If it stops, it resumes from the saved id.
While it runs, I watch replication lag, lock waits and the table's dead rows. If lag climbs, the script slows down automatically, or I raise the sleep. At 5,000 rows per 150 ms the job takes 100,000,000 / 5,000 = 20,000 batches, about 50 minutes. That is a safe and predictable cost.
- "How do I handle rollbacks?"
-
Rollback is safe as long as the schema stays compatible with the previous version, and that is what the expand step guarantees. The planning question is which steps cannot be undone, and those are placed last.
After the expand step, the database has an extra nullable column or table that the old code ignores. If the new code has a bug, you deploy the old version again, and it runs fine against the expanded schema. The extra column does no harm. That is why every step before contract can be reversed by redeploying code.
The contract step is different: dropping a column or table destroys data, and a downgrade script cannot bring it back. So contract waits until the new version has run for a while, for example a week, with no incidents and no reads of the old column, which you can check in
pg_stat_user_tablesor logs. A backup or a copy of the column before the drop is cheap insurance.The rule for the team: never combine an expand and a contract in one deploy.
- "What does Alembic add here?"
-
Alembic gives you a versioned, ordered history of schema changes in the repository. Each migration is a Python script with a revision id, a link to its parent, and
upgrade()anddowngrade()functions.alembic upgrade headapplies the missing ones, and thealembic_versiontable records where the database is.For zero-downtime work, I use it as a tool and I do not trust its autogeneration.
alembic revision --autogeneratecompares your SQLAlchemy models with the database and drafts a migration. It sees added tables and columns, but it cannot see intent. A renamed column looks like a drop plus an add, which would delete the data. It also does not write data migrations, and it may produce a plainCREATE INDEXwithoutCONCURRENTLY.So the workflow is: generate, read every line, and edit by hand. Use
op.execute("ALTER TABLE ... RENAME COLUMN ...")for renames, split big changes into expand and contract revisions, and put index creation insidewith op.get_context().autocommit_block(), so concurrent index creation can run outside the transaction.Finally, run
upgradeanddowngradein CI against a fresh database.
Q145. "FastAPI, Django REST Framework, Django Ninja, Flask or Litestar — when each?"
Reveal answer
Strong answer There is no best framework, only the best fit for the team and the problem. My summary: FastAPI when the product is an API and you want typed models, validation and generated docs with little ceremony; Django with DRF or Ninja when you also want an admin site, an ORM with migrations, authentication and a mature ecosystem included; Flask for small services and teams that already know it; Litestar if you like FastAPI's ideas with a more opinionated structure and built-in extras.
Be honest about FastAPI's limits. It gives you routing, validation and dependency injection, but not an ORM, migrations, admin, background jobs or a project layout; you assemble those. It is also still a 0.x project, so pin versions and read release notes. Django gives a lot of that for free but is more tied to its own ORM and request cycle, and sync-first (async support exists but is uneven in places).
The comparison below is based on the documentation and general practice; only FastAPI and Flask are installed on the course machine, so nothing else was run, and some details change between versions.
Picture it The decision table I would draw on the whiteboard.
| Pick it when | Cost or catch | Switch when | |
|---|---|---|---|
| FastAPI | API-first service, typed models, generated OpenAPI, async I/O | you assemble ORM, auth, migrations; 0.x release cadence | you need a full admin and CRUD site, or the team lacks Python typing habits |
| Django + DRF | you want admin, ORM, auth and a mature plugin ecosystem | heavier, serializers are verbose, sync-first | the product becomes API-only with high concurrency needs |
| Django Ninja | Django project that wants FastAPI-style typed endpoints | smaller community, fewer plugins than DRF | you leave Django entirely |
| Flask | small service, simple needs, existing Flask knowledge | no validation or OpenAPI by default; extensions to choose and maintain | the service grows and you keep re-inventing FastAPI's parts |
| Litestar | you want structure, DTOs and batteries with typing | smaller community and hiring pool | team prefers the larger ecosystem of FastAPI or Django |
| Starlette alone | tiny gateways, custom frameworks, streaming proxies | no validation or docs; you write the glue | you start adding validation and docs by hand |
Spring Boot
One big, opinionated framework.
// illustrative
Web + Security + Data JPA + Actuator
+ Flyway + Validation, one BOM,
conventions decide most thingsFastAPI
Small core, you choose the rest.
FastAPI + Pydantic
+ SQLAlchemy + Alembic
+ pydantic-settings + structlog
(you pick and wire each one)The shift: FastAPI is closer to a toolkit than to Spring Boot; Django is the closer cousin of Spring Boot in spirit.
Land it FastAPI for API-first services, Django when I want its batteries and admin, Flask for small existing services, and I decide from team skills and what I would otherwise have to build myself.
- "How would I decide on a new team's project?"
-
I ask four questions in order, and the answers usually decide it without a long debate.
- Is it an API, or a whole product? A pure JSON API for a mobile app or other services points to FastAPI. A product with server-rendered pages, an admin site for staff, and user accounts built in points to Django.
- What does the team know? A team fluent in Django ships faster in Django, whatever the benchmarks say. Skills outweigh features for the first year.
- What load and latency are needed? Most business APIs are database-bound and any of these frameworks copes. Very high concurrency of waiting connections favours an async design.
- What would we have to build ourselves? With FastAPI you add the ORM, migrations, admin, auth and background jobs. Count that work honestly.
For QuickBite, a pure orders API, FastAPI fits. If the company also needed a back-office admin for restaurant onboarding next month, I would consider Django for that part, and I would not force one framework onto both.
- "Is FastAPI production-ready if it is still 0.x?"
-
Yes, production-ready, and many large systems run on it. The 0.x version only tells you how to treat upgrades.
Under semantic versioning, a 1.0 release promises that breaking changes happen only in a major version. A 0.x project makes no such promise, so a minor release can change behaviour. FastAPI is careful, and uses deprecation warnings for a long time, but it has changed things: the timing of teardown in yield dependencies changed between versions, and
ORJSONResponsewas deprecated in 0.141, for example. Check the release notes for what you use.My practice is four rules:
- pin the exact version in the lock file;
- read the release notes before each bump;
- run the full test suite, with warnings turned into errors in CI, so a deprecation is seen early;
- upgrade regularly in small steps, because skipping ten versions is harder to debug than ten single bumps.
I would say the same for any fast-moving dependency, and the discipline costs very little compared to the risk.
- "What about performance differences?"
-
For the usual database-bound API, the framework is a small part of the request time, and the differences between frameworks are dwarfed by the database and the design. In the course measurements, the time went to round trips, not to routing.
There are real differences at the edges. Async frameworks built on Starlette, such as FastAPI and Litestar, can hold thousands of waiting connections in one process, which suits WebSockets, streaming and calls to many slow services. A sync-first Django stack uses a thread or process per request in that situation, which costs more memory per waiting request. Django also does more per request by default: middleware, sessions, an ORM with signals. A bare Flask app is light, and without validation it also does less work.
Yet a well-designed Django service, scaled across more pods, serves the same traffic, and hardware is often cheaper than engineering time.
So I never choose on a general benchmark. I build the busiest route in the candidate frameworks with the real database, run a load test at the real concurrency, and compare p99 latency and cost per thousand requests.
- "Django Ninja or DRF for a Django project?"
-
Ninja or DRF is mostly a question about the existing team, the ecosystem and the type hints, and I would choose from these four points.
Django Ninja has a FastAPI-like feel: you write functions with type hints, Pydantic schemas validate input and output, and OpenAPI docs are generated without extra work. It has much less boilerplate than DRF's serializer, viewset and router stack, and it supports async views. It suits a team that likes FastAPI's style but wants Django's ORM, admin and auth.
DRF is older and has a much larger ecosystem. Third-party packages for filtering, token and OAuth authentication, throttling, browsable API screens and permissions are built for it, and many engineers already know it. If you inherit a large DRF code base, rewriting to Ninja is rarely worth the time.
So: greenfield, with a team comfortable with type hints, I would try Ninja, after checking that every plugin I need exists. Existing DRF code, or a need for its packages, I would stay with DRF. Neither was run on the course machine, so check current versions and docs first.
Q146 · Scenario. "The team wants to move a Flask app to FastAPI. Plan the migration."
Reveal answer
Strong answer I would not rewrite it in one go. A big-bang rewrite freezes features, hides regressions and ends up late. The safe approach is the strangler pattern: put FastAPI in front, serve new and migrated routes from it, and let everything else fall through to Flask, until Flask has nothing left.
- Characterise first: write black-box tests against the existing HTTP API (status, body, headers) for every route, or record real traffic. These tests are the safety net and they run unchanged against both implementations.
- Mount, then migrate: create the FastAPI app and mount the Flask app as a fallback so one process serves both. Starlette's
WSGIMiddlewaredoes this, but it is deprecated and announced for removal (the warning points toa2wsgi), so use the replacement for anything lasting. Alternatively route by path at the gateway. - Move route by route: start with read-only, simple routes. Define Pydantic models that reproduce the current JSON exactly, including odd field names and error shapes; clients depend on them. Improve later, behind a new version (Q35).
- Share the data layer: keep the same database and, at first, the same SQLAlchemy models, so both frameworks see one truth. Move to the layered structure (routers, services, repositories) as you go.
- Handle auth and sessions: put token validation in a dependency, and make sure sessions or cookies set by Flask are still honoured until the last route moves.
- Remove Flask: when no traffic reaches it, delete the mount, the extensions and the dependency.
Watch for sync code in the Flask routes: copying it into async def endpoints blocks the loop (Q4). Move sync code as plain def first.
Picture it The mount in miniature: FastAPI owns /v2, Flask answers the rest.
import warnings
warnings.simplefilter("default")
from flask import Flask, jsonify
from fastapi import FastAPI
from fastapi.testclient import TestClient
from starlette.middleware.wsgi import WSGIMiddleware
flask_app = Flask(__name__)
@flask_app.get("/legacy/orders/<int:oid>")
def legacy(oid): return jsonify(id=oid, source="flask")
app = FastAPI()
@app.get("/v2/orders/{oid}")
def new(oid: int): return {"id": oid, "source": "fastapi"}
app.mount("/", WSGIMiddleware(flask_app)) # strangler: anything FastAPI does not own falls through
c = TestClient(app)
print(c.get("/v2/orders/1").json()); print(c.get("/legacy/orders/1").json())Make the invisible visible: Real output, with the deprecation warning the real run prints.
flask_mount.py:6: StarletteDeprecationWarning: starlette.middleware.wsgi is deprecated and will be removed in a future release. Please refer to https://github.com/abersheeran/a2wsgi as a replacement.
{'id': 1, 'source': 'fastapi'}
{'id': 1, 'source': 'flask'}What you see: Both apps answer in one process: the migrated route comes from FastAPI and the legacy route from Flask. The warning is real: starlette.middleware.wsgi is deprecated and will be removed, with a pointer to a2wsgi, which is not installed on the course machine, so this is a demonstration of the shape and not of the long-term mechanism.
Big bang
Months without releases.
# ❌ TRAP
freeze Flask, rewrite everything,
switch on release day, hopeStrangler
Small, reversible steps.
characterise -> mount -> move one route
-> compare responses -> shift traffic
-> repeat -> delete FlaskThe shift: Replace the system a slice at a time, with the old and new answering the same tests.
Land it I migrate with a strangler: black-box tests first, FastAPI in front with Flask as fallback, one route at a time with identical JSON, shared data layer, and Flask deleted last.
- "How do I prove the new route behaves like the old one?"
-
I prove it by running the same tests against both, and then by comparing real traffic, so that I do not depend on my reading of the code.
- Same characterisation tests: the black-box tests (status, headers, body) run unchanged against the Flask route and the FastAPI route. A test that passes on one and fails on the other shows a difference you must decide on.
- Shadow traffic: for risky routes, the gateway sends a copy of each real request to the new service, and discards the new response. A comparer logs differences between old and new answers. Users still get the old answer, so nothing can go wrong for them. Only use it for safe reads, or for writes that go to a test database.
- Gradual shift: move 1 percent of real traffic to the new route, then 10, 50 and 100, watching error rate and latency at each step.
Expect differences in small things: key order does not matter in JSON, but number formats, date formats, trailing slashes and error shapes do. Fix them in the new route, so clients do not have to change.
- "What if Flask uses
g,requestand thread-locals everywhere?" -
Those globals become explicit parameters. In Flask,
request,gandcurrent_userare proxies to thread-local state that exists "somewhere", so any function can reach them without a signature saying so. FastAPI makes each need visible, through function arguments andDepends.I translate route by route. Look at what the Flask view reads from
g: sayg.userandg.db. Write one small dependency per item,get_current_userandget_session, and add them as parameters. The route's signature now lists everything it needs, and tests can override each item.The temptation is to copy the old style with a ContextVar called
g, so that deep helper functions keep working with no changes. It runs, but it keeps the hidden coupling that made the old code hard to test. I allow it only for a narrow case, such as a request id for logging, where a ContextVar is the right tool.For helper functions that read
gdeep inside, I add a parameter and pass the value down from the route. It is more edits now, and far less confusion later. - "How long should this take?"
-
I do not promise a date without data, because the answer depends on the number of routes, the test coverage and what hides in the Flask code. I make the estimate the first deliverable, and I base it on measurement.
In the first sprint, migrate the three simplest routes, end to end, through the strangler setup, with characterisation tests and the same JSON. This is a small task, and it exposes the real problems early: how sessions and cookies work, how errors are shaped, which extensions the code depends on, how auth is done, and how the deploy works with two frameworks in one process.
Then estimate from velocity. If three simple routes took 5 days including set-up, and set-up is a one-off cost, then the next ten take less per route, and I add a multiplier for medium and hard routes. For example, 80 routes, of which 50 are simple at half a day each, 25 medium at two days and 5 hard at a week, gives 25 + 50 + 35 = 110 days of effort, which I then convert to calendar time using the team size.
I report it as a range and update it every sprint.
- "Should I go async at the same time?"
-
No, change one thing at a time. A migration that changes the framework, the sync model and the database driver together has many possible causes for every failure, and the team cannot tell which change broke what.
The safe first step is to move the Flask views into FastAPI as plain
defendpoints that still use the existing synchronous SQLAlchemy code. FastAPI runs them in its threadpool (40 threads by default), so the event loop stays free, and the behaviour is close to what Flask did with its worker threads. You get validation, generated documentation and typed models, and the database access is unchanged.Copying sync code into
async defendpoints is the classic mistake: a blocking query then stalls the whole loop (Q134), and you will see latency spikes you did not have in Flask.After the migration is finished and stable, look at the metrics. Where a route waits long on the database or on external services, and concurrency is high, move that route to an async driver, by measurement (Q138). Many routes never need it.
Q147. "When would you not use Python for an API at all?"
Reveal answer
Strong answer Python is a good choice for I/O-bound business APIs, data and machine learning products, and fast iteration. I would not choose it, or I would limit its role, in these cases.
- Extreme throughput or tight latency: very high request rates per core, or p99 targets of a few milliseconds, where Go, Rust, Java or C# serve several times more per CPU and use less memory per connection. Python's GIL and interpreter overhead set a ceiling per process.
- CPU-heavy request handling: image or video processing, large computations, parsing at scale, done inline per request. Python offloads these to C libraries or workers, but if the whole job is CPU code, a compiled language is simpler.
- Hard real-time or tiny footprints: edge devices, embedded, anything with memory in the tens of megabytes or strict latency guarantees.
- Large teams wanting compile-time safety: a big code base with many contributors benefits from a statically typed compiled language, where refactoring and interfaces are checked by the compiler; Python's type hints help but are not enforced at run time.
- Existing platform standards: a company with a strong Java or Go platform, shared libraries, security tooling and on-call knowledge. A one-off Python service costs more to operate than it saves.
Python with FastAPI is a good fit when the team knows it, the service is I/O-bound and moderate in scale, it sits next to data or machine learning code, or time to market matters most. And it can be mixed: Python for the product API, Go or Rust for one hot path behind it.
Picture it The decision as a table, with the signal that moves each row.
| Situation | Python API fine? | Switch when |
|---|---|---|
| Typical business CRUD, a few hundred req/s per service | yes | never needed |
| Machine learning or data product exposed through an API | yes, the libraries live there | only the inference hot loop moves to native code |
| 20,000 req/s per node, p99 under 5 ms | strained | benchmark first; consider Go, Java or Rust for that service |
| CPU-bound work in every request | no, unless offloaded to workers | the offload code becomes bigger than the service |
| Team of 80 on one large code base, strict interfaces | possible with strict typing and linters | refactoring cost and run-time type errors keep rising |
Spring Boot
Compiled, threads or virtual threads.
// illustrative
JIT-compiled, true parallel threads,
virtual threads for blocking I/O,
static types checked at build timePython
Interpreted, one loop per process.
GIL: one thread runs Python at a time
scale with processes and pods
types are hints, enforced by testsThe shift: The trade is development speed and ecosystem against raw throughput per core and compile-time checks.
Land it I choose Python for I/O-bound, data-adjacent and fast-moving APIs, and I would pick a compiled language for extreme per-core throughput, CPU-bound request work or platforms standardised on something else.
- "Does free-threaded Python change this?"
-
It changes one part of the argument, and the rest still holds. Free-threaded Python is a build without the global interpreter lock, available since 3.13 as an optional build and supported in 3.14. In it, several threads can run Python code on several cores at once.
That attacks the strongest argument against Python for CPU-heavy request work: the GIL ceiling per process. In the E19 benchmark on the pricer workload, four threads on the free-threaded build took 0.25 s against 1.04 s on the normal build with the same threads. So threaded CPU work can now scale.
The limits are practical. Compiled extension packages must be built for the free-threaded build, and some are still catching up. Single-thread code is slower on that build, about 23 percent on the same benchmark. And thread safety of your own code becomes a real concern, since races that the GIL hid can appear.
So for an API I would treat it as promising, and test it on my own dependencies and workload before relying on it. I would still not choose Python for work where a compiled language is plainly simpler.
- "Is "Python is slow" a good argument?"
-
Rarely, when said by itself. "Python is slow" is true for a tight loop of arithmetic, where Python is 10 to 100 times slower than C or Go. It is mostly false for a typical API, where the time goes elsewhere.
Take a request that takes 80 ms: 60 ms is waiting for the database, 15 ms is the call to another service, and 5 ms is Python code and serialisation. A language that is ten times faster saves 4.5 ms and the request takes 75.5 ms. The user cannot notice that, so the claim "Python is slow" misses where the time is.
I ask for numbers instead. What is the throughput per core of the real endpoint, measured with the real database? How many servers does that mean at peak load? What do those servers cost per month, compared with the cost of engineers writing and maintaining the service in a slower-to-develop language?
If the answers show that you need 400 cores in Python and 60 in Go, and that the saving is larger than the extra development cost, the argument is real, and I would act on it. Without the numbers, it is a preference.
- "How do you reduce the Python cost when it matters?"
-
I follow the order that measurement suggests, starting with the cheapest and least risky, and I stop when the target is met.
- Remove waste first: fewer layers and dependencies per request, no repeated work, fix N+1 queries, cut the size of responses with pagination.
- Serialise once: declare a return type or response model so FastAPI validates and encodes in one pass in Pydantic's Rust core. Avoid building dicts first.
- Cache: menu data and other reads that change slowly, in memory or in Redis.
- Async drivers: where many requests wait at once, by measurement.
- C or Rust on the hot path: a compiled library or a small extension for the one measured hot loop.
- Scale out: more pods are often the cheapest answer for stateless services.
The order of 4, 5 and 6 changes with the workload. I decide by profiling a realistic load, and not by guessing. Each step makes the code a little more complex, so I stop as soon as the objective is met.
- "Would you ever mix languages?"
-
Yes, when a measured need justifies it, and the language boundary is chosen carefully. The usual shape is a Python API for the product surface, where change is frequent, and a service in Go or Rust for one hot path that Python cannot serve well.
A concrete case for QuickBite: the order API stays in Python, and the rider-location ingestion, which receives 50,000 small updates per second, is a small Go service. The two talk over gRPC or HTTP, or through a queue such as Kafka, with a clear contract and versioned schemas.
The rule I keep is to keep the number of languages small. Every extra language multiplies the tools you maintain: build pipelines, linters, base images, security scanning, dashboards, libraries for logging and tracing. It also splits the on-call pool, because fewer people can fix a service in a language they do not use, and it makes hiring harder.
I would also ask whether a Python extension in Rust (for example with PyO3) solves the hot path inside the existing service, which avoids a new deployment unit altogether.
Q148 · Scenario. "A CPU-heavy endpoint (PDF generation) blocks the server. Fix it."
Reveal answer
The real test Whether you know threads do not help pure-Python CPU work because of the GIL, and reach for processes or a worker queue.
Strong answer CPU-bound code run inside an async def endpoint holds the event loop thread for its whole duration, so every other request in that worker waits (Q134). The first fix people try is asyncio.to_thread. It frees the loop to accept requests, but the thread still has to take turns with the loop's thread for the GIL (the lock that lets only one thread run Python bytecode at a time), so pure-Python CPU work still slows everything down, just less.
Better options. A process pool (ProcessPoolExecutor via loop.run_in_executor) runs the work in separate processes with their own GIL, so it truly runs in parallel and the event loop stays responsive. Arguments and results are pickled, so pass small data. A job queue with workers (Q126) is better still for work that takes seconds: return 202 with a status resource (Q105), and scale workers independently of web pods.
Native code that releases the GIL (a C library, a Rust extension, or a subprocess such as a headless renderer) can run in threads without the penalty.
Also bound it: a limit on concurrent jobs, a timeout, and a limit on input size, so one customer cannot consume every CPU.
Picture it A 270 ms hashing loop standing in for PDF rendering, run three ways while a health probe is due 50 ms after the request begins.
import asyncio, hashlib, time, httpx
from concurrent.futures import ProcessPoolExecutor
from fastapi import FastAPI
def render_pdf(n: int) -> str: # stand-in for ~0.3 s of pure-Python CPU work
h = b"x"
for _ in range(n): h = hashlib.sha256(h).digest()
return h.hex()[:8]
N = 600_000
pool = ProcessPoolExecutor(2)
app = FastAPI()
@app.get("/health")
async def health(): return {"ok": 1}
@app.get("/pdf-on-loop")
async def a(): return {"pdf": render_pdf(N)} # ❌ TRAP: CPU on the event loop
@app.get("/pdf-thread")
async def b(): return {"pdf": await asyncio.to_thread(render_pdf, N)} # frees the loop only partly: the GIL is still shared
@app.get("/pdf-process")
async def c(): return {"pdf": await asyncio.get_running_loop().run_in_executor(pool, render_pdf, N)}
async def measure(path):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as cl:
t0 = time.perf_counter(); out = {}
async def probe():
await asyncio.sleep(0.05); due = time.perf_counter(); await cl.get("/health"); out["ms"] = (due - t0 - 0.05) * 1000
await asyncio.gather(cl.get(path), probe()); out["total"] = (time.perf_counter() - t0) * 1000; return out
t = time.perf_counter(); render_pdf(N); print(f"one render alone: {(time.perf_counter()-t)*1000:.0f} ms")
asyncio.run(measure("/pdf-process")) # warm the worker processes
for p in ("/pdf-on-loop", "/pdf-thread", "/pdf-process"):
o = asyncio.run(measure(p)); print(f"{p:14} health probe, due at 50 ms, started {o['ms']:6.1f} ms late; whole run {o['total']:5.0f} ms")Make the invisible visible: Real output (course machine; ratios matter more than digits).
one render alone: 275 ms
/pdf-on-loop health probe, due at 50 ms, started 270.1 ms late; whole run 321 ms
/pdf-thread health probe, due at 50 ms, started 11.9 ms late; whole run 292 ms
/pdf-process health probe, due at 50 ms, started 0.9 ms late; whole run 273 msWhat you see: On the loop, the probe started 270 ms late, the whole length of the job. In a thread it started 12 ms late: much better, but not zero, because the GIL is still shared. In a process pool it started under 1 ms late and the total run time did not grow, so the loop was untouched.
CPU on the loop
Everyone waits for the PDF.
@router.get("/invoice")
async def invoice():
return render_pdf(order) # ❌ 270 ms of CPUProcess pool
Loop stays free.
@router.get("/invoice")
async def invoice():
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
pool, render_pdf, order_id)The shift: Give CPU work its own cores, not a seat on the thread that serves everyone.
Land it I move CPU-bound work off the event loop into a process pool or, for anything that takes seconds, into a queue with separate workers and a 202 status resource.
- "Why is
to_threadnot enough here?" -
Because of the GIL, the lock that lets only one thread run Python bytecode at any moment. A thread moves the work off the event loop's thread, but the two threads still take turns for that one lock.
Suppose the endpoint runs a pure-Python loop for 2 seconds, in
await asyncio.to_thread(render). The worker thread runs the loop. The event loop thread wants a turn to serve other requests. Python switches between threads every few milliseconds (5 ms by default), so the loop gets small slices, and every other request becomes slower. The loop is not completely blocked, which is the improvement, but latency of other requests still rises, and the CPU work is not any faster.A thread helps in two cases. If the work waits, such as network or disk I/O, the thread releases the GIL while waiting. And many C libraries release the GIL during heavy computation: hashing large buffers, compression, image libraries, some NumPy operations.
A PDF library written in pure Python does not. For that, processes are the answer, since each process has its own GIL. On the free-threaded build, threads would scale too, which is worth testing.
- "What are the costs of a process pool?"
-
The costs are real but manageable, and they decide how I set it up. A process pool is the right tool for CPU work, so the question is how to pay its costs once.
Start-up is the first one: each process starts a new interpreter and imports your modules, which can take hundreds of milliseconds and tens of megabytes. So create the pool once, in the lifespan, and reuse it, never per request. Shut it down on exit, with
pool.shutdown(wait=True).Pickling is the second. Arguments and results travel between processes as bytes, so passing a 50 MB object for each job costs more than the work. Pass identifiers or small structures, and let the worker load the data itself.
The third is size: about one process per core, or you get no more speed, and each process holds its own memory.
The fourth is isolation. Workers cannot share a database session or a connection, so each worker must create its own, if it needs one. A crashed worker raises
BrokenProcessPool, so handle that error and rebuild the pool. - "How do I stop PDF jobs from taking all CPUs?"
-
The aim is to limit how many jobs run at once and to say no early when you are full, so that the load does not spread into every other request.
- Limit concurrency: the pool size is the first limit, for example 4 processes on a 4-core pod. An
asyncio.Semaphorein front of it limits how many requests wait for the pool. - Bound the queue: a queue absorbs bursts, but only up to a length. When it is longer than, say, 20 waiting jobs, return 429 (too many requests) or 503 with a
Retry-Afterheader, instead of letting wait times grow without limit. - Timeouts: each job gets a time limit, so a runaway document with a million pages cannot keep a core forever. Remember that a running process job cannot be cancelled by
asyncioalone, so the worker must stop itself, or you kill that process. - Input limits: cap the document size and the page count before starting.
Per-customer limits stop one customer from filling all the slots.
- Limit concurrency: the pool size is the first limit, for example 4 processes on a 4-core pod. An
- "Would you generate PDFs in the web tier at all?"
-
Rarely, and only for small documents. A web pod should answer requests quickly, and PDF rendering is heavy, bursty and memory-hungry, which fits badly with that job.
Consider what rendering does to a web pod. It uses a whole core for seconds, may load fonts and images, and may use hundreds of megabytes, so the pod needs a bigger memory limit just for this one route, and every other route pays for it. A burst of reports, for example at the end of the month, slows the order API for customers who never asked for a PDF.
The better design is a separate path. The API accepts the request, writes a job, and returns 202 with a status URL. A worker, with its own pods and its own scaling rules, renders the file, stores it in object storage, and marks the job done. The client polls the status, or receives a notification, and downloads the file with a signed link that expires.
Web pods stay small, and rendering capacity scales on its own. Inline generation is fine for a one-page receipt that takes 50 ms, but I would measure that before deciding.
Q149 · Design. "Design a multi-tenant FastAPI SaaS backend: tenancy, isolation, auth and data."
Reveal answer
Strong answer The central choice is how tenants share data. I describe the options and then pick one by risk and scale.
| Model | Isolation | Cost and operations | Pick it when |
|---|---|---|---|
Shared tables with a tenant_id column | logical, enforced by code and optionally row-level security | cheapest, one schema, simplest migrations | many small tenants, strong engineering discipline |
| Schema per tenant | stronger, separate namespaces in one database | migrations run per schema, thousands of schemas strain tooling | dozens to hundreds of mid-size tenants |
| Database per tenant | strongest, can place data by region | most expensive, most operational work | large or regulated tenants who pay for it |
My default is shared tables with a tenant id and PostgreSQL row-level security, moving large or regulated tenants to their own database later. Whatever the model, four rules hold.
- Tenant comes from the verified token: a signed claim, never a header or path value the client chooses. A dependency reads it and returns a
TenantContext. - The repository cannot forget the filter: every query goes through a base class that adds
WHERE tenant_id = :t, and row-level security setsapp.tenant_idper transaction as a second wall. - Tenant-aware everything else: cache keys, object storage prefixes, search indexes, rate limits and background jobs all carry the tenant id.
- Fairness: per-tenant rate limits and quotas so one noisy tenant cannot starve others.
Test isolation explicitly: for each route, a test creates data as tenant A and asserts tenant B gets 404 (the IDOR test of Q91, repeated per tenant).
Picture it A repository that makes the tenant filter impossible to forget, tested with a foreign row.
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, select, String
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.pool import StaticPool
class Base(DeclarativeBase): pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
tenant_id: Mapped[str] = mapped_column(String(20), index=True)
note: Mapped[str]
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool); Base.metadata.create_all(engine)
with Session(engine) as s, s.begin(): s.add_all([Order(tenant_id="acme", note="acme order"), Order(tenant_id="globex", note="globex order")])
def tenant(x_tenant_from_verified_token: str = Header()) -> str: return x_tenant_from_verified_token # real code: a JWT claim
class TenantRepo:
def __init__(self, tenant_id: Annotated[str, Depends(tenant)]): self.t = tenant_id
def orders(self, s): # the ONLY way to read orders: the filter cannot be forgotten
return s.scalars(select(Order).where(Order.tenant_id == self.t)).all()
def get(self, s, oid):
o = s.scalars(select(Order).where(Order.tenant_id == self.t, Order.id == oid)).first()
if o is None: raise HTTPException(404)
return o
app = FastAPI()
@app.get("/v1/orders")
def lst(repo: Annotated[TenantRepo, Depends()]):
with Session(engine) as s: return [o.note for o in repo.orders(s)]
@app.get("/v1/orders/{oid}")
def one(oid: int, repo: Annotated[TenantRepo, Depends()]):
with Session(engine) as s: return repo.get(s, oid).note
c = TestClient(app); acme = {"X-Tenant-From-Verified-Token": "acme"}
print("acme list :", c.get("/v1/orders", headers=acme).json())
print("acme gets #1 :", c.get("/v1/orders/1", headers=acme).json())
print("acme gets #2 :", c.get("/v1/orders/2", headers=acme).status_code, "(globex's row: same 404 as missing)")Make the invisible visible: Real output.
acme list : ['acme order']
acme gets #1 : acme order
acme gets #2 : 404 (globex's row: same 404 as missing)What you see: Tenant acme lists only its own order and reads order 1. Asking for order 2, which belongs to globex, gives 404, the same answer as a missing row. The demo takes the tenant from a header named after "verified token" to stay short; real code reads it from a validated JWT claim.
Filter by hand
One forgotten where clause is a breach.
def orders(s):
# ❌ someone forgets tenant_id
return s.scalars(select(Order)).all()Repository owns the filter
No unscoped query exists.
class TenantRepo:
def __init__(self, tenant_id):
self.t = tenant_id
def orders(self, s):
return s.scalars(select(Order).where(
Order.tenant_id == self.t)).all()The shift: Make the safe query the only query available.
Land it Shared tables with a tenant id from the verified token, a repository that always filters, row-level security as a second wall, tenant-aware caches and jobs, and per-tenant rate limits and isolation tests.
- "How does row-level security work with SQLAlchemy?"
-
Because the wall is placed where mistakes cannot get past it. Application filters depend on every developer remembering them in every query, forever. Row-level security (RLS) is enforced by PostgreSQL itself on every query.
- Policy: on each table,
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;and a policy such asUSING (tenant_id = current_setting('app.tenant_id')::uuid). Rows of other tenants become invisible. - Setting per transaction: when the request starts its transaction, run
SET LOCAL app.tenant_id = :t, with the value taken from the verified token.SET LOCALlasts only until the end of that transaction. - The right role: the application's database role must not own the tables and must not have
BYPASSRLS, or the policies are skipped.
With this, a query that forgot its
WHERE tenant_idstill returns only that tenant's rows. BecauseSET LOCALends with the transaction, it is also safe with PgBouncer in transaction mode, as no setting leaks to the next client.I still keep the repository filter. The filter gives clear queries and good index use, and RLS catches the mistakes.
- Policy: on each table,
- "How do you handle tenants of very different sizes?"
-
I start everyone in the shared tables, because that is cheapest, and I keep a way to move the few tenants who outgrow it. Sizes follow a steep curve, where a handful of tenants produce most of the load.
The signals to move a tenant are concrete: its queries dominate the database's load and slow others (the noisy neighbour problem), a contract demands data in a specific region or separate encryption keys, or its data is so large that it distorts indexes and backups.
The mechanism is a small routing table that maps
tenant_idto a database URL. A dependency reads the tenant from the token, looks up the URL, and returns the engine for that tenant, from a dictionary of engines created at start-up or on first use. All the code below that point just asks for a session and does not care which database it is.So design from the beginning with one function,
engine_for(tenant), even while it returns the same engine for everyone. Moving a tenant is then a data copy, a switch in the routing table and a short freeze of writes, and the application code does not change. Remember that each extra database means extra migrations and connection pools. - "How do you onboard, offboard and export a tenant?"
-
I treat these three as tenant lifecycle features, and plan them from the start, because with shared tables they are all operations by key.
- Onboarding: create the tenant row, default roles and settings, an organisation in the identity provider, and quotas, all in one idempotent routine, so a retry after a half-failed signup is safe.
- Export: a background job reads every table by
tenant_idand writes an archive, for example a zip of JSON or CSV files, to object storage, with an expiring download link. It runs in batches, not as one giant query. - Offboarding: delete or anonymise by tenant id, in batches, with an audit record of what was deleted and when. Legal rules may require a grace period, and also deletion from backups and caches within a stated time.
This is why the tenant id column comes first in composite indexes, such as
(tenant_id, created_at): both the normal queries and these bulk operations use it. Test the export and the deletion on a copy, as these jobs are used rarely and break unnoticed. - "What about analytics and reporting across tenants?"
-
I keep cross-tenant analytics away from the product database and the request path. A query across all tenants in the same database where tenant isolation is the main security property is risky, since one wrong parameter exposes everyone's data.
The safe pattern is a copy. Replicate or stream the data to a warehouse, which is a separate system built for analytics, such as a columnar store. There, only staff roles have access, access is logged, and the data can be reduced: drop or hash personal fields that analysts do not need, for example customer names and addresses, and keep what they need, such as order totals and timestamps.
Per-tenant reports, for a customer who wants to see their own numbers, are a different matter. They run with the same tenant context and RLS as everything else, perhaps on a read replica, and they pass through the same tests.
The rule I give the team: if a query has no tenant filter, it does not run in the product database. It runs in the warehouse, by a person with the right role, and with the access logged.
Q150 · Design. "Whiteboard the QuickBite orders API end to end — from the load balancer to the database to the event stream."
Reveal answer
Strong answer I draw the path of one request and then the path of its consequences, and name the failure behaviour at every box.
Edge: clients reach a CDN and load balancer that terminate TLS, apply a coarse rate limit and enforce a body size limit. They forward to an API gateway that checks CORS policy and routes /v1/orders to the orders service. Service: Kubernetes pods running uvicorn (one or two workers each), with readiness and startup probes, graceful shutdown and a pod disruption budget.
Inside a pod: the request-id middleware, then the router, then dependencies (token validation and scope, a request-scoped SQLAlchemy session), then the service layer that checks the idempotency key, atomically decrements stock with a conditional update, inserts the order, its lines and an outbox row in one transaction, and commits. A Problem Details handler turns any error into a standard response with the request id.
Data: PostgreSQL through PgBouncer, with small per-pod pools and a replica for read-only routes. Events: a relay (or change data capture) reads the outbox and publishes order.created to Kafka; consumers (notifications, dispatch, analytics) are idempotent. Observability: structured logs with the request id, RED metrics, OpenTelemetry traces and SLO alerts.
Picture it The whole picture in one block, followed by the real test totals of the canonical app that implements the middle of it.
# illustrative
client -> CDN/LB (TLS, size limit, coarse rate limit)
-> gateway (CORS, routing, auth-lite)
-> pod: uvicorn
request-id middleware
router -> Depends(token, scope, session)
OrderService.create_order:
idempotency key -> stored reply? return it
UPDATE stock ... WHERE stock >= qty (atomic)
INSERT order, lines, outbox (one tx)
problem+json handlers, /healthz /readyz
-> PgBouncer -> PostgreSQL (primary; replica for reads)
outbox -> relay/CDC -> Kafka: order.created
consumers: notify, dispatch, analytics (idempotent)
signals: JSON logs + request id | RED metrics | tracesReason:
('/home/iam100god/Desktop/AI_COURSE/code/e20-python-api/quickbite_api/tests/test
_postgres.py', 24, 'Skipped: set QUICKBITE_TEST_PG_URL to run')
44 passed, 1 skipped, 1 warning in 3.73sWhy: The service layer in the middle of the diagram is the canonical app: its 44 passing tests (and 45 against a real PostgreSQL 18 container, including 8 threads buying 5 items with five 201 responses, three 409 and stock zero) cover validation, auth, idempotency, stock, pagination and error shapes.
Happy path only
Looks fine until the first failure.
client -> API -> DB -> 201
# ❌ no retry story, no events,
# no idea what happens on a crashWith failure behaviour
Every box has a plan.
retry+key | atomic stock | outbox
timeouts | pool limits | drain
alerts | request id | replayThe shift: Draw the failure for each box, not only the success.
Land it One request is validated, authorised, deduplicated by an idempotency key, committed atomically with an outbox row, answered in problem-details form, and its event is published later by a relay to idempotent consumers, with timeouts, limits and observability at every hop.
- "What happens if the pod dies after the commit but before the response?"
-
The client gets the same order back, and nothing is duplicated. This is exactly the failure that the idempotency key and the transaction were designed for.
Walk through it. The pod runs the transaction: it checks the key, decrements stock, inserts the order, its lines, the idempotency record with the response, and an outbox row, then commits. The pod dies before the response is sent. The client sees a timeout or a connection reset and does not know what happened.
The client retries with the same
Idempotency-Keyand the same body. A different pod receives it, looks up the key and finds the stored record, and returns the saved response, which is a 200 with the same order and anIdempotent-Replayed: trueheader. Stock is not decremented again. If the retry came with the same key but a different body, the service answers 422, because that is a client bug.The outbox row was in the same transaction, so it is in the database too, and the relay publishes
order.createdas usual. Nothing was lost and nothing doubled. - "What if Kafka is down?"
-
Orders still succeed, because the API's only dependency on Kafka is through the outbox table, and that is a database table. This is the main reason for the pattern.
What happens in the system: the relay tries to publish and fails, it waits and retries with exponential backoff (for example 1 s, 2 s, 4 s up to a limit), and the unsent rows stay in the outbox. Notifications, dispatch and analytics get no new events, so they are late, but no order is lost, and customers can still order.
The backlog grows, and I watch it with an alert on the age of the oldest unsent row, for example above 5 minutes. It is the number that says how late the consumers are. A table that grows for a few hours is a small cost, but I also watch its size.
When Kafka recovers, the relay drains the backlog. If it publishes in order of the outbox id, and uses the order id as the message key, events for one order arrive in sequence. Consumers handle repeats, since the relay may publish a row twice after a crash.
- "Where is the consistency boundary?"
-
The boundary is the database transaction, and I say so explicitly in an interview. Inside it, everything is strongly consistent. Outside it, everything is eventually consistent.
Inside the transaction are the things where being wrong costs money or trust: the stock decrement, the order row, its lines, the idempotency record and the outbox row. They commit together or not at all, so there is never an order without its stock reservation, or an order without its pending event.
Outside are the consequences: the Kafka event, the confirmation email, the dispatch of a rider, the analytics. They happen after the commit, driven by the outbox, and may be seconds late, or retried. A customer may see "order placed" a moment before the email arrives, and that is acceptable.
The design question I ask for each new feature is: which side of the line does it belong on? If a feature cannot tolerate a delay or a repeat, it must either join the transaction or be redesigned. Be strict about keeping the transaction short: no network calls to other services inside it, since a slow call there holds a connection and locks.
- "What would you scale first under load?"
-
I measure first, then work down a list ordered by cost and risk, since the first bottleneck is usually not the one people guess.
- More pods: the pods are stateless, so adding them is easy and quick, until the database becomes the limit.
- Caching and replicas: menu data changes rarely and is read constantly, so cache it. Send list routes to a read replica.
- Connections: PgBouncer and pool limits, because pods times pool size can exceed
max_connections(Q143). - Partitioning: split the orders table by time once it is very large, so recent data stays small and old data can be archived.
Two bottlenecks appear first in practice. The connection budget is the first, and it is shown by pool wait time and the connection count in the database. The second is a hot row: one very popular menu item, whose stock row is updated by every order, so updates queue on one lock. Throughput is then limited by the speed of that single row, and the fixes are shorter transactions, stock reserved in chunks, or a queue in front of that item.
12 · RecapWhat You Can Do Now
- You can explain how a request travels from socket to handler through uvicorn, middleware and the dependency graph, and state the rule that decides between
defandasync def, including the 40-thread pool behind plaindef - You can model data at the boundary with Pydantic v2: separate request, response and ORM models, constrained
Annotatedtypes, discriminated unions, exclude_unset for PATCH, and settings that fail at start-up - You can structure a service as routers, services and repositories, wire it with
Dependsand lifespan, and replace any seam in tests withdependency_overrides - You can run SQLAlchemy 2.x safely: one session per request, eager loading against N+1, atomic stock updates, optimistic locking, idempotency keys and the pool-size formula pods x workers x (pool + overflow)
- You can validate a JWT with every check (algorithm allow-list, signature, exp, nbf, iss, aud, required claims), authorise by scope and by ownership so that another customer's order is a 404, and return RFC 9457 problems that never leak a trace
- You can use HTTP precisely: 201 with Location, 202 with a status resource, 409, 422, 429 with Retry-After, ETag with If-Match and 412, cursor pagination, UTC with offsets and integer cents
- You can test with a clean database per test and a token factory, explain what SQLite hides, and read load-test percentiles, event-loop lag and profiler output to find where time really goes
- You can ship it: multi-stage uv Dockerfile, non-root user, separate liveness, readiness and startup probes, graceful shutdown with a preStop sleep, an outbox for work that must survive a deploy, and expand-and-contract migrations
Close the page and write down, from memory: the rule for def versus async def with the thread-pool number, the checks a JWT must pass before you trust it, and the connection-pool formula with a worked example for 20 pods. Then reach back to Chapter E4: Spring's @Transactional wraps a method in a proxy that commits or rolls back. Which part of the FastAPI stack plays that role with a yield dependency, and what do you give up by not having the proxy?
13 · SummaryAll 26 Idioms on One Page
Every idiom in this chapter, each with the problem it solves and the solution in one line. Click an idiom name to jump to its full breakdown.
02 · ASGI, servers and the event loop
| Idiom | Problem | Solution |
|---|---|---|
| def versus async def | A blocking call inside async def freezes every request in the worker. | Use async def only when everything awaited is non-blocking; otherwise plain def (40-thread pool) or run_in_threadpool. |
| Middleware onion | Cross-cutting code runs in a surprising order, or consumes the body so the endpoint hangs. | Know that the last-added middleware runs first; prefer pure ASGI middleware and read bodies in dependencies. |
| Workers sizing | One process uses one core while the rest sit idle, or too many workers exhaust the database. | About one worker per core for I/O APIs, and budget connections as workers times pods times pool size. |
03 · Validation and serialisation with Pydantic v2
| Idiom | Problem | Solution |
|---|---|---|
| Separate in and out models | Returning an ORM object leaks internal fields such as password_hash. | Use a request model, a response model and the ORM model; always declare response_model. |
| Annotated constraints | The same range check is copied into many models and drifts. | Define reusable types such as Qty = Annotated[int, Field(gt=0, le=50)]. |
| Discriminated union | A payload with several shapes gives vague, slow validation errors. | Use Field(discriminator="type") so one tag picks the model and errors point at it. |
| Settings object | Configuration is scattered through the code and bad values fail late. | One BaseSettings class, cached with lru_cache, with SecretStr for secrets, validated at start. |
04 · Dependency injection, lifespan and structure
| Idiom | Problem | Solution |
|---|---|---|
| Yield dependency | Resources such as sessions are not closed or rolled back when the endpoint fails. | Put setup before yield and commit, rollback and close in try, except and finally after it. |
| Lifespan resources | Creating a client or engine per request exhausts sockets and connections. | Create shared resources once in the lifespan, keep them on app.state and close them on shutdown. |
| Dependency override | Tests hit real databases, identity providers or mailers. | Replace a dependency with app.dependency_overrides for the app under test. |
| Layered structure | Business rules in endpoints cannot be reused or tested. | Routers handle HTTP, services hold rules and transactions, repositories hold queries. |
05 · Persistence, transactions, migrations and idempotency
| Idiom | Problem | Solution |
|---|---|---|
| Session per request | Shared sessions leak state between requests and threads. | One session per request from a yield dependency; the service owns the commit. |
| Eager load | Lazy loading issues one query per row (51 queries for 50 orders). | Use selectinload or joinedload to fetch related rows in one or two statements. |
| Expand and contract migration | A schema change breaks the old version during a rolling deploy. | Add compatibly, dual-write and backfill, switch reads, then enforce and drop in a later release. |
| Idempotency key | Client retries create duplicate orders. | Store the key with a request hash and the response; replay the stored result for the same key and body. |
| Pool sizing | The fleet opens more connections than the database allows. | Budget pods x workers x (pool + overflow) below max_connections, and use a pooler. |
06 · Authentication, authorisation, errors and behaviour
| Idiom | Problem | Solution |
|---|---|---|
| Verify the JWT | Forged or replayed tokens are accepted when checks are skipped. | Algorithm allow-list, signature, exp, nbf, iss, aud and required claims, with keys from JWKS. |
| Auth dependency | Authorisation is scattered and one route is forgotten; users read each other's data. | A get_current_user dependency, scope factories and ownership filters in the repository. |
| Problem Details | Every endpoint returns errors in a different shape, sometimes with traces. | RFC 9457 application/problem+json from registered handlers, including a catch-all. |
| Cursor pagination | Offset pages skip or repeat rows when data changes, and get slow. | An opaque cursor of the last row's sort key, stable ordering and a capped limit. |
| Partial update | PATCH overwrites omitted fields with null. | Apply model_dump(exclude_unset=True) to a patch model that forbids extra fields. |
07 · Testing, background work, observability and deployment
| Idiom | Problem | Solution |
|---|---|---|
| ASGI transport tests | Tests that start real servers are slow and flaky. | Call the app in-process with TestClient or AsyncClient(ASGITransport), with overrides and a fresh database per test. |
| Request id middleware | Interleaved async logs cannot be traced to one request. | Pure ASGI middleware sets a ContextVar; the log processor adds it to every line and the response. |
| Durable background jobs | BackgroundTasks are lost on deploy or crash and never retried. | Write an outbox row in the transaction and let an idempotent worker or queue retry. |
| Graceful shutdown | Deploys cut in-flight requests. | Readiness flips, a preStop sleep, uvicorn drains within a timeout shorter than the pod grace period. |
| uv multi-stage Docker | Images are huge, slow to rebuild and run as root. | Build with uv sync --frozen in one stage, ship a slim non-root runtime with an exec-form command. |