← Interview prep

FastAPI interview questions

Async APIs, dependency injection, and FastAPI production patterns.

100 questions · Page 5 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 5 of 5

Questions 81–100 of 100 · 0 of 20 on this page marked learned

81.fastapi-0081Mediummid

How do you customise the OpenAPI schema in FastAPI: operation IDs, tag metadata, examples, hidden routes and a custom openapi() function?

FastAPI builds the schema from your code, and you shape it with parameters: tags and openapi_tags for grouping and descriptions, summary and description (or docstrings), operation_id or generate_unique_id_function for stable client method names, responses for extra status codes, examples through Field(examples=...) or json_schema_extra, deprecated=True, include_in_schema=False, and an overridden app.openapi() for global changes such as servers or security schemes.

Full answer

Why it matters: the OpenAPI document is the contract for docs, SDK generators and tests. Default operation IDs look like read_students_students__get, which produce ugly generated client methods.

Tools:

  • Tags: tags=["students"] groups endpoints. Describe tags once with FastAPI(openapi_tags=[{"name": "students", "description": "Student records"}]).
  • summary, description, and the function docstring (rendered as Markdown) fill the docs. response_description documents the success body.
  • Stable operation IDs: set operation_id="list_students" per route, or a global generator: FastAPI(generate_unique_id_function=lambda r: f"{r.tags[0]}-{r.name}"). Generated clients then expose StudentsService.listStudents() instead of a long auto name.
  • Examples: Field(examples=["BCA-17"]), model_config = ConfigDict(json_schema_extra={"examples": [...]}), and Body(examples=[...]), Query(examples=[...]) for parameters. They show up in /docs and in generated mock servers.
  • Extra responses: responses={404: {"model": Problem}, 409: {"description": "Duplicate"}}.
  • deprecated=True strikes the route in docs. include_in_schema=False hides internal routes (health, admin).
  • openapi_extra={...} merges arbitrary keys into one operation (for example x-codegen hints).
  • Global change: override the function, cache the result and add servers, security schemes or info.x-logo:
python
def custom_openapi():
    if app.openapi_schema: return app.openapi_schema
    schema = get_openapi(title=app.title, version=app.version, routes=app.routes)
    schema["servers"] = [{"url": "https://api.schoolabe.example"}]
    app.openapi_schema = schema
    return schema
app.openapi = custom_openapi
  • Disable docs in production if the API is private: FastAPI(docs_url=None, redoc_url=None, openapi_url=None).

Pin the schema in CI (snapshot tests) so accidental contract changes are caught.

python
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.routing import APIRoute
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field


def unique_id(route: APIRoute) -> str:
    return f"{route.tags[0]}_{route.name}" if route.tags else route.name


app = FastAPI(
    title="Campus API",
    version="1.4.0",
    openapi_tags=[{"name": "students", "description": "Student records"}],
    generate_unique_id_function=unique_id,
)


class Student(BaseModel):
    model_config = ConfigDict(json_schema_extra={"examples": [{"roll_no": "BCA-17", "name": "Asha Rao"}]})
    roll_no: str = Field(examples=["BCA-17"], description="Unique roll number")
    name: str


class Problem(BaseModel):
    title: str
    status: int


@app.get("/students", tags=["students"], summary="List students", responses={404: {"model": Problem}})
def list_students() -> list[Student]:
    """Return every student.\n\nSupports **Markdown** in the description."""
    return []


@app.post("/students", tags=["students"], operation_id="enrol_student", status_code=201)
def create_student(student: Student) -> Student:
    return student


@app.get("/old", tags=["students"], deprecated=True)
def old():
    return {}


@app.get("/healthz", include_in_schema=False)
def healthz():
    return {"ok": True}


def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    schema = get_openapi(title=app.title, version=app.version, routes=app.routes, tags=app.openapi_tags)
    schema["servers"] = [{"url": "https://api.schoolabe.example"}]
    app.openapi_schema = schema
    return schema


app.openapi = custom_openapi

schema = TestClient(app).get("/openapi.json").json()
print(sorted(schema["paths"]))
print({f"{m} {p}": op["operationId"] for p, item in schema["paths"].items() for m, op in item.items()})
print(schema["paths"]["/old"]["get"]["deprecated"], schema["servers"], schema["tags"][0]["name"])
print(schema["components"]["schemas"]["Student"]["examples"], sorted(schema["paths"]["/students"]["get"]["responses"]))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): ['/old', '/students'] {'get /students': 'students_list_students', 'post /students': 'enrol_student', 'get /old': 'students_old'} True [{'url': 'https://api.schoolabe.example'}] students [{'name': 'Asha Rao', 'roll_no': 'BCA-17'}] ['200', '404']

Key points

  • Tags, summaries and docstrings organise the docs
  • Stable operation IDs give clean generated client method names
  • Examples via Field, Body and json_schema_extra
  • include_in_schema=False and deprecated=True control visibility
  • Override app.openapi() for servers and security schemes

Common mistakes

  • Shipping default operation IDs and getting unreadable generated clients
  • Exposing internal routes in the public schema
  • Documenting 404 and 409 responses with models but never returning those shapes
  • Changing the schema accidentally without a snapshot test
  • Leaving docs enabled on private production APIs

Follow-ups

  • How do generated clients use operationId?
  • How do you add a security scheme globally?
  • How do you version the OpenAPI document?

Tips

  • Show an operation ID strategy
  • List 4 customisation parameters
  • Mention snapshot tests
82.fastapi-0082Mediummid

How do you version a FastAPI API with routers and prefixes, and how do you deprecate old versions with Deprecation and Sunset headers?

The most common scheme is a URL prefix per major version (/v1, /v2), each in its own APIRouter, sharing services and with version-specific request and response schemas. Alternatives are a header or media type. Deprecate old versions by marking routes deprecated=True (visible in docs) and sending Deprecation and Sunset headers (and a Link to migration docs) so clients can detect retirement dates. Only create a new version for breaking changes.

Full answer

Structure:

app/ api/ v1/routes.py # router_v1 = APIRouter(prefix="/v1", tags=["v1"]) v2/routes.py # router_v2 = APIRouter(prefix="/v2", tags=["v2"]) services/ # business logic shared by both schemas/v1.py, schemas/v2.py

Each router maps requests to the same service layer, converting to and from version-specific schemas. This keeps old behaviour stable without copying business logic.

When to bump a version: removing or renaming fields, changing types or meanings, tightening validation, changing error formats or status codes. Adding optional fields or new endpoints is backward compatible (clients must ignore unknown fields: document that).

Schemes:

  • URL path (/v2/students): visible, cacheable, easy to route at a gateway, simple to test with curl. Most common.
  • Header (X-API-Version: 2) or media type (Accept: application/vnd.schoolabe.v2+json): cleaner URLs, but harder for caches and casual testing.
  • Date-based versions (Stripe style) pin each client to the behaviour at its integration date: powerful but needs infrastructure.

Deprecation process:

  1. Announce the plan with dates; mark routes deprecated=True so /docs strikes them through.
  2. Send headers on every response of the old version: Deprecation: true (or a date), Sunset: Wed, 01 Jul 2027 00:00:00 GMT (RFC 8594) and Link: <https://docs...>; rel="deprecation". A router-level dependency or middleware can add them.
  3. Track usage per version and per client; contact heavy users.
  4. After the sunset date return 410 Gone with a problem document pointing to the new version, then delete.

Keep live versions to two or three, and test all of them in CI.

python
from fastapi import APIRouter, Depends, FastAPI, Response
from fastapi.testclient import TestClient
from pydantic import BaseModel

SERVICE_DB = [{"first": "Asha", "last": "Rao", "roll_no": "BCA-17"}]       # shared business data


def deprecation_headers(response: Response):
    response.headers["Deprecation"] = "true"
    response.headers["Sunset"] = "Thu, 01 Jul 2027 00:00:00 GMT"
    response.headers["Link"] = '<https://docs.schoolabe.example/migrate-v2>; rel="deprecation"'


class StudentV1(BaseModel):
    name: str
    roll_no: str


class StudentV2(BaseModel):
    first_name: str
    last_name: str
    roll_no: str


v1 = APIRouter(prefix="/v1", tags=["v1"], dependencies=[Depends(deprecation_headers)], deprecated=True)
v2 = APIRouter(prefix="/v2", tags=["v2"])


@v1.get("/students", response_model=list[StudentV1])
def students_v1():
    return [{"name": f"{s['first']} {s['last']}", "roll_no": s["roll_no"]} for s in SERVICE_DB]


@v2.get("/students", response_model=list[StudentV2])
def students_v2():
    return [{"first_name": s["first"], "last_name": s["last"], "roll_no": s["roll_no"]} for s in SERVICE_DB]


app = FastAPI()
app.include_router(v1)
app.include_router(v2)

c = TestClient(app)
r1, r2 = c.get("/v1/students"), c.get("/v2/students")
print(r1.json(), r1.headers.get("deprecation"), r1.headers.get("sunset"))
print(r2.json(), r2.headers.get("deprecation"))
schema = c.get("/openapi.json").json()["paths"]
print({p: item["get"].get("deprecated", False) for p, item in schema.items()})

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): [{'name': 'Asha Rao', 'roll_no': 'BCA-17'}] true Thu, 01 Jul 2027 00:00:00 GMT [{'first_name': 'Asha', 'last_name': 'Rao', 'roll_no': 'BCA-17'}] None {'/v1/students': True, '/v2/students': False}

Key points

  • Router per major version, shared service layer
  • Version only for breaking changes
  • deprecated=True plus Deprecation and Sunset headers
  • Track version usage before retiring
  • After sunset return 410 Gone with migration info

Common mistakes

  • Creating a new version for every small change
  • Copying business logic into each version
  • Removing a version without notice or usage data
  • Not telling clients to ignore unknown fields
  • Leaving old versions untested

Follow-ups

  • How would you route versions at an API gateway?
  • How does date-based versioning work?
  • How do you handle breaking changes in error formats?

Tips

  • Explain router per version
  • Name the deprecation headers
  • State when to bump a version
83.fastapi-0083Mediummid

How do you handle datetimes with time zones, Decimals and custom JSON encoding correctly in Pydantic v2 and FastAPI?

Use timezone-aware datetimes (AwareDatetime type, or store UTC) so comparisons are unambiguous, accept ISO 8601 strings with offsets, and convert to the user's zone only at the edges. Use Decimal for money with max_digits and decimal_places constraints; Pydantic v2 serialises Decimal as a JSON string through a response model, which preserves exactness. Customise output with field_serializer or Annotated serializers, and note that naive datetimes serialise without an offset.

Full answer

Datetimes:

  • A naive datetime has no zone (2026-12-04T10:00:00); an aware one carries an offset (+05:30) or Z. Mixing them raises TypeError when compared.
  • Pydantic types: datetime (either), AwareDatetime (offset required), NaiveDatetime. For APIs, require AwareDatetime and normalise to UTC in your service: value.astimezone(timezone.utc).
  • JSON output is ISO 8601 with offset (2026-12-04T04:30:00Z for UTC). Clients convert to local time.
  • Store timestamps in UTC (timestamptz in PostgreSQL); keep the user's IANA zone name (Asia/Kolkata) separately if you need local-time features. Use zoneinfo.ZoneInfo, not fixed offsets, for daylight-saving aware conversion.
  • "Dates" like a birthday are date, not datetime, to avoid zone shifts.

Decimals:

  • Decimal avoids binary float errors (0.1 + 0.2). Constrain: Field(max_digits=10, decimal_places=2).
  • Input accepts JSON numbers or strings; sending strings ("199.90") avoids client-side float rounding.
  • Output through a response model is a JSON string by default ("199.90"), which JavaScript clients must parse; a plain dict without a model passes through jsonable_encoder and becomes a float, losing exactness.
  • Do arithmetic with Decimal and quantise explicitly (.quantize(Decimal("0.01"), ROUND_HALF_UP)) at defined points.
  • Store as NUMERIC in the database; many ORMs map it to Decimal.

Custom encodings:

  • Annotated[Decimal, PlainSerializer(lambda v: float(v), return_type=float)] forces numbers (accepting precision loss).
  • field_serializer formats a datetime for display.
  • ConfigDict(ser_json_timedelta="iso8601", ser_json_bytes="base64") and json_encoders (deprecated in v2) control other types.

Test around month ends, leap days and DST changes, and always include the offset in test data.

python
from datetime import datetime, timezone
from decimal import ROUND_HALF_UP, Decimal
from zoneinfo import ZoneInfo

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import AwareDatetime, BaseModel, Field, ValidationError

app = FastAPI()


class Payment(BaseModel):
    paid_at: AwareDatetime
    amount: Decimal = Field(max_digits=10, decimal_places=2, gt=0)


class Receipt(BaseModel):
    paid_at_utc: datetime
    amount: Decimal


