Choosing Uvicorn worker count in production
WHAT IT TESTS: Sizing process parallelism. OUTLINE: workers exist to use multiple CPU cores past the GIL; a common starting point ties count to cores, then you tune by load testing, balancing CPU and memory (each worker is a full copy) against connection-pool…
Reading the full response body in middleware
WHAT IT TESTS: Understanding ASGI's streaming send model. OUTLINE: responses stream as multiple body messages and headers go first, so you cannot add a header after seeing the body; you must buffer all chunks, compute the hash, set the header, then resend.
OAuth2 social login with your own JWT
WHAT IT TESTS: The authorization code flow end to end. OUTLINE: a login endpoint redirects to the provider with a state param, a callback exchanges the code for the provider token, you fetch the user profile, upsert the local user, then mint your own JWT.
selectinload vs joinedload for eager loading
WHAT IT TESTS: Eager loading to kill N+1 queries. OUTLINE: use eager loading options to avoid lazy N+1; joinedload uses a single JOIN (good for many-to-one) but can fan out rows on collections; selectinload issues a second IN query (better for one-to-many).
Feature-based vs layer-based project structure
WHAT IT TESTS: Structuring code for scale. OUTLINE: layer-based groups by technical role and is simple early but scatters a feature across folders; feature-based groups by domain, improving cohesion and ownership at the cost of some duplication and…
Streaming large file downloads efficiently
WHAT IT TESTS: Memory-safe file delivery. OUTLINE: use StreamingResponse with a generator that yields chunks (or FileResponse for an on-disk file), set media_type and a Content-Disposition header, so memory stays flat regardless of file size.
Pydantic computed fields in response models
WHAT IT TESTS: Deriving output-only fields. OUTLINE: a @computed_field decorated property is excluded from input and validation but included in serialization and the OpenAPI schema, ideal for values like full_name derived from other fields.
Mapping camelCase JSON to snake_case Pydantic fields
WHAT IT TESTS: Pydantic field aliasing across the JSON boundary. OUTLINE: set an alias_generator (to_camel) plus populate_by_name in model config, accept aliases on input, and serialize with by_alias=True so responses come out camelCase.
Pydantic BaseModel vs dataclasses in FastAPI
WHAT IT TESTS: Why FastAPI standardizes on Pydantic. OUTLINE: BaseModel validates and coerces data at runtime, parses and serializes JSON, integrates with OpenAPI schema generation, and supports rich validators; dataclasses only store data with no validation.
Testing a DB endpoint via dependency override
WHAT IT TESTS: Isolating tests from production data. OUTLINE: use app.dependency_overrides to swap the real get_db for one yielding a test database session, run against a disposable SQLite or test Postgres, and assert through TestClient.
Secure refresh token flow for access renewal
WHAT IT TESTS: Designing the access plus refresh token pattern. OUTLINE: short-lived access token, longer-lived refresh token stored server-side, a refresh endpoint that validates and rotates the refresh token issuing a new pair.
Zero-downtime blue-green deploys on Kubernetes
WHAT IT TESTS: Safe deploys with no dropped requests. OUTLINE: run blue and green deployments, switch a Service or ingress selector to the new color after readiness probes pass, drain old pods gracefully, and handle backward-compatible DB migrations.
Limits of BackgroundTasks vs Celery or ARQ
WHAT IT TESTS: Knowing when in-process tasks are not enough. OUTLINE: BackgroundTasks run in the same worker with no persistence, retries, or visibility, and die with the process; Celery or ARQ add durability, retries, scheduling, and separate workers.
Diagnosing a slow FastAPI endpoint under load
WHAT IT TESTS: Systematic performance diagnosis. OUTLINE: add timing and tracing to isolate the slow span, watch CPU vs wait time and event-loop lag, then use profilers like py-spy or cProfile and DB EXPLAIN.
WebSocket connection manager and broadcast
WHAT IT TESTS: Managing WebSocket lifecycle and fan-out. OUTLINE: a manager class holding a list of active connections, connect accepts and appends, disconnect removes, broadcast iterates sending to each, all wrapped in try/finally to handle disconnects.
BackgroundTasks dependency vs response.background
WHAT IT TESTS: Two ways to defer work after a response. OUTLINE: the injected BackgroundTasks parameter lets endpoints and dependencies stack tasks and is the common path; response.background attaches a single Starlette task when you return a Response object…
Propagating a correlation ID without parameter passing
WHAT IT TESTS: Ambient request-scoped context in async code. OUTLINE: middleware reads or generates the header, stores it in a contextvars.ContextVar, service code reads it anywhere, and logging filters inject it.
Revoking stateless JWTs on logout
WHAT IT TESTS: Reconciling stateless tokens with real revocation. OUTLINE: a server-side denylist of revoked token IDs checked per request, or short-lived access tokens paired with revocable refresh tokens.
SQLAlchemy connection pooling across Uvicorn workers
WHAT IT TESTS: Connection pool sizing under multi-process concurrency. OUTLINE: each worker has its own pool; total DB connections equal workers times (pool_size plus max_overflow); overflow connections are temporary; misconfiguration exhausts DB…
MongoDB async ODM vs SQLAlchemy sessions
WHAT IT TESTS: NoSQL data access in async FastAPI. OUTLINE: Motor client as a connection pool with no SQLAlchemy-style session or transaction; Beanie document models over Motor; initialize once at startup and await find queries.