@app.post("/payments", response_model=Receipt)
def pay(p: Payment):
    gst = (p.amount * Decimal("0.18")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return {"paid_at_utc": p.paid_at.astimezone(timezone.utc), "amount": p.amount + gst}


c = TestClient(app)
r = c.post("/payments", json={"paid_at": "2026-12-04T10:00:00+05:30", "amount": "199.90"})
print(r.status_code, r.text)
print(c.post("/payments", json={"paid_at": "2026-12-04T10:00:00", "amount": "199.90"}).json()["detail"][0]["type"])
print(c.post("/payments", json={"paid_at": "2026-12-04T10:00:00Z", "amount": "10.999"}).json()["detail"][0]["type"])

print(0.1 + 0.2, Decimal("0.1") + Decimal("0.2"))
local = datetime(2026, 12, 4, 10, 0, tzinfo=ZoneInfo("Asia/Kolkata"))
print(local.isoformat(), local.astimezone(timezone.utc).isoformat(), local.astimezone(ZoneInfo("America/New_York")).isoformat())
try:
    datetime(2026, 1, 1) < local
except TypeError as exc:
    print("naive vs aware:", exc)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 {"paid_at_utc":"2026-12-04T04:30:00Z","amount":"235.88"} timezone_aware decimal_max_places 0.30000000000000004 0.3 2026-12-04T10:00:00+05:30 2026-12-04T04:30:00+00:00 2026-12-03T23:30:00-05:00 naive vs aware: can't compare offset-naive and offset-aware datetimes

Key points

  • Aware datetimes with offsets; store UTC, convert at the edges
  • AwareDatetime rejects naive input
  • Decimal for money with max_digits and decimal_places
  • Through a response model Decimal becomes a string; bare dicts give floats
  • Use serializers for custom output; avoid deprecated json_encoders

Common mistakes

  • Using naive datetimes in an API and guessing the zone later
  • Using float for currency
  • Storing local times without a zone
  • Returning Decimal in a bare dict and getting a float
  • Using fixed offsets instead of IANA zones for daylight saving

Follow-ups

  • How do you store a user's preferred time zone?
  • How do you format Decimal as a number in JSON when needed?
  • What breaks around daylight-saving changes?

Tips

  • State UTC at the edges
  • Say Decimal with constraints
  • Mention serialization differences
84.fastapi-0084Mediummid

How do you implement safe filtering and sorting parameters (?sort=-score,name) in a FastAPI endpoint with a dependency and an allow-list?

Parse the sort string in a dependency, validate every field against a whitelist that maps public names to real columns, and build the SQLAlchemy ORDER BY from those column objects, never from raw strings. Return 422 for unknown fields. Filters follow the same idea: a Pydantic model of allowed filters turns query parameters into typed conditions. This prevents SQL injection, slow sorts on unindexed columns and leaking internal column names.

Full answer

Naively interpolating order_by(text(sort)) lets clients inject SQL or sort by columns that are unindexed, private (password_hash) or expensive.

Design:

  1. Define the public contract: sort fields name, score, joined, with - prefix for descending and comma-separated for multiple keys. Default sort is deterministic (include id as a tie-breaker, otherwise paginated results can repeat or skip rows).
  2. Map public names to column objects: SORTABLE = {"name": Student.name, "score": Student.score}.
  3. A dependency parses and validates:
python
def sort_params(sort: Annotated[str, Query(pattern=r"^-?\w+(,-?\w+)*$", max_length=50)] = "name") -> list[ColumnElement]:
    clauses = []
    for part in sort.split(","):
        desc = part.startswith("-")
        name = part.lstrip("-")
        if name not in SORTABLE:
            raise HTTPException(422, f"Cannot sort by {name!r}. Allowed: {sorted(SORTABLE)}")
        clauses.append(SORTABLE[name].desc() if desc else SORTABLE[name].asc())
    return clauses
  1. The endpoint applies select(Student).order_by(*clauses, Student.id).

Filters: group them in a Pydantic model used as Annotated[StudentFilters, Query()] (FastAPI 0.115+) with typed fields (min_score: int | None, grade: Literal["A", "B", "C"] | None, name_contains: str | None) and apply each non-None field as a condition. extra="forbid" on the model rejects unknown parameters, but it applies to every query parameter of that endpoint, so sort and pagination must then be fields of the same model; without it, unknown parameters are silently ignored.

Performance and safety:

  • Sortable and filterable columns should be indexed (composite indexes for common combinations), or the database sorts large tables on every request.
  • Cap page size and total number of sort keys.
  • Escape LIKE wildcards in user text (% and _) if you build ilike patterns.
  • Document allowed fields in the parameter description or as an enum for clients.
  • Use keyset pagination with the same sort keys for large tables.
python
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel
from sqlalchemy import ColumnElement, create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.pool import StaticPool


class Base(DeclarativeBase):
    pass


class Student(Base):
    __tablename__ = "student"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    score: Mapped[int]
    password_hash: Mapped[str] = mapped_column(default="x")


engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
with Session(engine) as s:
    s.add_all([Student(name=n, score=v) for n, v in [("Asha", 91), ("Ravi", 58), ("Kiran", 74), ("Meera", 74)]])
    s.commit()

SORTABLE = {"name": Student.name, "score": Student.score}
app = FastAPI()


def sort_params(sort: Annotated[str, Query(pattern=r"^-?\w+(,-?\w+)*$", max_length=50)] = "name") -> list[ColumnElement]:
    clauses = []
    for part in sort.split(","):
        name = part.lstrip("-")
        if name not in SORTABLE:
            raise HTTPException(status_code=422, detail=f"Cannot sort by {name!r}. Allowed: {sorted(SORTABLE)}")
        clauses.append(SORTABLE[name].desc() if part.startswith("-") else SORTABLE[name].asc())
    return clauses


class Filters(BaseModel):
    min_score: int | None = None
    name_contains: str | None = None


@app.get("/students")
def students(order: Annotated[list[ColumnElement], Depends(sort_params)], f: Annotated[Filters, Query()]):
    stmt = select(Student.name, Student.score)
    if f.min_score is not None:
        stmt = stmt.where(Student.score >= f.min_score)
    if f.name_contains:
        escaped = f.name_contains.replace("%", r"\%").replace("_", r"\_")
        stmt = stmt.where(Student.name.ilike(f"%{escaped}%", escape="\\"))
    with Session(engine) as db:
        return [{"name": n, "score": v} for n, v in db.execute(stmt.order_by(*order, Student.id))]


c = TestClient(app)
print(c.get("/students?sort=-score,name").json())
print(c.get("/students?sort=name&min_score=70&name_contains=ra").json())
print(c.get("/students?sort=password_hash").status_code, c.get("/students?sort=name;DROP TABLE student").status_code)
print(c.get("/students?min_score=1&bogus=1").status_code, "(unknown filters are ignored unless the model forbids extras)")
print(c.get("/students?min_score=abc").json()["detail"][0]["type"])

Standalone script. Run it with `python file.py`; it uses an in-memory SQLite database and TestClient. Grouping query parameters in a Pydantic model needs FastAPI 0.115 or later. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): [{'name': 'Asha', 'score': 91}, {'name': 'Kiran', 'score': 74}, {'name': 'Meera', 'score': 74}, {'name': 'Ravi', 'score': 58}] [{'name': 'Kiran', 'score': 74}, {'name': 'Meera', 'score': 74}] 422 422 200 (unknown filters are ignored unless the model forbids extras) int_parsing

Key points

  • Whitelist maps public names to real column objects
  • Never pass user strings to order_by(text(...))
  • Add id as a tie-breaker for stable pagination
  • Group filters in a typed Pydantic query model
  • Index sortable columns; cap page and key counts

Common mistakes

  • Passing user strings into order_by(text(...))
  • Allowing sort by unindexed or private columns
  • Omitting a unique tie-breaker so pages repeat or skip rows
  • Not escaping LIKE wildcards in user search text
  • Unbounded numbers of sort keys or page sizes

Follow-ups

  • How would you combine this with keyset pagination?
  • How do you expose allowed sort fields in OpenAPI?
  • How would you filter on related tables safely?

Tips

  • Describe the whitelist mapping
  • Mention the tie-breaker
  • Say index the sort columns
85.fastapi-0085Hardsenior

How do you design an API for long-running jobs in FastAPI using 202 Accepted, status polling and idempotency keys?

Accept the request, validate it, create a job record, hand the work to a worker, and return 202 Accepted with a Location header pointing to a job status resource. Clients poll that resource (or receive a webhook) until it reports succeeded or failed with a result link. An Idempotency-Key header lets clients retry the POST safely: the same key returns the same job instead of starting duplicate work. Production workers should be a queue such as Celery, ARQ or a database-backed worker.

Full answer

Request-response APIs should not hold HTTP connections open for minutes: proxies time out, clients retry, and workers get tied up.

Resource flow:

  1. POST /reports validates input, creates a job row (id, status=queued, created_at, owner, idempotency_key), enqueues work, and returns 202 Accepted with Location: /jobs/{id} and a body like {"id": ..., "status": "queued"}. Optionally include Retry-After.
  2. GET /jobs/{id} returns status (queued, running, succeeded, failed), progress, timestamps, error details, and on success a link to the result (/reports/{id}/download). A finished job may answer 303 See Other to the result.
  3. DELETE /jobs/{id} or POST /jobs/{id}/cancel cancels if possible.
  4. Optional push: webhook or Server-Sent Events for status changes, with polling still available.

Idempotency: clients on flaky networks retry the POST. With an Idempotency-Key header, store (owner, key) -> job_id with a unique constraint; if the key is seen, return the original job with the same status code (and reject reuse of a key with a different payload using 422 or 409). Expire keys after a day or so.

Workers: BackgroundTasks and in-process thread pools disappear on restart and cannot scale out. Use Celery, ARQ, RQ or Dramatiq with a persistent broker, make tasks idempotent, write status transitions to the database, add retries with backoff and a dead-letter strategy, and set time limits. Enqueue after commit (or via an outbox) to avoid workers seeing a missing job.

Details: authorise job reads (owner check), do not leak other users' job IDs, use unguessable IDs, rate-limit job creation, cap queue length with 429 or 503 under load, and keep results for a limited time.

python
import threading
from concurrent.futures import ThreadPoolExecutor
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException, Response
from fastapi.testclient import TestClient

app = FastAPI()
pool = ThreadPoolExecutor(max_workers=2)           # stand-in for Celery or ARQ workers
jobs: dict[str, dict] = {}
by_key: dict[str, str] = {}
gate = threading.Event()                           # lets the demo keep a job "running" on purpose


def build_report(job_id: str):
    jobs[job_id]["status"] = "running"
    gate.wait(timeout=5)
    jobs[job_id].update(status="succeeded", result="/reports/" + job_id + "/download")


@app.post("/reports", status_code=202)
def start(response: Response, idempotency_key: Annotated[str | None, Header()] = None):
    if idempotency_key and idempotency_key in by_key:
        job_id = by_key[idempotency_key]                       # same key, same job
    else:
        job_id = f"job-{len(jobs) + 1}"                        # use uuid4 in real code
        jobs[job_id] = {"id": job_id, "status": "queued"}
        if idempotency_key:
            by_key[idempotency_key] = job_id
        pool.submit(build_report, job_id)
    response.headers["Location"] = f"/jobs/{job_id}"
    response.headers["Retry-After"] = "2"
    return {"id": job_id, "status": jobs[job_id]["status"]}


@app.get("/jobs/{job_id}")
def status(job_id: str):
    if job_id not in jobs:
        raise HTTPException(404, "Unknown job")
    return jobs[job_id]


c = TestClient(app)
first = c.post("/reports", headers={"Idempotency-Key": "abc-1"})
retry = c.post("/reports", headers={"Idempotency-Key": "abc-1"})
print(first.status_code, first.headers["location"], retry.headers["location"], "jobs created:", len(jobs))
import time
while jobs["job-1"]["status"] != "running":
    time.sleep(0.01)
print("while the worker runs:", c.get(first.headers["location"]).json()["status"])
gate.set()
pool.shutdown(wait=True)
print("after the worker finishes:", c.get("/jobs/job-1").json())
print(c.get("/jobs/nope").status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The thread pool stands in for a real queue. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 202 /jobs/job-1 /jobs/job-1 jobs created: 1 while the worker runs: running after the worker finishes: {'id': 'job-1', 'status': 'succeeded', 'result': '/reports/job-1/download'} 404

Key points

  • 202 Accepted with a Location header to a job resource
  • Status endpoint with queued, running, succeeded, failed
  • Idempotency-Key makes retried POSTs safe
  • Use a persistent queue, not in-process tasks, in production
  • Enqueue after commit; authorise job access

Common mistakes

  • Holding the HTTP request open for the whole job
  • Using in-process background tasks for important jobs
  • No idempotency, so retries create duplicate jobs
  • Letting any user read any job by ID
  • Enqueueing before the transaction commits

Follow-ups

  • How would you notify clients without polling?
  • How do you cancel a running job?
  • How do you size the queue and apply backpressure?

Tips

  • Lay out the endpoint flow
  • Explain Idempotency-Key
  • Say where the worker runs
86.fastapi-0086Hardsenior

How do you manage transactions and savepoints with async SQLAlchemy in FastAPI, and what are the common failure modes?

Use one AsyncSession per request from a dependency, and make the transaction boundary explicit: async with session.begin() (commit on success, rollback on error) in the service layer or the dependency. Use session.begin_nested() for a SAVEPOINT so one failing step can roll back without losing the rest. Set expire_on_commit=False to avoid lazy loads after commit, load relationships eagerly, and never share a session between concurrent tasks.

Full answer

Session lifecycle:

  • Create the engine once (create_async_engine), a async_sessionmaker(engine, expire_on_commit=False) once, and a dependency that yields one AsyncSession per request and closes it at the end.
  • Transaction boundary: either async with session.begin(): around a unit of work, or commit explicitly at the end of the service function. Pick one convention for the codebase. Do not commit in repositories or random helpers.
  • Autobegin: a session starts a transaction implicitly on first use; a long-lived dependency that never commits holds a connection (and locks) open until closed. With the default dependency scope, exit code runs after the response, so heavy post-processing keeps the connection busy.

Savepoints:

python
async with session.begin():
    session.add(order)
    try:
        async with session.begin_nested():       # SAVEPOINT
            session.add(loyalty_points_row)
            await session.flush()                # may raise IntegrityError
    except IntegrityError:
        ...                                      # only the inner work is undone

Use them for optional or retryable steps (inserting a duplicate-prone row, a best-effort audit record) without aborting the outer transaction. PostgreSQL aborts the whole transaction after an error unless the failing statement ran inside a savepoint.

Failure modes:

  • MissingGreenlet errors: touching a lazy relationship or an expired attribute outside an awaitable context. Use selectinload/joinedload, await session.refresh(obj), or lazy="raise" to find mistakes early. expire_on_commit=False prevents attributes from expiring at commit.
  • Sharing one AsyncSession across asyncio.gather tasks: sessions are not concurrency-safe. Create a session per task.
  • Exceptions after flush() leave the session in a failed state until you roll back; with session.begin() this is automatic.
  • Concurrency: row races need SELECT ... FOR UPDATE (with_for_update()), optimistic version columns, or unique constraints with retry on IntegrityError.
  • Isolation level: default READ COMMITTED on PostgreSQL; use REPEATABLE READ or SERIALIZABLE (with retries) for stricter guarantees.
  • Pool exhaustion when requests hold sessions while waiting on slow external calls; do external I/O outside the transaction.
python
import asyncio

from sqlalchemy import event, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class Base(DeclarativeBase):
    pass


class Account(Base):
    __tablename__ = "account"
    id: Mapped[int] = mapped_column(primary_key=True)
    owner: Mapped[str] = mapped_column(unique=True)
    balance: Mapped[int]


engine = create_async_engine("sqlite+aiosqlite://")


@event.listens_for(engine.sync_engine, "connect")
def no_implicit_begin(dbapi_connection, record):
    dbapi_connection.isolation_level = None            # pysqlite recipe so SAVEPOINT works


@event.listens_for(engine.sync_engine, "begin")
def emit_begin(conn):
    conn.exec_driver_sql("BEGIN")


Session = async_sessionmaker(engine, expire_on_commit=False)


async def main():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    async with Session() as session:
        async with session.begin():                     # commits at the end of the block
            session.add(Account(owner="asha", balance=100))
            try:
                async with session.begin_nested():      # SAVEPOINT: only this part can roll back
                    session.add(Account(owner="asha", balance=999))        # unique violation
                    await session.flush()
            except IntegrityError:
                print("duplicate rejected, outer transaction still alive")
            session.add(Account(owner="ravi", balance=50))

    async with Session() as session:
        rows = (await session.execute(select(Account.owner, Account.balance).order_by(Account.owner))).all()
        print([tuple(r) for r in rows])

    try:
        async with Session() as session:
            async with session.begin():
                session.add(Account(owner="meera", balance=10))
                await session.flush()
                raise RuntimeError("business rule failed")
    except RuntimeError as exc:
        print("rolled back:", exc)
    async with Session() as session:
        print("meera saved:", (await session.scalar(select(Account).where(Account.owner == "meera"))) is not None)
    await engine.dispose()


asyncio.run(main())

Standalone script. Run it with `python file.py`. Requires `pip install sqlalchemy aiosqlite`; SQLite needs the small connect and begin event hooks so savepoints work, PostgreSQL does not. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): duplicate rejected, outer transaction still alive [('asha', 100), ('ravi', 50)] rolled back: business rule failed meera saved: False

Key points

  • One AsyncSession per request; one explicit transaction convention
  • begin_nested() creates a SAVEPOINT for partial rollback
  • expire_on_commit=False and eager loading avoid MissingGreenlet
  • Never share a session between concurrent tasks
  • Keep external I/O outside the transaction

Common mistakes

  • Sharing one AsyncSession between concurrent tasks
  • Triggering lazy loads in async code and hitting MissingGreenlet
  • Committing in many layers so the unit of work is unclear
  • Calling slow external services while holding a transaction open
  • Ignoring that PostgreSQL aborts the transaction after an error unless a savepoint was used

Follow-ups

  • How do you handle serialization failures with retries?
  • When do you use SELECT FOR UPDATE versus optimistic locking?
  • How do you test code that uses savepoints?

Tips

  • Show begin() plus begin_nested()
  • Name MissingGreenlet and how to avoid it
  • Mention session per request
87.fastapi-0087Hardsenior

How do you prevent lost updates in a FastAPI REST API using ETags, If-Match and optimistic locking?

Return an ETag that identifies the current version of a resource (for example from a version column). Require clients to send it back as If-Match on PUT or PATCH. If the header is missing answer 428 Precondition Required, if it does not match answer 412 Precondition Failed, and enforce the check atomically with a version column (UPDATE ... WHERE id = ? AND version = ?) so concurrent writers cannot both win. This stops one user's edit from silently overwriting another's.

Full answer

The lost update problem: user A and user B both read a record, edit, and PUT; the later write overwrites the earlier one without either noticing.

Protocol:

  • GET /students/7 returns the body and ETag: "3" (the strong validator, quoted). The version can be an integer column, a row hash, or xmin in PostgreSQL.
  • PUT /students/7 must send If-Match: "3". No header: 428 Precondition Required. Stale value: 412 Precondition Failed (the client re-fetches and merges). Success returns the new ETag: "4".
  • If-None-Match on GET enables cache validation: if the ETag matches, return 304 Not Modified with no body.

Atomic enforcement: comparing the header to the current value in Python is a race (check-then-act). Make the database enforce it:

  • SQLAlchemy __mapper_args__ = {"version_id_col": version} adds WHERE version = :old to UPDATE and raises StaleDataError when no row matches. Catch it and return 412 (or 409).
  • Raw SQL: UPDATE student SET name=:n, version=version+1 WHERE id=:id AND version=:v and check rowcount.

Design points:

  • Use strong ETags for writes (weak W/ tags are not valid for If-Match comparison, per RFC 9110).
  • A response model should not expose internal columns, but may include version too for clients that cannot read headers; the header is still the standard path.
  • Compare ETags exactly including quotes, and support lists (If-Match: "3", "4") and * only if you mean it.
  • Document 412 and 428 in OpenAPI responses.
  • PATCH with JSON Merge Patch benefits as well.
  • Pessimistic locking (SELECT FOR UPDATE) is better for short critical sections inside one transaction; optimistic locking suits user-edit flows spread over minutes.

Test with two sessions: both load, the first commits, the second must fail with 412.

python
import tempfile
from pathlib import Path
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException, Response
from fastapi.testclient import TestClient
from pydantic import BaseModel
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.orm.exc import StaleDataError


class Base(DeclarativeBase):
    pass


class Student(Base):
    __tablename__ = "student"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    version: Mapped[int] = mapped_column(default=1)
    __mapper_args__ = {"version_id_col": version}


engine = create_engine(f"sqlite:///{Path(tempfile.mkdtemp()) / 'db.sqlite'}")
Base.metadata.create_all(engine)
with Session(engine) as s:
    s.add(Student(name="Asha"))
    s.commit()

app = FastAPI()


class StudentIn(BaseModel):
    name: str


@app.get("/students/{sid}")
def read(sid: int, response: Response):
    with Session(engine) as db:
        st = db.get(Student, sid)
        response.headers["ETag"] = f'"{st.version}"'
        return {"id": st.id, "name": st.name}


@app.put("/students/{sid}")
def update(sid: int, body: StudentIn, response: Response, if_match: Annotated[str | None, Header()] = None):
    if if_match is None:
        raise HTTPException(428, "If-Match header required")
    expected = int(if_match.strip('"'))
    with Session(engine) as db:
        st = db.get(Student, sid)
        if st.version != expected:
            raise HTTPException(412, "Resource changed; fetch it again")
        st.name = body.name
        try:
            db.commit()                                  # UPDATE ... WHERE version = :old
        except StaleDataError:
            raise HTTPException(412, "Concurrent update detected")
        response.headers["ETag"] = f'"{st.version}"'
        return {"id": st.id, "name": st.name}


c = TestClient(app)
etag = c.get("/students/1").headers["etag"]
print("etag:", etag)
print("no header:", c.put("/students/1", json={"name": "A1"}).status_code)
ok = c.put("/students/1", json={"name": "Asha R"}, headers={"If-Match": etag})
print("fresh:", ok.status_code, ok.headers["etag"])
print("stale:", c.put("/students/1", json={"name": "Lost"}, headers={"If-Match": etag}).status_code)

# the database catches a race the Python check cannot
a, b = Session(engine), Session(engine)
sa, sb = a.get(Student, 1), b.get(Student, 1)
sa.name, sb.name = "from A", "from B"
a.commit()
try:
    b.commit()
except StaleDataError:
    print("second writer stopped by version_id_col")
    b.rollback()
a.close()
b.close()

Standalone script. Run it with `python file.py`; it uses a temporary SQLite file and TestClient. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): etag: "1" no header: 428 fresh: 200 "2" stale: 412 second writer stopped by version_id_col

Key points

  • ETag carries the version; If-Match returns it on writes
  • 428 when missing, 412 when stale
  • Enforce atomically with a version column, not a Python check
  • Use strong ETags for If-Match; weak ones are invalid there
  • If-None-Match gives cache validation with 304

Common mistakes

  • Checking the version in Python only, which leaves a race window
  • Using weak ETags with If-Match
  • Returning 409 or silently overwriting instead of 412 and 428
  • Not documenting the headers in OpenAPI
  • Ignoring that PATCH needs the same protection

Follow-ups

  • How do ETags help caching with If-None-Match?
  • When is pessimistic locking a better fit?
  • How would you use PostgreSQL xmin as a version?

Tips

  • Describe 428 and 412
  • Name the database enforcement
  • Mention strong vs weak ETags
88.fastapi-0088Hardsenior

How do you get good performance from Pydantic v2 in a FastAPI service: TypeAdapter reuse, model_validate_json, strict mode and avoiding double validation?

Pydantic v2 validates in a Rust core, so most cost comes from avoidable work around it. Build TypeAdapters and models once at import time, not per request, use model_validate_json to parse and validate bytes in one pass, prefer simple types and strict mode where coercion is not needed, avoid re-validating data you just validated (response models, model_construct only for trusted data), and set a return annotation so FastAPI serialises through Pydantic directly. Measure with realistic payloads before tuning.

Full answer

Where time goes: building a validator (schema compilation) is expensive; running it is cheap. Per-request building is the most common mistake.

Practical rules:

  1. Create TypeAdapter(list[Student]) at module level. Calling TypeAdapter(...) inside a request handler rebuilds the core schema every time. The same applies to defining models inside functions.
  2. Parse bytes directly: Model.model_validate_json(raw) avoids creating an intermediate Python dict from json.loads. In FastAPI the framework already parses the body for you, but for custom reads (webhooks, queue messages, files) this saves memory and time.
  3. Strict mode: ConfigDict(strict=True) or Field(strict=True) skips coercion paths (and rejects "5" for an int), which is faster and safer for internal service-to-service payloads. For public JSON APIs lax mode is usually what clients expect.
  4. Avoid double validation: with response_model or a return annotation FastAPI validates and serialises your return value, so returning an already-validated model means the work happens twice. For hot endpoints, return plain dicts that match the schema, or return a Response object yourself with response_model=None when bytes are prebuilt (cached JSON).
  5. model_construct() skips validation: use it only for data you trust (rows from your own database, already validated), never for client input.
  6. Choose cheaper types: concrete list[int] beats Sequence[int], Literal beats custom validators, built-in constraints beat Python validators. Python field_validator functions run per item and cost the most. mode="before" validators run extra code on every call.
  7. from_attributes=True for ORM objects reads attributes; load only the columns you need (select(Student.id, Student.name)) and return rows mapped to a lean model.
  8. Serialisation: model_dump_json() writes JSON bytes in Rust and is faster than json.dumps(model.model_dump()). FastAPI uses this path when a return type or response model exists, so deprecated custom response classes such as ORJSONResponse are no longer needed.
  9. Large payloads: stream NDJSON, paginate, and limit list sizes to protect memory.

Measure: use timeit/pyperf on production-shaped payloads and profile endpoints under load (py-spy). The database and network usually dominate, so do not trade readability for micro-gains without evidence.

python
import json

from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError, validate_call


class Student(BaseModel):
    roll_no: str
    marks: int


class StrictStudent(BaseModel):
    model_config = ConfigDict(strict=True)
    roll_no: str
    marks: int


STUDENTS = TypeAdapter(list[Student])                      # built once, reused for every call

raw = b'[{"roll_no": "BCA-1", "marks": "81"}, {"roll_no": "BCA-2", "marks": 64}]'
parsed = STUDENTS.validate_json(raw)                       # bytes in, validated models out
print(parsed)
print("same result via json.loads:", parsed == STUDENTS.validate_python(json.loads(raw)))

try:
    StrictStudent.model_validate({"roll_no": "BCA-1", "marks": "81"})
except ValidationError as exc:
    print("strict mode:", exc.errors()[0]["type"])

trusted = Student.model_construct(roll_no="BCA-3", marks="not-an-int")      # no validation at all
print("model_construct keeps bad data:", repr(trusted.marks))

print("serialised:", STUDENTS.dump_json(parsed).decode())


@validate_call
def percent(marks: int, total: int = 100) -> float:
    return round(marks * 100 / total, 1)


print(percent("45", total=50))

Standalone script. Run it with `python file.py`; no server is needed. Timing is deliberately not printed because it varies by machine. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): [Student(roll_no='BCA-1', marks=81), Student(roll_no='BCA-2', marks=64)] same result via json.loads: True strict mode: int_type model_construct keeps bad data: 'not-an-int' serialised: [{"roll_no":"BCA-1","marks":81},{"roll_no":"BCA-2","marks":64}] 90.0

Key points

  • Build TypeAdapters and models once at import time
  • model_validate_json parses and validates bytes in one pass
  • Strict mode avoids coercion work when clients are trusted
  • Avoid validating the same data twice; model_construct only for trusted data
  • Python validators are the slowest part; measure before tuning

Common mistakes

  • Creating TypeAdapter or models inside request handlers
  • Calling json.loads then model_validate when model_validate_json works
  • Returning validated models and also paying for response_model validation on hot paths
  • Using model_construct on client input
  • Optimising before measuring with real payloads

Follow-ups

  • How do you profile a FastAPI endpoint under load?
  • What does defer_build do?
  • When would you use RootModel?

Tips

  • List 3 concrete optimisations
  • Say measure first
  • Mention Rust core
89.fastapi-0089Hardsenior

How do you manage shared resources with FastAPI lifespan and typed state, and what does graceful shutdown involve?

Use an async context manager passed as lifespan to open shared resources (HTTP client, connection pools, caches) before the first request and close them after the last, yielding a state dictionary that each request reads through request.state (Starlette 0.26+). Type it with a TypedDict for editor support. Graceful shutdown means the server stops accepting connections, lets in-flight requests finish within a timeout, then lifespan cleanup awaits or cancels tracked background work and closes resources.

Full answer

Replace the deprecated @app.on_event("startup") handlers with lifespan:

python
class State(TypedDict):
    http: httpx.AsyncClient
    tasks: set[asyncio.Task]

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[State]:
    async with httpx.AsyncClient(timeout=5) as client:
        tasks: set[asyncio.Task] = set()
        yield {"http": client, "tasks": tasks}
        await asyncio.gather(*tasks, return_exceptions=True)     # drain background work
  • Everything before yield is startup; everything after is shutdown. Because of the async with, the client is closed even when startup later fails or the server is interrupted.
  • The yielded dict becomes request.state for every request (request.state.http), and also scope["state"]. Type hints: annotate with Request and a typed accessor, or a small dependency def get_http(request: Request) -> httpx.AsyncClient: return request.state.http. This avoids module-level globals that complicate testing and multi-app processes.
  • Tests: with TestClient(app) as client: runs lifespan; without the context manager lifespan does not run. Override the dependency to inject fakes.
  • With multiple workers each process runs its own lifespan, so each opens its own pool: size pools per process.

Graceful shutdown sequence (Uvicorn/Gunicorn):

  1. SIGTERM received: the server stops accepting new connections.
  2. In-flight requests continue until they finish or --timeout-graceful-shutdown expires (Uvicorn) or graceful_timeout (Gunicorn).
  3. The lifespan shutdown phase runs: cancel or await tracked background tasks, flush buffers (metrics, logs), close pools and clients.
  4. The process exits; the orchestrator's termination grace period must be longer than all of these timers, or it sends SIGKILL and cuts them short.

Also: keep shutdown work bounded (use asyncio.wait_for), mark the readiness probe unhealthy first, do not start new long tasks during shutdown, and handle CancelledError in long-running tasks so they clean up. Exceptions in startup abort the app start, which is what you want when the database is unreachable.

python
import asyncio
from contextlib import asynccontextmanager
from typing import AsyncIterator, TypedDict

import httpx
from fastapi import Depends, FastAPI, Request
from fastapi.testclient import TestClient

log = []


class State(TypedDict):
    http: httpx.AsyncClient
    tasks: set[asyncio.Task]


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[State]:
    log.append("startup: open client")
    async with httpx.AsyncClient(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={"ok": True}))) as client:
        tasks: set[asyncio.Task] = set()
        yield {"http": client, "tasks": tasks}
        log.append(f"shutdown: draining {len(tasks)} task(s)")
        await asyncio.gather(*tasks, return_exceptions=True)
        log.append("shutdown: tasks drained")
    log.append(f"shutdown: client closed={client.is_closed}")


app = FastAPI(lifespan=lifespan)


def get_http(request: Request) -> httpx.AsyncClient:
    return request.state.http                      # one place that knows where the resource lives


async def flush_metrics():
    await asyncio.sleep(0.01)
    log.append("background flush finished")


@app.get("/ping")
async def ping(request: Request, http: httpx.AsyncClient = Depends(get_http)):
    reply = await http.get("https://upstream.example/health")
    task = asyncio.create_task(flush_metrics())
    request.state.tasks.add(task)
    task.add_done_callback(request.state.tasks.discard)
    return reply.json()


with TestClient(app) as client:                    # the with-block runs lifespan
    print(client.get("/ping").json())
print("\n".join(log))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install httpx`; a mock transport replaces the real network. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'ok': True} startup: open client shutdown: draining 1 task(s) background flush finished shutdown: tasks drained shutdown: client closed=True

Key points

  • lifespan replaces on_event; before yield is startup, after is shutdown
  • The yielded state dict is available as request.state
  • Expose resources through dependencies, not globals, for testability
  • Graceful shutdown: stop accepting, drain, cleanup, exit
  • Termination grace period must exceed server and lifespan timeouts

Common mistakes

  • Using deprecated on_event handlers in new code
  • Module-level globals for clients and pools
  • Forgetting the with-block in TestClient so lifespan never runs
  • Untracked background tasks that get killed at shutdown
  • Pool sizes not adjusted per worker process

Follow-ups

  • How do Uvicorn and Gunicorn graceful timeouts differ?
  • How would you share state between multiple lifespans?
  • How does the readiness probe fit in?

Tips

  • Show the lifespan code
  • List shutdown steps
  • Mention TestClient context manager
90.fastapi-0090Hardsenior

How do you handle timeouts, cancellation and client disconnects in async FastAPI endpoints without leaking work or connections?

Set explicit timeouts on every outbound call and wrap multi-step work in asyncio.timeout so slow dependencies produce a clean 504 instead of hanging workers. When a client disconnects, the ASGI server cancels the handler task (for streaming responses) and the code receives CancelledError: use try/finally to release resources and never swallow the cancellation. Poll request.is_disconnected() in long non-streaming loops. Shield only short critical cleanup, such as commits.

Full answer

Why this matters: without limits, one slow database or API call holds a task, a connection and memory for as long as the dependency stalls. Hung requests pile up until the pool is exhausted.

Timeouts at every layer:

  • Client side: httpx.Timeout(connect=2, read=5, write=5, pool=1) (never rely on defaults of libraries without a timeout; some wait forever). Database: statement timeout (SET statement_timeout), pool timeout.
  • Endpoint level: async with asyncio.timeout(3): (Python 3.11+) around the whole operation; catch TimeoutError and return 504 Gateway Timeout (or 503). The inner awaits are cancelled, which triggers their finally blocks.
  • Server level: Uvicorn --timeout-keep-alive, --timeout-graceful-shutdown; Gunicorn worker timeout (for UvicornWorker it is a heartbeat, not a request limit); proxy timeouts (nginx proxy_read_timeout) should be larger than the app's own limit so the app answers first.

Cancellation semantics:

  • asyncio.CancelledError is raised at an await. Do cleanup in finally or except asyncio.CancelledError: ...; raise. Swallowing it breaks timeout(), task groups and shutdown.
  • When a client drops the connection, Starlette's StreamingResponse (and server-sent events) detects http.disconnect and cancels the task, so generators receive cancellation and can close upstream streams.
  • For normal endpoints that already received the full body, the framework does not interrupt your handler on disconnect; the work finishes and the response is discarded. For expensive operations, poll await request.is_disconnected() between steps and stop early, or run the work as a background job independent of the connection.
  • asyncio.shield() protects a short operation (final commit, releasing a lock) from being cancelled mid-way. Do not shield long work.
  • Sync (def) endpoints run in worker threads that cannot be cancelled; set timeouts inside their calls.

Idempotency matters because after a timeout the client may retry while the original work is still running or already committed.

python
import asyncio

from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse

app = FastAPI()
events = []


async def slow_dependency():
    try:
        await asyncio.sleep(10)
    finally:
        events.append("slow dependency cancelled and cleaned up")


@app.get("/report")
async def report():
    try:
        async with asyncio.timeout(0.05):
            await slow_dependency()
    except TimeoutError:
        raise HTTPException(status_code=504, detail="Upstream too slow")


@app.get("/stream")
async def stream():
    async def numbers():
        try:
            yield b"first chunk\n"
            await asyncio.Event().wait()               # waits forever, like a slow upstream
        except asyncio.CancelledError:
            events.append("stream cancelled by client disconnect")
            raise
        finally:
            events.append("upstream connection closed")

    return StreamingResponse(numbers())


def scope(path):
    return {"type": "http", "asgi": {"version": "3.0", "spec_version": "2.3"}, "http_version": "1.1", "method": "GET",
            "scheme": "http", "path": path, "raw_path": path.encode(), "query_string": b"", "headers": [],
            "server": ("t", 80), "client": ("127.0.0.1", 1), "root_path": ""}


async def get(path, disconnect_after_first_chunk=False):
    first_chunk_sent = asyncio.Event()
    status = []

    async def receive():
        if disconnect_after_first_chunk:
            await first_chunk_sent.wait()
            return {"type": "http.disconnect"}
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(message):
        if message["type"] == "http.response.start":
            status.append(message["status"])
        elif message["type"] == "http.response.body" and message.get("body"):
            first_chunk_sent.set()

    await app(scope(path), receive, send)
    return status[0]


async def main():
    print("timeout ->", await get("/report"), events)
    events.clear()
    await get("/stream", disconnect_after_first_chunk=True)
    print(events)


asyncio.run(main())

Standalone script. Run it with `python file.py`; it drives the ASGI app directly so the disconnect can be simulated. Requires Python 3.11 or later for asyncio.timeout. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): timeout -> 504 ['slow dependency cancelled and cleaned up'] ['stream cancelled by client disconnect', 'upstream connection closed']

Key points

  • Set explicit timeouts on every outbound call and with asyncio.timeout
  • CancelledError must be allowed to propagate; use finally for cleanup
  • Streaming responses are cancelled on disconnect; plain handlers are not
  • Proxy timeouts should exceed app timeouts
  • Make operations idempotent because retries follow timeouts

Common mistakes

  • Calling external services without timeouts
  • Catching CancelledError and not re-raising it
  • Assuming plain endpoints stop when the client disconnects
  • Setting proxy timeouts lower than the application's
  • Shielding long operations, which defeats timeouts

Follow-ups

  • How do task groups change cancellation handling?
  • What happens to sync endpoints on timeout?
  • How do you design retries after a gateway timeout?

Tips

  • Mention asyncio.timeout
  • Say re-raise CancelledError
  • Contrast streaming and plain endpoints
91.fastapi-0091Hardsenior

What is the difference between pure ASGI middleware and BaseHTTPMiddleware in FastAPI, and why do contextvars and streaming behave differently?

BaseHTTPMiddleware is a convenience wrapper (dispatch(request, call_next)) that runs the downstream app in a separate task, which is why context variables set in the endpoint do not reach the middleware after call_next, and why it adds overhead and complicates streaming and background tasks. Pure ASGI middleware, a class with async __call__(scope, receive, send), runs in the same task and context, adds minimal overhead, and gives full control, at the cost of more code.

Full answer

Two ways to write middleware:

python
# convenience
class Timing(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        return response

# pure ASGI
class Timing:
    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)
        ...
        await self.app(scope, receive, send_wrapper)

Differences:

  • Task boundary: BaseHTTPMiddleware.call_next runs the downstream app in a separate task connected by memory streams. A ContextVar set in the middleware before call_next is visible downstream (the task copies the context), but a value set inside the endpoint is not visible after call_next returns, because it lives in the other task's context. Pure ASGI middleware calls the app in the same task, so changes are visible both ways (for async endpoints; sync endpoints run in a thread with a copied context).
  • Performance: the extra task and stream cost per request; pure ASGI is leaner, which matters for high-throughput services.
  • Streaming and disconnects: the wrapper buffers or proxies body streams; reading request.body() in the middleware and then letting the endpoint read it needs care (modern Starlette handles it better but it remains subtle). Background tasks run after the response, and the wrapper's handling of them has had edge cases.
  • Exceptions: with BaseHTTPMiddleware exceptions from the app propagate through call_next; with pure ASGI you must wrap send yourself to modify headers or status after the app has started responding.
  • Only HTTP: BaseHTTPMiddleware does not handle websockets; pure ASGI sees scope["type"] of http, websocket and lifespan.

Guidelines: use BaseHTTPMiddleware for simple request-in/response-out logic where you do not need contextvars written downstream or streaming control (adding a header, simple auth gate). Use pure ASGI for request IDs and logging context that downstream code writes, tracing, body size limits, compression, anything performance sensitive or streaming. Libraries like asgi-correlation-id and Starlette's own middleware (CORS, GZip, TrustedHost) are pure ASGI for these reasons.

Order matters: middleware added last runs outermost; exception handlers and ServerErrorMiddleware sit at the edges.

python
import asyncio
from contextvars import ContextVar

from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware

request_id = ContextVar("request_id", default=None)
user = ContextVar("user", default=None)
seen = {}


class SimpleMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        request_id.set("req-1")                         # set before the app runs
        response = await call_next(request)
        seen["basehttp: user visible after call_next"] = user.get()
        return response


class PureMiddleware:
    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)
        request_id.set("req-1")
        await self.app(scope, receive, send)
        seen["pure asgi: user visible after the app"] = user.get()


def build(middleware_class):
    app = FastAPI()

    @app.get("/who")
    async def who():
        seen["endpoint sees request_id"] = request_id.get()
        user.set("asha")                                # written downstream
        return {"ok": True}

    app.add_middleware(middleware_class)
    return app


async def call(app):
    scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http",
             "path": "/who", "raw_path": b"/who", "query_string": b"", "headers": [], "server": ("t", 80),
             "client": ("127.0.0.1", 1), "root_path": ""}

    async def receive():
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(message):
        pass

    await app(scope, receive, send)


for cls in (SimpleMiddleware, PureMiddleware):
    seen.clear()
    user.set(None)
    asyncio.run(call(build(cls)))
    print(cls.__name__, seen)

Standalone script. Run it with `python file.py`; it drives the ASGI app directly. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): SimpleMiddleware {'endpoint sees request_id': 'req-1', 'basehttp: user visible after call_next': None} PureMiddleware {'endpoint sees request_id': 'req-1', 'pure asgi: user visible after the app': 'asha'}

Key points

  • BaseHTTPMiddleware runs the app in a separate task
  • ContextVars set in middleware reach the endpoint; values set in the endpoint do not come back
  • Pure ASGI shares the task and context, with less overhead
  • Use pure ASGI for streaming, contextvars written downstream and performance
  • BaseHTTPMiddleware is HTTP-only and simpler to write

Common mistakes

  • Expecting ContextVars set in endpoints to be visible in BaseHTTPMiddleware
  • Using BaseHTTPMiddleware for streaming or high-throughput paths
  • Forgetting to pass non-http scopes through in pure ASGI middleware
  • Assuming middleware order is first added, first run
  • Reading the body in middleware without restoring it for the endpoint

Follow-ups

  • How do you wrap send to add a response header in pure ASGI?
  • How does middleware order work in Starlette?
  • Why is request ID logging usually pure ASGI?

Tips

  • Explain the extra task
  • Describe the contextvar effect
  • Give guidance on when to use each
92.fastapi-0092Hardsenior

How would you implement multi-tenancy in FastAPI with per-tenant database routing, and what are the isolation trade-offs?

Resolve the tenant early (subdomain, header or token claim), validate it against a registry, and give each request a session bound to that tenant's database through a dependency. Options are database per tenant, schema per tenant (schema_translate_map), or shared tables with a tenant_id column enforced by row-level security. The more isolated the model, the higher the operational cost: connection pools, migrations and monitoring multiply per tenant.

Full answer

Models:

  1. Shared tables with tenant_id: cheapest, easiest to scale to thousands of tenants. Risk: one missing WHERE tenant_id leaks data. Mitigate with a base query helper, PostgreSQL Row-Level Security (SET app.tenant = ... per transaction), and tests.
  2. Schema per tenant (PostgreSQL): one database, separate schemas; use execution_options(schema_translate_map={None: tenant_schema}) per connection. Moderate isolation; migrations must run for every schema.
  3. Database per tenant: strongest isolation, per-tenant backup/restore, noisy-neighbour control, data residency. Costs: many pools and connections, migrations across all databases, onboarding automation.

Routing in FastAPI:

  • Resolve the tenant in a dependency (or pure ASGI middleware) from the subdomain, a header (only if trusted), or a verified JWT claim. Never trust a header the client can set freely when authenticated identity already implies the tenant. Check that the authenticated user belongs to that tenant.
  • Keep a registry (database table or config) mapping tenant to connection URL, and a bounded cache of engines: create engines lazily, evict least-recently-used ones (engine.dispose()), and cap the total number of open connections (pool_size times active tenants).
  • Dependency yields a Session bound to the tenant engine; unknown tenants give 404, suspended ones 403.
  • Set a ContextVar with the tenant for logging and metrics labels; include tenant in cache keys and background job payloads so workers route correctly.
  • Migrations: Alembic needs a loop over tenants with progress tracking and failure handling; version tenants independently or force lockstep.
  • Test cross-tenant leaks explicitly: create data in tenant A, assert tenant B cannot see or fetch it by ID.

Operational: per-tenant rate limits and quotas, backups, observability dimensions, and an admin path with explicit audit trails for support access.

python
import tempfile
from pathlib import Path
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column

root = Path(tempfile.mkdtemp())
REGISTRY = {"acme": root / "acme.db", "globex": root / "globex.db"}       # tenant -> database (a table in real systems)
engines: dict = {}


class Base(DeclarativeBase):
    pass


class Note(Base):
    __tablename__ = "note"
    id: Mapped[int] = mapped_column(primary_key=True)
    text: Mapped[str]


def engine_for(tenant: str):
    if tenant not in REGISTRY:
        raise HTTPException(status_code=404, detail="Unknown tenant")
    if tenant not in engines:                                      # lazy; evict least-recently-used in real code
        engines[tenant] = create_engine(f"sqlite:///{REGISTRY[tenant]}")
        Base.metadata.create_all(engines[tenant])
    return engines[tenant]


def tenant_session(x_tenant: Annotated[str, Header()]):
    with Session(engine_for(x_tenant)) as db:
        yield db


app = FastAPI()


@app.post("/notes", status_code=201)
def add(text: str, db: Annotated[Session, Depends(tenant_session)]):
    db.add(Note(text=text))
    db.commit()
    return {"saved": text}


@app.get("/notes")
def listing(db: Annotated[Session, Depends(tenant_session)]):
    return list(db.scalars(select(Note.text)))


c = TestClient(app)
c.post("/notes", params={"text": "acme budget"}, headers={"X-Tenant": "acme"})
c.post("/notes", params={"text": "globex roadmap"}, headers={"X-Tenant": "globex"})
print("acme sees:", c.get("/notes", headers={"X-Tenant": "acme"}).json())
print("globex sees:", c.get("/notes", headers={"X-Tenant": "globex"}).json())
print("unknown tenant:", c.get("/notes", headers={"X-Tenant": "evilcorp"}).status_code)
print("missing header:", c.get("/notes").status_code)
print("databases on disk:", sorted(p.name for p in root.iterdir()))

Standalone script. Run it with `python file.py`; it uses temporary SQLite files and TestClient. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): acme sees: ['acme budget'] globex sees: ['globex roadmap'] unknown tenant: 404 missing header: 422 databases on disk: ['acme.db', 'globex.db']

Key points

  • Choose isolation: tenant_id column, schema per tenant or database per tenant
  • Resolve tenant early and verify the user belongs to it
  • Lazy, bounded cache of engines; dispose evicted ones
  • Migrations and pools multiply with isolation level
  • Test cross-tenant access explicitly

Common mistakes

  • Trusting a client-supplied tenant header without verifying membership
  • Forgetting a tenant filter in one query in shared-table designs
  • Unbounded engine caches that exhaust database connections
  • Cache keys and background jobs without the tenant
  • No automated cross-tenant leak tests

Follow-ups

  • How does PostgreSQL row-level security help?
  • How do you run Alembic across all tenants?
  • How do you onboard a new tenant database?

Tips

  • Compare the three isolation models
  • Show tenant resolution
  • Mention bounded engine caches
93.fastapi-0093Hardsenior

How do you securely receive webhooks in FastAPI: HMAC signature verification over the raw body, timestamp tolerance and replay protection?

Read the raw request bytes before any JSON parsing, compute an HMAC (usually SHA-256) over timestamp plus body with the shared secret, and compare it to the signature header with hmac.compare_digest. Reject timestamps outside a small window (for example five minutes) to limit replay, store processed event IDs to ignore duplicates, return 2xx quickly and process asynchronously, and support secret rotation by accepting several signatures during a transition period.

Full answer

Why verify: a webhook URL is public. Without authentication anyone can post fake events (payment succeeded, user upgraded).

Verification recipe (Stripe-style header t=1733300000,v1=<hex>):

  1. Get the raw body: body = await request.body(). Do not declare a Pydantic body parameter first: parsing and re-serialising JSON changes bytes (spacing, key order, unicode escapes), so the signature would not match.
  2. Parse the header, build the signed payload f"{timestamp}.".encode() + body.
  3. expected = hmac.new(secret, payload, hashlib.sha256).hexdigest().
  4. Compare with hmac.compare_digest(expected, received) (constant time) to avoid timing leaks. Never use ==.
  5. Check the timestamp: abs(now - timestamp) <= 300 seconds. This limits replay of captured requests. Include the timestamp in the signed data, otherwise an attacker can change it.
  6. Parse JSON only after verification, with a Pydantic model.
  7. Deduplicate: providers deliver at least once and retry on non-2xx, so store event.id (unique constraint) and ignore repeats. Make handlers idempotent.
  8. Respond 200 quickly; enqueue slow work (queue or outbox) so the provider does not time out and retry.

Other points:

  • Secret management: one secret per endpoint, stored in a secrets manager; support rotation by trying a list of active secrets and by accepting multiple v1= entries.
  • Use HTTPS only, and optionally IP allow-lists from the provider as an extra layer (not a replacement).
  • Limit body size, and return 400 for bad signatures without revealing which check failed.
  • Log event IDs, not secrets or full bodies containing personal data.
  • Test with fixed timestamps (inject the clock) and a table of cases: valid, wrong secret, altered body, stale timestamp, missing header, duplicate event.
  • For providers that sign with asymmetric keys (GitHub uses HMAC; others use Ed25519 or RSA), verify with their public key and the same raw-body rule.
python
import hashlib
import hmac
import json

from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.testclient import TestClient

SECRET = b"whsec_demo_only"
TOLERANCE = 300
NOW = 1_733_300_000                                  # injected clock so the demo is deterministic
processed: set[str] = set()
app = FastAPI()


def sign(body: bytes, timestamp: int, secret: bytes = SECRET) -> str:
    mac = hmac.new(secret, f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
    return f"t={timestamp},v1={mac}"


@app.post("/webhooks/payments")
async def webhook(request: Request, x_signature: str = Header(default="")):
    body = await request.body()                       # raw bytes, before any JSON parsing
    try:
        parts = dict(p.split("=", 1) for p in x_signature.split(","))
        timestamp, received = int(parts["t"]), parts["v1"]
    except (KeyError, ValueError):
        raise HTTPException(400, "Invalid signature")
    expected = hmac.new(SECRET, f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, received):
        raise HTTPException(400, "Invalid signature")
    if abs(NOW - timestamp) > TOLERANCE:
        raise HTTPException(400, "Stale timestamp")
    event = json.loads(body)
    if event["id"] in processed:                      # at-least-once delivery means duplicates happen
        return {"status": "duplicate ignored"}
    processed.add(event["id"])
    return {"status": "processed", "type": event["type"]}


c = TestClient(app)
body = json.dumps({"id": "evt_1", "type": "payment.succeeded"}, separators=(",", ":")).encode()


def post(b, sig):
    return c.post("/webhooks/payments", content=b, headers={"X-Signature": sig, "Content-Type": "application/json"})


print("valid:", post(body, sign(body, NOW)).json())
print("duplicate:", post(body, sign(body, NOW)).json())
print("tampered body:", post(body.replace(b"succeeded", b"refunded"), sign(body, NOW)).status_code)
print("wrong secret:", post(body, sign(body, NOW, b"other")).status_code)
print("stale timestamp:", post(body, sign(body, NOW - 3600)).json())
print("missing header:", c.post("/webhooks/payments", content=body).status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): valid: {'status': 'processed', 'type': 'payment.succeeded'} duplicate: {'status': 'duplicate ignored'} tampered body: 400 wrong secret: 400 stale timestamp: {'detail': 'Stale timestamp'} missing header: 400

Key points

  • Verify over the raw bytes before JSON parsing
  • Constant-time comparison with hmac.compare_digest
  • Signed timestamp plus tolerance window limits replay
  • Deduplicate by event ID; handlers must be idempotent
  • Respond quickly and process asynchronously; support secret rotation

Common mistakes

  • Parsing JSON first and verifying a re-serialised body
  • Comparing signatures with == instead of compare_digest
  • No timestamp check, which allows replay forever
  • Doing slow work before responding so the provider retries
  • Not deduplicating events

Follow-ups

  • How do you rotate webhook secrets without downtime?
  • How do asymmetric webhook signatures differ?
  • How would you test signature code?

Tips

  • List the verification steps
  • Say raw body first
  • Mention replay and duplicates
94.fastapi-0094Hardsenior

How do you size database connection pools for a FastAPI deployment with several workers, and how does dependency scope affect connection hold time?

Each worker process has its own pool, so total possible connections are workers x replicas x (pool_size + max_overflow) and must stay below the database's max_connections with room for admin and migration sessions. Keep pool_size modest, set pool_timeout so overload fails fast, use pool_pre_ping and pool_recycle, and release connections early: FastAPI dependencies with yield can use scope="function" so the session closes before the response is sent instead of after it.

Full answer

Capacity formula:

max connections used = replicas x workers per replica x (pool_size + max_overflow)

Example: 4 pods x 4 workers x (5 + 5) = 160 possible connections. PostgreSQL's default max_connections is 100, and each connection costs memory (several MB), so this would fail under load. Options: smaller pools, fewer workers, a pooler such as PgBouncer (transaction pooling) between app and database, or a bigger database.

Sizing guidance:

  • Async apps need fewer connections than you think: concurrency is high but most time is spent waiting on I/O in other places. A pool of 5 to 20 per process serves hundreds of concurrent requests if each holds a connection briefly.
  • pool_size: steady connections kept open. max_overflow: temporary extras closed when returned. pool_timeout: how long a request waits for a connection before raising TimeoutError (set it low, e.g. 5 s, so overload becomes fast 503s rather than a pile-up). pool_recycle: replace connections older than N seconds (below firewall or server idle timeouts). pool_pre_ping=True: test connections on checkout to survive restarts and failovers.
  • Little's law: needed connections is about requests per second x average connection hold time. Halving hold time halves the need.
  • Reduce hold time: do not call slow external APIs while holding a session, keep transactions short, avoid lazy N+1 loops, and release early.

Dependency scope (FastAPI 0.121+): by default a yield dependency's exit code runs after the response is sent (scope="request"). A session dependency declared with Depends(get_db, scope="function") exits right after the path function returns, before the response is serialised and sent, so the connection returns to the pool sooner. Use scope="function" for sessions when the response body does not need an open session (all data loaded), and keep the default if streaming responses read from the session.

Monitor: pool checked-out gauge, wait time, pg_stat_activity counts by application name, and errors from pool timeouts. Load test with realistic concurrency before choosing numbers.

python
import asyncio
import sqlite3
import tempfile
from pathlib import Path
from typing import Annotated

from fastapi import Depends, FastAPI
from sqlalchemy import create_engine
from sqlalchemy.exc import TimeoutError as PoolTimeout
from sqlalchemy.pool import QueuePool

path = Path(tempfile.mkdtemp()) / "pool.db"
sqlite3.connect(path).close()
engine = create_engine(f"sqlite:///{path}", poolclass=QueuePool, pool_size=2, max_overflow=1, pool_timeout=0.2, pool_pre_ping=True)

held = [engine.connect() for _ in range(3)]            # 2 pooled + 1 overflow
print("checked out:", engine.pool.checkedout(), "of", engine.pool.size() + 1)
try:
    engine.connect()
except PoolTimeout as exc:
    print("fourth caller:", type(exc).__name__, str(exc).split(" (")[0])
for conn in held:
    conn.close()
print("after release:", engine.pool.checkedout())
print("worst case for 4 pods x 4 workers:", 4 * 4 * (2 + 1), "connections")

events = []


def get_session():
    events.append("session opened")
    yield "session"
    events.append("session closed")


app = FastAPI()


@app.get("/default")
async def default(s: Annotated[str, Depends(get_session)]):
    events.append("handler done")
    return {"ok": True}


@app.get("/early")
async def early(s: Annotated[str, Depends(get_session, scope="function")]):
    events.append("handler done")
    return {"ok": True}


async def call(path):
    scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http",
             "path": path, "raw_path": path.encode(), "query_string": b"", "headers": [], "server": ("t", 80),
             "client": ("127.0.0.1", 1), "root_path": ""}

    async def receive():
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(message):
        if message["type"] == "http.response.body":
            events.append("response sent")

    await app(scope, receive, send)


for p in ("/default", "/early"):
    events.clear()
    asyncio.run(call(p))
    print(p, events)

Standalone script. Run it with `python file.py`; it uses a temporary SQLite file for the pool and drives the ASGI app directly. The scope option on Depends needs a recent FastAPI (0.121 or later). Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): checked out: 3 of 3 fourth caller: TimeoutError QueuePool limit of size 2 overflow 1 reached, connection timed out, timeout 0.20 after release: 0 worst case for 4 pods x 4 workers: 48 connections /default ['session opened', 'handler done', 'response sent', 'session closed'] /early ['session opened', 'handler done', 'session closed', 'response sent']

Key points

  • Total connections = replicas x workers x (pool_size + max_overflow)
  • Stay below max_connections or add PgBouncer
  • Low pool_timeout turns overload into fast failures
  • Hold time drives need: keep transactions short and avoid external calls
  • scope='function' releases the session before the response is sent

Common mistakes

  • Setting pool sizes per process without multiplying by workers and replicas
  • Holding a session open while calling external APIs
  • Very large pools that overload the database
  • No pool_timeout, so overload turns into long hangs
  • Not using pre_ping or recycle behind load balancers that drop idle connections

Follow-ups

  • When would you add PgBouncer, and which pooling mode?
  • How do you detect connection leaks?
  • How does async change pool sizing?

Tips

  • State the formula
  • Mention pool_timeout and pre_ping
  • Mention early release
95.fastapi-0095Hardsenior

How do you harden a FastAPI deployment: TrustedHost, HTTPS redirects, security headers, CORS, body size limits and docs exposure?

Layer defences. Restrict accepted Host headers with TrustedHostMiddleware, terminate HTTPS at a proxy and redirect HTTP (HTTPSRedirectMiddleware or at the proxy), add headers such as Strict-Transport-Security, X-Content-Type-Options and a Content-Security-Policy, configure CORS with explicit origins (never "*" with credentials), enforce request size limits in the proxy and in ASGI middleware, hide docs and OpenAPI in private services, and keep secrets and debug mode out of production.

Full answer

Checklist with reasons:

  • Host validation: TrustedHostMiddleware(allowed_hosts=["api.schoolabe.example"]) blocks Host-header attacks (poisoned password-reset links, cache poisoning). Requests with other hosts get 400.
  • HTTPS: terminate TLS at the load balancer or reverse proxy. Behind a proxy, run Uvicorn with --proxy-headers --forwarded-allow-ips=<proxy ip> so the app sees the real scheme and client IP; trust only your proxy, otherwise clients can spoof X-Forwarded-*. HTTPSRedirectMiddleware answers 307 for http requests, but redirecting at the proxy is usual.
  • Security headers (add through middleware or proxy): Strict-Transport-Security: max-age=31536000; includeSubDomains, X-Content-Type-Options: nosniff, Referrer-Policy, Cache-Control: no-store on sensitive responses, and CSP when serving HTML (APIs mostly return JSON, so focus on HSTS and nosniff).
  • CORS: CORSMiddleware with an explicit allow_origins list. allow_origins=["*"] cannot be combined with credentials; list methods and headers you need. CORS is a browser-side protection, not authentication.
  • Request limits: a body size cap (413) in proxy config and a pure ASGI middleware that counts bytes even for chunked uploads; limits on JSON depth and list lengths in models (max_length), and timeouts.
  • Rate limiting at the gateway (and per-user in the app for login and expensive routes), plus lockouts and monitoring on authentication endpoints.
  • Docs: disable /docs, /redoc and /openapi.json (docs_url=None, ...) for internal or sensitive APIs, or protect them.
  • Errors: do not leak stack traces; return generic 500 bodies, log details with a correlation ID. Keep debug=False.
  • Secrets: environment or secret manager, never in the repo; rotate; least-privilege database users.
  • Dependencies: pin and scan (pip-audit), update FastAPI/Starlette regularly (multipart parsing and path handling have had advisories), run containers as non-root with read-only file systems where possible.
  • Authentication and authorization are separate layers: see JWT validation and object-level authorization.
python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.testclient import TestClient

MAX_BODY = 1024


class SecurityHeaders:
    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)

        async def send_with_headers(message):
            if message["type"] == "http.response.start":
                headers = message.setdefault("headers", [])
                headers += [(b"x-content-type-options", b"nosniff"),
                            (b"strict-transport-security", b"max-age=31536000; includeSubDomains")]
            await send(message)

        await self.app(scope, receive, send_with_headers)


class BodyLimit:
    def __init__(self, app, limit):
        self.app, self.limit = app, limit

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)
        seen = 0
        too_big = False

        async def counted_receive():
            nonlocal seen, too_big
            message = await receive()
            if message["type"] == "http.request":
                seen += len(message.get("body", b""))
                if seen > self.limit:
                    too_big = True
                    return {"type": "http.request", "body": b"", "more_body": False}
            return message

        async def guarded_send(message):
            if too_big and message["type"] == "http.response.start":
                message = {"type": "http.response.start", "status": 413, "headers": [(b"content-type", b"text/plain")]}
            elif too_big and message["type"] == "http.response.body":
                message = {"type": "http.response.body", "body": b"Payload too large"}
            await send(message)

        await self.app(scope, counted_receive, guarded_send)


app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.add_middleware(BodyLimit, limit=MAX_BODY)
app.add_middleware(SecurityHeaders)
app.add_middleware(CORSMiddleware, allow_origins=["https://app.schoolabe.example"], allow_methods=["GET", "POST"], allow_headers=["Authorization"])
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.schoolabe.example"])
app.add_middleware(HTTPSRedirectMiddleware)


@app.post("/echo")
async def echo(payload: dict):
    return {"keys": sorted(payload)}


c = TestClient(app, base_url="https://api.schoolabe.example")
r = c.post("/echo", json={"a": 1})
print(r.status_code, r.json(), r.headers["x-content-type-options"], r.headers["strict-transport-security"])
print("big body:", c.post("/echo", content=b"x" * 5000, headers={"content-type": "application/json"}).status_code)
print("wrong host:", c.post("/echo", json={}, headers={"host": "evil.example"}).status_code)
print("docs hidden:", c.get("/docs").status_code, c.get("/openapi.json").status_code)
http = TestClient(app, base_url="http://api.schoolabe.example", follow_redirects=False)
resp = http.post("/echo", json={})
print("http ->", resp.status_code, resp.headers["location"])
pre = c.options("/echo", headers={"Origin": "https://evil.example", "Access-Control-Request-Method": "POST"})
print("CORS evil origin:", pre.status_code, pre.headers.get("access-control-allow-origin"))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 {'keys': ['a']} nosniff max-age=31536000; includeSubDomains big body: 413 wrong host: 400 docs hidden: 404 404 http -> 307 https://api.schoolabe.example/echo CORS evil origin: 400 None

Key points

  • TrustedHost blocks forged Host headers
  • Trust forwarded headers only from your proxy
  • Explicit CORS origins; CORS is not authentication
  • Enforce body size limits at proxy and in ASGI middleware
  • Hide docs on private APIs; do not leak error details

Common mistakes

  • Using allow_origins=['*'] together with credentials
  • Trusting X-Forwarded headers from any client
  • No request size limit, which allows memory exhaustion
  • Leaving docs and debug output public on private APIs
  • Treating CORS as an authorization mechanism

Follow-ups

  • How do you configure Uvicorn behind nginx or a cloud load balancer?
  • What does a CSP buy an API?
  • How do you rate-limit login endpoints?

Tips

  • Go layer by layer
  • Name Host validation and forwarded headers
  • Mention limits and docs
96.fastapi-0096Hardsenior

How do you detect breaking API changes in FastAPI using OpenAPI snapshots and contract tests in CI?

Export app.openapi() to a committed snapshot file and compare the new schema with the main-branch version in CI. A diff tool classifies changes: removed paths or methods, removed or retyped response fields, new required request parameters or properties, narrowed enums and changed status codes are breaking; added optional fields and new endpoints are not. Fail the build on breaking changes unless the version is bumped deliberately. Add consumer-driven contract tests for critical clients.

Full answer

Why: FastAPI generates the OpenAPI schema from code, so a harmless refactor (renamed field, changed type annotation) silently changes the public contract. Clients and generated SDKs break in production.

Pipeline:

  1. python -c "import json, app; print(json.dumps(app.app.openapi(), indent=2, sort_keys=True))" > openapi.json, committed to the repository. Sorted keys keep diffs readable and stable.
  2. A test regenerates the schema and compares it with the committed snapshot; if different, it fails with a message to update the snapshot (a conscious, reviewed change). This catches unintended changes.
  3. A CI job compares the snapshot with the target branch (or last release) using a diff tool: oasdiff breaking old.json new.json, openapi-diff, or Optic. Breaking changes block the merge unless labelled for a new major version.
  4. Optional: schema-based fuzzing (Schemathesis) runs generated requests against the app (with TestClient or a running service) and checks every response against the declared schema, finding 500s and schema violations.
  5. Consumer-driven contracts (Pact) let important clients publish their expectations, which provider tests verify.

Classification rules (what the custom diff in the snippet checks):

  • Breaking for responses: removed field, type change, field becoming nullable or optional that was required, removed status code that clients depend on, narrowed or widened enums (consumers with exhaustive switches break on new values: document this policy).
  • Breaking for requests: new required parameter or property, removed accepted values, tightened constraints (new maxLength), changed type.
  • Non-breaking: new endpoints, new optional request fields, new response fields (if clients ignore unknown fields), looser constraints on requests.

Keep operationIds stable, since generated clients use them. Use deprecation windows before removals, and keep version-specific routers (/v1) for unavoidable breaks.

python
from fastapi import FastAPI
from pydantic import BaseModel


def build(version):
    app = FastAPI(title="Campus", version=version)

    class StudentV1(BaseModel):
        id: int
        name: str
        marks: int

    class StudentV2(BaseModel):
        id: int
        name: str
        marks: str                              # type change: breaking
        email: str | None = None                # new optional field: fine

    Student = StudentV1 if version == "1" else StudentV2

    @app.get("/students/{sid}")
    def get_student(sid: int) -> Student:
        ...

    if version == "1":
        @app.get("/legacy")
        def legacy():
            return {}

    @app.get("/search")
    def search(q: str = "", page: int | None = None, region: str = "" if version == "1" else ...):
        return []

    return app.openapi()


def resolve(schema, node):
    ref = node.get("$ref")
    return schema["components"]["schemas"][ref.split("/")[-1]] if ref else node


def properties(schema, op):
    body = op["responses"]["200"]["content"]["application/json"]["schema"]
    node = resolve(schema, body)
    return {k: v.get("type") or [t.get("type") for t in v.get("anyOf", [])] for k, v in node.get("properties", {}).items()}


def breaking_changes(old, new):
    problems = []
    for path, methods in old["paths"].items():
        if path not in new["paths"]:
            problems.append(f"removed path {path}")
            continue
        for method, op in methods.items():
            if method not in new["paths"][path]:
                problems.append(f"removed {method.upper()} {path}")
                continue
            new_op = new["paths"][path][method]
            old_params = {p["name"]: p for p in op.get("parameters", [])}
            for p in new_op.get("parameters", []):
                if p.get("required") and (p["name"] not in old_params or not old_params[p["name"]].get("required")):
                    problems.append(f"{method.upper()} {path}: parameter {p['name']!r} became required")
            if "200" in op["responses"] and "content" in op["responses"]["200"]:
                before, after = properties(old, op), properties(new, new_op)
                for field, kind in before.items():
                    if field not in after:
                        problems.append(f"{path}: response field {field!r} removed")
                    elif after[field] != kind:
                        problems.append(f"{path}: response field {field!r} changed {kind} -> {after[field]}")
    return problems


v1, v2 = build("1"), build("2")
for line in breaking_changes(v1, v2):
    print("BREAKING:", line)
print("v1 vs v1:", breaking_changes(v1, v1))
print("added in v2 (not breaking):", sorted(properties(v2, v2["paths"]["/students/{sid}"]["get"])) )

Standalone script. Run it with `python file.py`; it builds two schema versions in memory and diffs them. In CI use a maintained tool such as oasdiff instead of the small diff shown here. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): BREAKING: /students/{sid}: response field 'marks' changed integer -> string BREAKING: removed path /legacy BREAKING: GET /search: parameter 'region' became required v1 vs v1: [] added in v2 (not breaking): ['email', 'id', 'marks', 'name']

Key points

  • Commit a sorted OpenAPI snapshot and fail on unreviewed changes
  • Run a breaking-change diff (oasdiff, openapi-diff) against the main branch
  • New required inputs and removed or retyped outputs are breaking
  • Fuzz with Schemathesis to validate responses against the schema
  • Keep operationIds stable; deprecate before removing

Common mistakes

  • Treating the generated schema as an implementation detail
  • No snapshot or diff in CI
  • Removing fields without a deprecation window
  • Letting operationIds change on refactors
  • Testing only happy paths against the schema

Follow-ups

  • How would you use Schemathesis in CI?
  • How do consumer-driven contracts differ from schema diffs?
  • How should enum additions be treated?

Tips

  • Describe the pipeline
  • Classify breaking vs non-breaking
  • Mention operationId stability
97.fastapi-0097Hardsenior

How do you validate JWT access tokens in FastAPI using RS256, a JWKS endpoint, key rotation, and audience and issuer checks?

Resource servers verify tokens with the issuer's public keys, fetched from a JWKS endpoint and cached, and selected by the kid in the token header. Pin the allowed algorithms (RS256), require exp, iss and aud, and verify them explicitly. Rotation works by publishing the new key beside the old one, signing with the new one, and removing the old one after the longest token lifetime passes. Refresh the JWKS cache on unknown kid, rate-limited.

Full answer

Why RS256 (asymmetric): the issuer (an identity provider such as Auth0, Keycloak or Cognito) signs with a private key; any API can verify with the public key without being able to mint tokens. HS256 shares one secret between signer and verifier, so every verifier could forge tokens.

Validation steps in the API:

  1. Read the unverified header to get kid and alg. Never trust alg from the token: call jwt.decode(..., algorithms=["RS256"]) with a fixed list. This blocks alg: none and HS256 key-confusion attacks (an attacker signing with the public key as an HMAC secret).
  2. Look up the key by kid in a cached JWKS (PyJWKClient(url, cache_keys=True) fetches /.well-known/jwks.json). On an unknown kid, refetch at most every few minutes (rotation), then fail.
  3. Verify the signature and the claims: exp (and nbf) with small leeway, iss equals your issuer exactly, aud includes your API identifier (audience prevents tokens meant for another API being accepted), optionally scope/roles for authorisation and token_use or typ.
  4. Put validated claims in a dependency (Depends(current_claims)) and enforce scopes with Security(current_claims, scopes=[...]). Return 401 with WWW-Authenticate: Bearer for invalid tokens, 403 for insufficient scope.

Key rotation:

  • Add the new public key to the JWKS (two keys with different kid), start signing with the new key, wait until all old tokens expire (max token lifetime plus clock skew), then remove the old key.
  • Emergency revocation of a key: remove it immediately; tokens signed with it fail. Short-lived access tokens (5 to 15 minutes) limit exposure; use refresh tokens, and token introspection or deny lists only where immediate revocation is needed.
  • Cache JWKS with a TTL, and never fetch it on every request (latency and outage risk). Keep serving from the cache if the endpoint is briefly down.

Operational: fetch JWKS over HTTPS only from a configured issuer URL (do not follow a jku header from the token), synchronise clocks (NTP), and never log tokens.

python
import time

import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from jwt import PyJWKSet
from jwt.algorithms import RSAAlgorithm

ISSUER, AUDIENCE = "https://login.schoolabe.example/", "https://api.schoolabe.example"


def new_key():
    private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    pem = private.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
    return pem, private.public_key()


def jwk(public_key, kid):
    d = RSAAlgorithm.to_jwk(public_key, as_dict=True)
    d.update(kid=kid, use="sig", alg="RS256")
    return d


def issue(pem, kid, **overrides):
    claims = {"iss": ISSUER, "aud": AUDIENCE, "sub": "asha", "exp": int(time.time()) + 300, "scope": "grades:read"}
    claims.update(overrides)
    return jwt.encode(claims, pem, algorithm="RS256", headers={"kid": kid})


def verify(token, jwks):
    kid = jwt.get_unverified_header(token)["kid"]
    keys = {k.key_id: k for k in PyJWKSet.from_dict(jwks).keys}
    if kid not in keys:
        return "rejected: unknown kid"
    try:
        claims = jwt.decode(token, keys[kid].key, algorithms=["RS256"], audience=AUDIENCE, issuer=ISSUER,
                            options={"require": ["exp", "iss", "aud"]})
        return f"ok: {claims['sub']}"
    except jwt.InvalidTokenError as exc:
        return f"rejected: {type(exc).__name__}"


pem_a, pub_a = new_key()
jwks = {"keys": [jwk(pub_a, "key-2026-01")]}
token = issue(pem_a, "key-2026-01")
print("valid token:", verify(token, jwks))
print("expired:", verify(issue(pem_a, "key-2026-01", exp=int(time.time()) - 60), jwks))
print("wrong audience:", verify(issue(pem_a, "key-2026-01", aud="https://other-api.example"), jwks))
print("wrong issuer:", verify(issue(pem_a, "key-2026-01", iss="https://evil.example/"), jwks))
print("hs256 with public key as secret:", end=" ")
forged = jwt.encode({"iss": ISSUER, "aud": AUDIENCE, "exp": int(time.time()) + 300}, "not-a-real-secret", algorithm="HS256", headers={"kid": "key-2026-01"})
print(verify(forged, jwks))

pem_b, pub_b = new_key()                                             # rotation: publish both keys
jwks = {"keys": [jwk(pub_a, "key-2026-01"), jwk(pub_b, "key-2026-07")]}
print("old token during rotation:", verify(token, jwks))
print("new token:", verify(issue(pem_b, "key-2026-07"), jwks))
jwks = {"keys": [jwk(pub_b, "key-2026-07")]}                           # old key retired
print("old token after retirement:", verify(token, jwks))

Standalone script. Run it with `python file.py`; it generates throwaway RSA keys. Requires `pip install pyjwt cryptography`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, PyJWT 2.15.1): valid token: ok: asha expired: rejected: ExpiredSignatureError wrong audience: rejected: InvalidAudienceError wrong issuer: rejected: InvalidIssuerError hs256 with public key as secret: rejected: InvalidAlgorithmError old token during rotation: ok: asha new token: ok: asha old token after retirement: rejected: unknown kid

Key points

  • RS256 lets APIs verify without being able to sign
  • Pin algorithms; never trust the token's alg
  • Select the key by kid from a cached JWKS; refetch on unknown kid
  • Verify exp, iss and aud explicitly
  • Rotate by publishing both keys until old tokens expire

Common mistakes

  • Accepting whatever algorithm the token header names
  • Skipping audience or issuer checks
  • Fetching the JWKS on every request or never refreshing it
  • Removing the old key before old tokens expire
  • Following a jku header from an untrusted token
  • Logging full tokens

Follow-ups

  • How do you enforce scopes with Security?
  • How would you revoke a token before it expires?
  • What are the differences between ID tokens and access tokens?

Tips

  • Explain why asymmetric
  • List the claims to verify
  • Describe rotation steps
98.fastapi-0098Hardsenior

What is the transactional outbox pattern and how would you implement it in a FastAPI service to publish events reliably?

Writing to the database and publishing to a broker are two separate systems, so a crash between them loses or duplicates events. With an outbox, the service inserts the event into an outbox table in the same database transaction as the business change, and a separate relay reads unsent rows and publishes them, marking them as sent. Delivery is at least once, so consumers must deduplicate by event ID.

Full answer

The dual-write problem: db.commit() then broker.publish() can fail between the calls (event lost), or publishing first then committing can fail (event announced for data that does not exist).

Outbox design:

  1. Table outbox(id uuid, aggregate_id, type, payload jsonb, created_at, published_at null).
  2. In the request handler, inside one transaction: change business rows and insert the outbox row. Either both commit or neither.
  3. Relay process: loop that selects unpublished rows ordered by id (SELECT ... WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED on PostgreSQL so multiple relays do not collide), publishes each to the broker, then sets published_at. If the process crashes after publishing but before marking, the event is published again: at-least-once delivery.
  4. Consumers keep a table of processed event IDs (unique constraint) and ignore duplicates, or make handlers naturally idempotent.
  5. Preserve ordering per aggregate by partitioning (message key = aggregate id) and processing outbox rows in order.

Alternatives for the relay: polling (simple, adds small latency), or change data capture with Debezium reading the write-ahead log (low latency, no polling load, more infrastructure). Some brokers also support transactional publishing, but that rarely spans the database too.

Operational concerns:

  • Clean up old published rows (partition by date or delete in batches).
  • Monitor the age of the oldest unpublished row, the main health signal.
  • Retries with backoff and a poison-message strategy (park failing events after N attempts).
  • Payload versioning: include a schema_version so consumers evolve safely.
  • In FastAPI, run the relay as a separate worker process or deployment (not inside the web workers), and keep handlers fast: write the outbox row and return.
  • The inbox pattern on the consumer side mirrors this for exactly-once-effect processing.
python
import json
import uuid

from sqlalchemy import create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column


class Base(DeclarativeBase):
    pass


class Order(Base):
    __tablename__ = "orders"
    id: Mapped[int] = mapped_column(primary_key=True)
    item: Mapped[str] = mapped_column(unique=True)


class Outbox(Base):
    __tablename__ = "outbox"
    id: Mapped[int] = mapped_column(primary_key=True)
    event_id: Mapped[str]
    type: Mapped[str]
    payload: Mapped[str]
    published: Mapped[bool] = mapped_column(default=False)


engine = create_engine("sqlite://")
Base.metadata.create_all(engine)


def place_order(item: str):
    with Session(engine) as db, db.begin():                       # one transaction for both writes
        order = Order(item=item)
        db.add(order)
        db.flush()
        db.add(Outbox(event_id=f"evt-{order.id}", type="order.created", payload=json.dumps({"order_id": order.id, "item": item})))


place_order("laptop")
try:
    place_order("laptop")                                          # unique violation: nothing is written, no event either
except Exception as exc:
    print("second order failed:", type(exc).__name__)
place_order("camera")

with Session(engine) as db:
    print("orders:", db.scalars(select(Order.item).order_by(Order.id)).all(), "| outbox rows:", db.scalars(select(Outbox.event_id).order_by(Outbox.id)).all())

delivered: list[str] = []
attempts = {"n": 0}


def publish(row):
    attempts["n"] += 1
    if attempts["n"] == 2:
        raise ConnectionError("broker unavailable")                # simulate a failure on the second publish
    delivered.append(row.event_id)


def relay_once():
    with Session(engine) as db:
        for row in db.scalars(select(Outbox).where(Outbox.published.is_(False)).order_by(Outbox.id)):
            try:
                publish(row)
            except ConnectionError:
                print("relay: publish failed, will retry", row.event_id)
                break                                              # keep order: stop at the first failure
            row.published = True
            db.commit()


relay_once()
relay_once()
print("delivered:", delivered)

seen: set[str] = set()
for event_id in delivered + ["evt-1"]:                              # a duplicate delivery
    print(event_id, "handled" if event_id not in seen else "duplicate ignored")
    seen.add(event_id)

Standalone script. Run it with `python file.py`; it uses an in-memory SQLite database and fakes the broker. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): second order failed: IntegrityError orders: ['laptop', 'camera'] | outbox rows: ['evt-1', 'evt-2'] relay: publish failed, will retry evt-2 delivered: ['evt-1', 'evt-2'] evt-1 handled evt-2 handled evt-1 duplicate ignored

Key points

  • Write the event into an outbox table within the same transaction
  • A relay publishes unsent rows and marks them
  • Delivery is at least once; consumers deduplicate by event ID
  • SKIP LOCKED lets several relays work safely; CDC is an alternative
  • Monitor the age of the oldest unpublished event

Common mistakes

  • Publishing to the broker inside the request before or after commit without an outbox
  • Assuming exactly-once delivery from the relay
  • Running the relay inside web workers
  • Never cleaning up published rows
  • Ignoring ordering for events of the same aggregate

Follow-ups

  • How does Debezium CDC compare with polling?
  • How would you implement an inbox table for consumers?
  • How do you handle poison messages?

Tips

  • Explain the dual-write problem
  • Say at-least-once with idempotent consumers
  • Mention monitoring lag
99.fastapi-0099Hardsenior

How do you run FastAPI in production with Gunicorn and UvicornWorker, and which settings matter for workers, timeouts and graceful restarts?

Gunicorn acts as a process manager that forks several Uvicorn worker processes (class uvicorn_worker.UvicornWorker, from the uvicorn-worker package), restarts crashed workers and handles signals. Key settings are workers (about one per CPU core to start), timeout (heartbeat) and graceful_timeout, keepalive, max_requests with jitter against memory growth, preload_app for copy-on-write memory savings, and bind to a socket or port behind a reverse proxy. In containers, many teams run plain Uvicorn per container and scale with the orchestrator instead.

Full answer

Why a manager: a single Uvicorn process uses one CPU core (the event loop is single threaded). Multiple processes use all cores and provide crash recovery.

Options:

  • uvicorn app:app --workers 4: simple supervisor built in. Fine for many cases; fewer production knobs.
  • gunicorn -k uvicorn_worker.UvicornWorker app:app: mature process management (rolling restarts with SIGHUP, max_requests, worker timeouts, hooks). The old uvicorn.workers module is deprecated in favour of the separate uvicorn-worker package.
  • Containers on Kubernetes or ECS: often one Uvicorn process per container with resource limits and replicas for scaling, so the orchestrator handles restarts and rolling updates. Multiple workers per container make CPU limits and memory accounting less precise.

Important Gunicorn settings (gunicorn.conf.py):

  • workers: start around CPU cores (or 2 x cores + 1 for sync apps; async apps need fewer). Each worker loads the app, so memory is multiplied.
  • worker_class = "uvicorn_worker.UvicornWorker".
  • bind: 0.0.0.0:8000 in containers or a unix socket behind nginx.
  • timeout: with async workers it is a heartbeat from the worker to the master (default 30 s); a blocked event loop that stops heartbeating gets killed. It is not a per-request limit.
  • graceful_timeout: time workers get to finish in-flight requests on restart or shutdown.
  • keepalive: keep-alive seconds, set above the load balancer's idle timeout to avoid 502s on reused connections.
  • max_requests and max_requests_jitter: recycle workers periodically to contain slow leaks, staggered so they do not all restart together.
  • preload_app: import the app in the master before forking to share memory (copy-on-write); do not open database pools or threads at import time, create them in lifespan.
  • forwarded_allow_ips or Uvicorn --forwarded-allow-ips behind a proxy.
  • Logging: send access and error logs to stdout and stderr for the platform.

Shutdown: SIGTERM makes the master stop accepting, wait up to graceful_timeout, run lifespan shutdown in each worker, then exit. Match the orchestrator's termination grace period to this. Health checks, readiness and resource limits complete the setup.

python
import os
import signal
import socket
import subprocess
import sys
import tempfile
import textwrap
import time
from pathlib import Path

import httpx

work = Path(tempfile.mkdtemp())
with socket.socket() as s:
    s.bind(("127.0.0.1", 0))
    port = s.getsockname()[1]

(work / "main.py").write_text(textwrap.dedent("""
    import os
    from fastapi import FastAPI
    app = FastAPI()

    @app.get("/ping")
    async def ping():
        return {"pong": True}
"""))
(work / "gunicorn.conf.py").write_text(textwrap.dedent(f"""
    bind = "127.0.0.1:{port}"
    workers = 2
    worker_class = "uvicorn_worker.UvicornWorker"
    timeout = 30
    graceful_timeout = 20
    keepalive = 75
    max_requests = 1000
    max_requests_jitter = 100
    accesslog = None
    errorlog = "-"
    loglevel = "warning"
"""))

check = subprocess.run([sys.executable, "-m", "gunicorn", "--check-config", "-c", "gunicorn.conf.py", "main:app"],
                       cwd=work, capture_output=True, text=True)
print("config check exit code:", check.returncode)

proc = subprocess.Popen([sys.executable, "-m", "gunicorn", "-c", "gunicorn.conf.py", "main:app"],
                        cwd=work, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
    deadline = time.time() + 30
    while time.time() < deadline:
        try:
            reply = httpx.get(f"http://127.0.0.1:{port}/ping", timeout=1)
            break
        except httpx.TransportError:
            time.sleep(0.2)
    print("response:", reply.status_code, reply.json())
    while time.time() < deadline:
        children = Path(f"/proc/{proc.pid}/task/{proc.pid}/children").read_text().split()
        if len(children) == 2:
            break
        time.sleep(0.2)
    print("worker processes under the master:", len(children))
finally:
    proc.send_signal(signal.SIGTERM)                       # graceful shutdown
    print("master exit code after SIGTERM:", proc.wait(timeout=30))

Standalone script that starts a real Gunicorn server on a free local port, calls it once and stops it. Linux only (it reads /proc). Requires `pip install fastapi gunicorn uvicorn-worker httpx`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, gunicorn 27.0.1, uvicorn-worker 0.4.0): config check exit code: 0 response: 200 {'pong': True} worker processes under the master: 2 master exit code after SIGTERM: 0

Key points

  • Gunicorn manages processes; UvicornWorker runs the ASGI app
  • Use the uvicorn-worker package; uvicorn.workers is deprecated
  • timeout is a heartbeat for async workers, not a request limit
  • max_requests with jitter recycles workers; keepalive above the LB idle time
  • In containers, one Uvicorn per container with orchestrator scaling is common

Common mistakes

  • Running many workers per container with tight CPU limits
  • Treating Gunicorn timeout as a per-request limit
  • Opening pools at import time with preload_app
  • keepalive lower than the load balancer idle timeout causing 502s
  • Using the deprecated uvicorn.workers module

Follow-ups

  • When would you choose plain Uvicorn per container?
  • What does preload_app change?
  • How do you do zero-downtime deploys with Gunicorn?

Tips

  • Explain why a process manager
  • Name 4 settings
  • Mention graceful shutdown
100.fastapi-0100Hardsenior

How do you prevent broken object level authorization (BOLA, also called IDOR) in FastAPI endpoints?

BOLA happens when an authenticated user can read or change another user's object by changing an ID in the URL, because the code checks who the caller is but not whether the object belongs to them. Prevent it by centralising ownership checks in a dependency that loads the object scoped to the current user (or tenant) and returns 404 otherwise, filtering list queries the same way, using policy functions for roles, and testing cross-user access for every route.

Full answer

BOLA is first in the OWASP API Security Top 10. Authentication ("who are you?") does not imply authorization ("may you touch this record?"). Hard-to-guess IDs (UUIDs) reduce guessing but are not a control: IDs leak through logs, links and other endpoints.

Defences:

  1. Scope queries by owner at the data access layer: select(Note).where(Note.id == note_id, Note.owner_id == user.id). If no row is returned, respond 404 (not 403) so you do not reveal that the object exists. Return 403 only when the existence is public and the action is forbidden.
  2. Put the pattern in a reusable dependency:
python
def owned_note(note_id: int, user: CurrentUser, db: DB) -> Note:
    note = db.scalar(select(Note).where(Note.id == note_id, Note.owner_id == user.id))
    if note is None:
        raise HTTPException(404, "Note not found")
    return note

Every route that takes note_id declares note: Annotated[Note, Depends(owned_note)], so developers cannot forget the check and the code stays DRY. For shared resources, a policy function decides: can(user, "edit", note) based on ownership, team membership or role. 3. Apply the same scope to list, search, export and aggregate endpoints, and to nested resources (/classes/{id}/students/{sid} must verify both). 4. Never accept the owner or tenant from the request body (owner_id in JSON): derive it from the token. Use separate input and output models (mass assignment protection). 5. Admin access: explicit role checks with audit logging. 6. Background jobs and webhooks need the same checks, since they act on behalf of users. 7. In multi-tenant systems add database-level protection, such as PostgreSQL Row-Level Security. 8. Test: for each endpoint create objects as user A and assert user B receives 404 for read, update and delete, and list never includes A's data. Automate with parametrised tests over the OpenAPI routes, and add authorization tests to code review checklists.

Related: BFLA (broken function level authorization, such as normal users calling admin endpoints) needs role or scope checks per route.

python
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel

NOTES = {1: {"id": 1, "owner": "asha", "text": "asha private"}, 2: {"id": 2, "owner": "ravi", "text": "ravi private"}}
TOKENS = {"token-asha": "asha", "token-ravi": "ravi"}                       # stand-in for real JWT validation
app = FastAPI()


def current_user(authorization: Annotated[str, Header()] = "") -> str:
    user = TOKENS.get(authorization.removeprefix("Bearer "))
    if user is None:
        raise HTTPException(401, "Invalid credentials", headers={"WWW-Authenticate": "Bearer"})
    return user


User = Annotated[str, Depends(current_user)]


def owned_note(note_id: int, user: User) -> dict:
    note = NOTES.get(note_id)
    if note is None or note["owner"] != user:                              # same answer for "missing" and "not yours"
        raise HTTPException(404, "Note not found")
    return note


class NoteUpdate(BaseModel):
    text: str                                                              # no owner field: it cannot be set by clients


@app.get("/notes")
def list_notes(user: User):
    return [n["text"] for n in NOTES.values() if n["owner"] == user]


@app.get("/notes/{note_id}")
def read(note: Annotated[dict, Depends(owned_note)]):
    return note


@app.put("/notes/{note_id}")
def update(body: NoteUpdate, note: Annotated[dict, Depends(owned_note)]):
    note["text"] = body.text
    return note


# Vulnerable version for comparison: authenticates but never checks ownership
@app.get("/unsafe/notes/{note_id}")
def unsafe_read(note_id: int, user: User):
    return NOTES[note_id]


c = TestClient(app)
asha, ravi = {"Authorization": "Bearer token-asha"}, {"Authorization": "Bearer token-ravi"}
print("own note:", c.get("/notes/1", headers=asha).status_code)
print("someone else's note:", c.get("/notes/2", headers=asha).status_code, "| missing note:", c.get("/notes/99", headers=asha).status_code)
print("update other's note:", c.put("/notes/2", json={"text": "hacked"}, headers=asha).status_code, "| text now:", NOTES[2]["text"])
print("list is scoped:", c.get("/notes", headers=ravi).json())
print("owner field ignored on update:", c.put("/notes/1", json={"text": "edited", "owner": "ravi"}, headers=asha).json())
print("unsafe route leaks:", c.get("/unsafe/notes/2", headers=asha).json()["text"])
print("no token:", c.get("/notes/1").status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): own note: 200 someone else's note: 404 | missing note: 404 update other's note: 404 | text now: ravi private list is scoped: ['ravi private'] owner field ignored on update: {'id': 1, 'owner': 'asha', 'text': 'edited'} unsafe route leaks: ravi private no token: 401

Key points

  • Authentication does not imply authorization for a specific object
  • Load objects scoped to the current user in a shared dependency
  • Return 404 for objects the caller may not know exist
  • Filter lists and nested resources the same way
  • Derive owner or tenant from the token and test cross-user access

Common mistakes

  • Checking authentication but not ownership
  • Relying on unguessable UUIDs as the only protection
  • Returning 403 and revealing which IDs exist
  • Accepting owner_id or tenant_id from the request body
  • Scoping single-object routes but forgetting list, export and nested routes

Follow-ups

  • How does PostgreSQL row-level security complement this?
  • How would you model team-shared objects?
  • What is BFLA and how does it differ?

Tips

  • Show the ownership dependency
  • Say 404 over 403
  • Mention cross-user tests